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"
34 #include "property-details.h"
35 #include "smart-array-pointer.h"
36 #include "unicode-inl.h"
37 #if V8_TARGET_ARCH_ARM
38 #include "arm/constants-arm.h"
39 #elif V8_TARGET_ARCH_MIPS
40 #include "mips/constants-mips.h"
46 // Most object types in the V8 JavaScript are described in this file.
48 // Inheritance hierarchy:
49 // - MaybeObject (an object or a failure)
50 // - Failure (immediate for marking failed operation)
52 // - Smi (immediate small integer)
53 // - HeapObject (superclass for everything allocated in the heap)
54 // - JSReceiver (suitable for property access)
79 // - CompilationCacheTable
80 // - CodeCacheHashTable
83 // - JSFunctionResultCache
87 // - ExternalPixelArray
88 // - ExternalByteArray
89 // - ExternalUnsignedByteArray
90 // - ExternalShortArray
91 // - ExternalUnsignedShortArray
93 // - ExternalUnsignedIntArray
94 // - ExternalFloatArray
102 // - ExternalAsciiString
103 // - ExternalTwoByteString
109 // - SharedFunctionInfo
117 // - FunctionTemplateInfo
118 // - ObjectTemplateInfo
126 // Formats of Object*:
127 // Smi: [31 bit signed int] 0
128 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
129 // Failure: [30 bit signed int] 11
135 // The "fast" kind for elements that only contain SMI values. Must be first
136 // to make it possible to efficiently check maps for this kind.
137 FAST_SMI_ONLY_ELEMENTS,
139 // The "fast" kind for tagged values. Must be second to make it possible to
140 // efficiently check maps for this and the FAST_SMI_ONLY_ELEMENTS kind
144 // The "fast" kind for unwrapped, non-tagged double values.
145 FAST_DOUBLE_ELEMENTS,
149 NON_STRICT_ARGUMENTS_ELEMENTS,
150 // The "fast" kind for external arrays
151 EXTERNAL_BYTE_ELEMENTS,
152 EXTERNAL_UNSIGNED_BYTE_ELEMENTS,
153 EXTERNAL_SHORT_ELEMENTS,
154 EXTERNAL_UNSIGNED_SHORT_ELEMENTS,
155 EXTERNAL_INT_ELEMENTS,
156 EXTERNAL_UNSIGNED_INT_ELEMENTS,
157 EXTERNAL_FLOAT_ELEMENTS,
158 EXTERNAL_DOUBLE_ELEMENTS,
159 EXTERNAL_PIXEL_ELEMENTS,
161 // Derived constants from ElementsKind
162 FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_BYTE_ELEMENTS,
163 LAST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS,
164 FIRST_ELEMENTS_KIND = FAST_SMI_ONLY_ELEMENTS,
165 LAST_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS
168 enum CompareMapMode {
170 ALLOW_ELEMENT_TRANSITION_MAPS
173 enum KeyedAccessGrowMode {
174 DO_NOT_ALLOW_JSARRAY_GROWTH,
178 const int kElementsKindCount = LAST_ELEMENTS_KIND - FIRST_ELEMENTS_KIND + 1;
180 void PrintElementsKind(FILE* out, ElementsKind kind);
182 inline bool IsMoreGeneralElementsKindTransition(ElementsKind from_kind,
183 ElementsKind to_kind);
185 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
186 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
189 // PropertyNormalizationMode is used to specify whether to keep
190 // inobject properties when normalizing properties of a JSObject.
191 enum PropertyNormalizationMode {
192 CLEAR_INOBJECT_PROPERTIES,
193 KEEP_INOBJECT_PROPERTIES
197 // NormalizedMapSharingMode is used to specify whether a map may be shared
198 // by different objects with normalized properties.
199 enum NormalizedMapSharingMode {
200 UNIQUE_NORMALIZED_MAP,
201 SHARED_NORMALIZED_MAP
205 // Indicates whether a get method should implicitly create the object looked up.
212 // Instance size sentinel for objects of variable size.
213 const int kVariableSizeSentinel = 0;
216 // All Maps have a field instance_type containing a InstanceType.
217 // It describes the type of the instances.
219 // As an example, a JavaScript object is a heap object and its map
220 // instance_type is JS_OBJECT_TYPE.
222 // The names of the string instance types are intended to systematically
223 // mirror their encoding in the instance_type field of the map. The default
224 // encoding is considered TWO_BYTE. It is not mentioned in the name. ASCII
225 // encoding is mentioned explicitly in the name. Likewise, the default
226 // representation is considered sequential. It is not mentioned in the
227 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
228 // mentioned. Finally, the string is either a SYMBOL_TYPE (if it is a
229 // symbol) or a STRING_TYPE (if it is not a symbol).
231 // NOTE: The following things are some that depend on the string types having
232 // instance_types that are less than those of all other types:
233 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
236 // NOTE: Everything following JS_VALUE_TYPE is considered a
237 // JSObject for GC purposes. The first four entries here have typeof
238 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
239 #define INSTANCE_TYPE_LIST_ALL(V) \
241 V(ASCII_SYMBOL_TYPE) \
242 V(CONS_SYMBOL_TYPE) \
243 V(CONS_ASCII_SYMBOL_TYPE) \
244 V(EXTERNAL_SYMBOL_TYPE) \
245 V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE) \
246 V(EXTERNAL_ASCII_SYMBOL_TYPE) \
247 V(SHORT_EXTERNAL_SYMBOL_TYPE) \
248 V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE) \
249 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE) \
251 V(ASCII_STRING_TYPE) \
252 V(CONS_STRING_TYPE) \
253 V(CONS_ASCII_STRING_TYPE) \
254 V(SLICED_STRING_TYPE) \
255 V(EXTERNAL_STRING_TYPE) \
256 V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE) \
257 V(EXTERNAL_ASCII_STRING_TYPE) \
258 V(SHORT_EXTERNAL_STRING_TYPE) \
259 V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE) \
260 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
261 V(PRIVATE_EXTERNAL_ASCII_STRING_TYPE) \
266 V(JS_GLOBAL_PROPERTY_CELL_TYPE) \
268 V(HEAP_NUMBER_TYPE) \
272 /* Note: the order of these external array */ \
273 /* types is relied upon in */ \
274 /* Object::IsExternalArray(). */ \
275 V(EXTERNAL_BYTE_ARRAY_TYPE) \
276 V(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE) \
277 V(EXTERNAL_SHORT_ARRAY_TYPE) \
278 V(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE) \
279 V(EXTERNAL_INT_ARRAY_TYPE) \
280 V(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE) \
281 V(EXTERNAL_FLOAT_ARRAY_TYPE) \
282 V(EXTERNAL_PIXEL_ARRAY_TYPE) \
285 V(ACCESSOR_INFO_TYPE) \
286 V(ACCESSOR_PAIR_TYPE) \
287 V(ACCESS_CHECK_INFO_TYPE) \
288 V(INTERCEPTOR_INFO_TYPE) \
289 V(CALL_HANDLER_INFO_TYPE) \
290 V(FUNCTION_TEMPLATE_INFO_TYPE) \
291 V(OBJECT_TEMPLATE_INFO_TYPE) \
292 V(SIGNATURE_INFO_TYPE) \
293 V(TYPE_SWITCH_INFO_TYPE) \
296 V(POLYMORPHIC_CODE_CACHE_TYPE) \
297 V(TYPE_FEEDBACK_INFO_TYPE) \
298 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
300 V(FIXED_ARRAY_TYPE) \
301 V(FIXED_DOUBLE_ARRAY_TYPE) \
302 V(SHARED_FUNCTION_INFO_TYPE) \
304 V(JS_MESSAGE_OBJECT_TYPE) \
309 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
311 V(JS_GLOBAL_OBJECT_TYPE) \
312 V(JS_BUILTINS_OBJECT_TYPE) \
313 V(JS_GLOBAL_PROXY_TYPE) \
316 V(JS_WEAK_MAP_TYPE) \
319 V(JS_FUNCTION_TYPE) \
320 V(JS_FUNCTION_PROXY_TYPE) \
322 #ifdef ENABLE_DEBUGGER_SUPPORT
323 #define INSTANCE_TYPE_LIST_DEBUGGER(V) \
325 V(BREAK_POINT_INFO_TYPE)
327 #define INSTANCE_TYPE_LIST_DEBUGGER(V)
330 #define INSTANCE_TYPE_LIST(V) \
331 INSTANCE_TYPE_LIST_ALL(V) \
332 INSTANCE_TYPE_LIST_DEBUGGER(V)
335 // Since string types are not consecutive, this macro is used to
336 // iterate over them.
337 #define STRING_TYPE_LIST(V) \
339 kVariableSizeSentinel, \
342 V(ASCII_SYMBOL_TYPE, \
343 kVariableSizeSentinel, \
346 V(CONS_SYMBOL_TYPE, \
350 V(CONS_ASCII_SYMBOL_TYPE, \
354 V(EXTERNAL_SYMBOL_TYPE, \
355 ExternalTwoByteString::kSize, \
358 V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE, \
359 ExternalTwoByteString::kSize, \
360 external_symbol_with_ascii_data, \
361 ExternalSymbolWithAsciiData) \
362 V(EXTERNAL_ASCII_SYMBOL_TYPE, \
363 ExternalAsciiString::kSize, \
364 external_ascii_symbol, \
365 ExternalAsciiSymbol) \
366 V(SHORT_EXTERNAL_SYMBOL_TYPE, \
367 ExternalTwoByteString::kShortSize, \
368 short_external_symbol, \
369 ShortExternalSymbol) \
370 V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE, \
371 ExternalTwoByteString::kShortSize, \
372 short_external_symbol_with_ascii_data, \
373 ShortExternalSymbolWithAsciiData) \
374 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE, \
375 ExternalAsciiString::kShortSize, \
376 short_external_ascii_symbol, \
377 ShortExternalAsciiSymbol) \
379 kVariableSizeSentinel, \
382 V(ASCII_STRING_TYPE, \
383 kVariableSizeSentinel, \
386 V(CONS_STRING_TYPE, \
390 V(CONS_ASCII_STRING_TYPE, \
394 V(SLICED_STRING_TYPE, \
395 SlicedString::kSize, \
398 V(SLICED_ASCII_STRING_TYPE, \
399 SlicedString::kSize, \
400 sliced_ascii_string, \
402 V(EXTERNAL_STRING_TYPE, \
403 ExternalTwoByteString::kSize, \
406 V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE, \
407 ExternalTwoByteString::kSize, \
408 external_string_with_ascii_data, \
409 ExternalStringWithAsciiData) \
410 V(EXTERNAL_ASCII_STRING_TYPE, \
411 ExternalAsciiString::kSize, \
412 external_ascii_string, \
413 ExternalAsciiString) \
414 V(SHORT_EXTERNAL_STRING_TYPE, \
415 ExternalTwoByteString::kShortSize, \
416 short_external_string, \
417 ShortExternalString) \
418 V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE, \
419 ExternalTwoByteString::kShortSize, \
420 short_external_string_with_ascii_data, \
421 ShortExternalStringWithAsciiData) \
422 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
423 ExternalAsciiString::kShortSize, \
424 short_external_ascii_string, \
425 ShortExternalAsciiString)
427 // A struct is a simple object a set of object-valued fields. Including an
428 // object type in this causes the compiler to generate most of the boilerplate
429 // code for the class including allocation and garbage collection routines,
430 // casts and predicates. All you need to define is the class, methods and
431 // object verification routines. Easy, no?
433 // Note that for subtle reasons related to the ordering or numerical values of
434 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
436 #define STRUCT_LIST_ALL(V) \
437 V(ACCESSOR_INFO, AccessorInfo, accessor_info) \
438 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
439 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
440 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
441 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
442 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
443 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
444 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
445 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
446 V(SCRIPT, Script, script) \
447 V(CODE_CACHE, CodeCache, code_cache) \
448 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
449 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
450 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
452 #ifdef ENABLE_DEBUGGER_SUPPORT
453 #define STRUCT_LIST_DEBUGGER(V) \
454 V(DEBUG_INFO, DebugInfo, debug_info) \
455 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
457 #define STRUCT_LIST_DEBUGGER(V)
460 #define STRUCT_LIST(V) \
462 STRUCT_LIST_DEBUGGER(V)
464 // We use the full 8 bits of the instance_type field to encode heap object
465 // instance types. The high-order bit (bit 7) is set if the object is not a
466 // string, and cleared if it is a string.
467 const uint32_t kIsNotStringMask = 0x80;
468 const uint32_t kStringTag = 0x0;
469 const uint32_t kNotStringTag = 0x80;
471 // Bit 6 indicates that the object is a symbol (if set) or not (if cleared).
472 // There are not enough types that the non-string types (with bit 7 set) can
473 // have bit 6 set too.
474 const uint32_t kIsSymbolMask = 0x40;
475 const uint32_t kNotSymbolTag = 0x0;
476 const uint32_t kSymbolTag = 0x40;
478 // If bit 7 is clear then bit 2 indicates whether the string consists of
479 // two-byte characters or one-byte characters.
480 const uint32_t kStringEncodingMask = 0x4;
481 const uint32_t kTwoByteStringTag = 0x0;
482 const uint32_t kAsciiStringTag = 0x4;
484 // If bit 7 is clear, the low-order 2 bits indicate the representation
486 const uint32_t kStringRepresentationMask = 0x03;
487 enum StringRepresentationTag {
489 kConsStringTag = 0x1,
490 kExternalStringTag = 0x2,
491 kSlicedStringTag = 0x3
493 const uint32_t kIsIndirectStringMask = 0x1;
494 const uint32_t kIsIndirectStringTag = 0x1;
495 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
496 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
498 (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
500 (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
502 // Use this mask to distinguish between cons and slice only after making
503 // sure that the string is one of the two (an indirect string).
504 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
505 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
507 // If bit 7 is clear, then bit 3 indicates whether this two-byte
508 // string actually contains ASCII data.
509 const uint32_t kAsciiDataHintMask = 0x08;
510 const uint32_t kAsciiDataHintTag = 0x08;
512 // If bit 7 is clear and string representation indicates an external string,
513 // then bit 4 indicates whether the data pointer is cached.
514 const uint32_t kShortExternalStringMask = 0x10;
515 const uint32_t kShortExternalStringTag = 0x10;
518 // A ConsString with an empty string as the right side is a candidate
519 // for being shortcut by the garbage collector unless it is a
520 // symbol. It's not common to have non-flat symbols, so we do not
521 // shortcut them thereby avoiding turning symbols into strings. See
522 // heap.cc and mark-compact.cc.
523 const uint32_t kShortcutTypeMask =
526 kStringRepresentationMask;
527 const uint32_t kShortcutTypeTag = kConsStringTag;
532 SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kSeqStringTag,
533 ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kSeqStringTag,
534 CONS_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kConsStringTag,
535 CONS_ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kConsStringTag,
536 SHORT_EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag |
537 kExternalStringTag | kShortExternalStringTag,
538 SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
539 kTwoByteStringTag | kSymbolTag | kExternalStringTag |
540 kAsciiDataHintTag | kShortExternalStringTag,
541 SHORT_EXTERNAL_ASCII_SYMBOL_TYPE = kAsciiStringTag | kExternalStringTag |
542 kSymbolTag | kShortExternalStringTag,
543 EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kExternalStringTag,
544 EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
545 kTwoByteStringTag | kSymbolTag | kExternalStringTag | kAsciiDataHintTag,
546 EXTERNAL_ASCII_SYMBOL_TYPE =
547 kAsciiStringTag | kSymbolTag | kExternalStringTag,
548 STRING_TYPE = kTwoByteStringTag | kSeqStringTag,
549 ASCII_STRING_TYPE = kAsciiStringTag | kSeqStringTag,
550 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag,
551 CONS_ASCII_STRING_TYPE = kAsciiStringTag | kConsStringTag,
552 SLICED_STRING_TYPE = kTwoByteStringTag | kSlicedStringTag,
553 SLICED_ASCII_STRING_TYPE = kAsciiStringTag | kSlicedStringTag,
554 SHORT_EXTERNAL_STRING_TYPE =
555 kTwoByteStringTag | kExternalStringTag | kShortExternalStringTag,
556 SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
557 kTwoByteStringTag | kExternalStringTag |
558 kAsciiDataHintTag | kShortExternalStringTag,
559 SHORT_EXTERNAL_ASCII_STRING_TYPE =
560 kAsciiStringTag | kExternalStringTag | kShortExternalStringTag,
561 EXTERNAL_STRING_TYPE = kTwoByteStringTag | kExternalStringTag,
562 EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
563 kTwoByteStringTag | kExternalStringTag | kAsciiDataHintTag,
565 EXTERNAL_ASCII_STRING_TYPE = kAsciiStringTag | kExternalStringTag,
566 PRIVATE_EXTERNAL_ASCII_STRING_TYPE = EXTERNAL_ASCII_STRING_TYPE,
568 // Objects allocated in their own spaces (never in new space).
569 MAP_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE
572 JS_GLOBAL_PROPERTY_CELL_TYPE,
574 // "Data", objects that cannot contain non-map-word pointers to heap
580 EXTERNAL_BYTE_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
581 EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
582 EXTERNAL_SHORT_ARRAY_TYPE,
583 EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
584 EXTERNAL_INT_ARRAY_TYPE,
585 EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
586 EXTERNAL_FLOAT_ARRAY_TYPE,
587 EXTERNAL_DOUBLE_ARRAY_TYPE,
588 EXTERNAL_PIXEL_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
589 FIXED_DOUBLE_ARRAY_TYPE,
590 FILLER_TYPE, // LAST_DATA_TYPE
595 ACCESS_CHECK_INFO_TYPE,
596 INTERCEPTOR_INFO_TYPE,
597 CALL_HANDLER_INFO_TYPE,
598 FUNCTION_TEMPLATE_INFO_TYPE,
599 OBJECT_TEMPLATE_INFO_TYPE,
601 TYPE_SWITCH_INFO_TYPE,
604 POLYMORPHIC_CODE_CACHE_TYPE,
605 TYPE_FEEDBACK_INFO_TYPE,
606 ALIASED_ARGUMENTS_ENTRY_TYPE,
607 // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
608 // is defined. However as include/v8.h contain some of the instance type
609 // constants always having them avoids them getting different numbers
610 // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
612 BREAK_POINT_INFO_TYPE,
615 SHARED_FUNCTION_INFO_TYPE,
617 JS_MESSAGE_OBJECT_TYPE,
619 // All the following types are subtypes of JSReceiver, which corresponds to
620 // objects in the JS sense. The first and the last type in this range are
621 // the two forms of function. This organization enables using the same
622 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
623 // NONCALLABLE_JS_OBJECT range.
624 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
625 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
627 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
630 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
632 JS_GLOBAL_OBJECT_TYPE,
633 JS_BUILTINS_OBJECT_TYPE,
634 JS_GLOBAL_PROXY_TYPE,
642 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
646 LAST_TYPE = JS_FUNCTION_TYPE,
647 INVALID_TYPE = FIRST_TYPE - 1,
648 FIRST_NONSTRING_TYPE = MAP_TYPE,
649 // Boundaries for testing for an external array.
650 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_BYTE_ARRAY_TYPE,
651 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_PIXEL_ARRAY_TYPE,
652 // Boundary for promotion to old data space/old pointer space.
653 LAST_DATA_TYPE = FILLER_TYPE,
654 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
655 // Note that there is no range for JSObject or JSProxy, since their subtypes
656 // are not continuous in this enum! The enum ranges instead reflect the
657 // external class names, where proxies are treated as either ordinary objects,
659 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
660 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
661 // Boundaries for testing the types represented as JSObject
662 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
663 LAST_JS_OBJECT_TYPE = LAST_TYPE,
664 // Boundaries for testing the types represented as JSProxy
665 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
666 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
667 // Boundaries for testing whether the type is a JavaScript object.
668 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
669 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
670 // Boundaries for testing the types for which typeof is "object".
671 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
672 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
673 // Note that the types for which typeof is "function" are not continuous.
674 // Define this so that we can put assertions on discrete checks.
675 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
678 const int kExternalArrayTypeCount =
679 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
681 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
682 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
683 STATIC_CHECK(ODDBALL_TYPE == Internals::kOddballType);
684 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
696 #define DECL_BOOLEAN_ACCESSORS(name) \
697 inline bool name(); \
698 inline void set_##name(bool value); \
701 #define DECL_ACCESSORS(name, type) \
702 inline type* name(); \
703 inline void set_##name(type* value, \
704 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
707 class DictionaryElementsAccessor;
708 class ElementsAccessor;
709 class FixedArrayBase;
714 struct ValueInfo : public Malloced {
715 ValueInfo() : type(FIRST_TYPE), ptr(NULL), str(NULL), number(0) { }
723 // A template-ized version of the IsXXX functions.
724 template <class C> static inline bool Is(Object* obj);
727 class MaybeObject BASE_EMBEDDED {
729 inline bool IsFailure();
730 inline bool IsRetryAfterGC();
731 inline bool IsOutOfMemory();
732 inline bool IsException();
733 INLINE(bool IsTheHole());
734 inline bool ToObject(Object** obj) {
735 if (IsFailure()) return false;
736 *obj = reinterpret_cast<Object*>(this);
739 inline Failure* ToFailureUnchecked() {
741 return reinterpret_cast<Failure*>(this);
743 inline Object* ToObjectUnchecked() {
744 ASSERT(!IsFailure());
745 return reinterpret_cast<Object*>(this);
747 inline Object* ToObjectChecked() {
749 return reinterpret_cast<Object*>(this);
753 inline bool To(T** obj) {
754 if (IsFailure()) return false;
755 *obj = T::cast(reinterpret_cast<Object*>(this));
760 // Prints this object with details.
761 inline void Print() {
764 inline void PrintLn() {
767 void Print(FILE* out);
768 void PrintLn(FILE* out);
771 // Verifies the object.
777 #define OBJECT_TYPE_LIST(V) \
782 #define HEAP_OBJECT_TYPE_LIST(V) \
790 V(ExternalTwoByteString) \
791 V(ExternalAsciiString) \
792 V(SeqTwoByteString) \
796 V(ExternalByteArray) \
797 V(ExternalUnsignedByteArray) \
798 V(ExternalShortArray) \
799 V(ExternalUnsignedShortArray) \
800 V(ExternalIntArray) \
801 V(ExternalUnsignedIntArray) \
802 V(ExternalFloatArray) \
803 V(ExternalDoubleArray) \
804 V(ExternalPixelArray) \
809 V(JSContextExtensionObject) \
813 V(DeoptimizationInputData) \
814 V(DeoptimizationOutputData) \
815 V(TypeFeedbackCells) \
817 V(FixedDoubleArray) \
825 V(SharedFunctionInfo) \
842 V(JSFunctionResultCache) \
843 V(NormalizedMapCache) \
844 V(CompilationCacheTable) \
845 V(CodeCacheHashTable) \
846 V(PolymorphicCodeCacheHashTable) \
851 V(JSBuiltinsObject) \
853 V(UndetectableObject) \
854 V(AccessCheckNeeded) \
855 V(JSGlobalPropertyCell) \
860 // Object is the abstract superclass for all classes in the
862 // Object does not use any virtual functions to avoid the
863 // allocation of the C++ vtable.
864 // Since Smi and Failure are subclasses of Object no
865 // data members can be present in Object.
866 class Object : public MaybeObject {
869 bool IsObject() { return true; }
871 #define IS_TYPE_FUNCTION_DECL(type_) inline bool Is##type_();
872 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
873 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
874 #undef IS_TYPE_FUNCTION_DECL
876 inline bool IsFixedArrayBase();
878 // Returns true if this object is an instance of the specified
879 // function template.
880 inline bool IsInstanceOf(FunctionTemplateInfo* type);
882 inline bool IsStruct();
883 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
884 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
885 #undef DECLARE_STRUCT_PREDICATE
887 INLINE(bool IsSpecObject());
888 INLINE(bool IsSpecFunction());
891 INLINE(bool IsUndefined());
892 INLINE(bool IsNull());
893 INLINE(bool IsTheHole()); // Shadows MaybeObject's implementation.
894 INLINE(bool IsTrue());
895 INLINE(bool IsFalse());
896 inline bool IsArgumentsMarker();
897 inline bool NonFailureIsHeapObject();
899 // Filler objects (fillers and free space objects).
900 inline bool IsFiller();
902 // Extract the number.
903 inline double Number();
906 // Returns true if the object is of the correct type to be used as a
907 // implementation of a JSObject's elements.
908 inline bool HasValidElements();
910 inline bool HasSpecificClassOf(String* name);
912 MUST_USE_RESULT MaybeObject* ToObject(); // ECMA-262 9.9.
913 Object* ToBoolean(); // ECMA-262 9.2.
915 // Convert to a JSObject if needed.
916 // global_context is used when creating wrapper object.
917 MUST_USE_RESULT MaybeObject* ToObject(Context* global_context);
919 // Converts this to a Smi if possible.
920 // Failure is returned otherwise.
921 MUST_USE_RESULT inline MaybeObject* ToSmi();
923 void Lookup(String* name, LookupResult* result);
926 MUST_USE_RESULT inline MaybeObject* GetProperty(String* key);
927 MUST_USE_RESULT inline MaybeObject* GetProperty(
929 PropertyAttributes* attributes);
930 MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
933 PropertyAttributes* attributes);
935 static Handle<Object> GetProperty(Handle<Object> object,
936 Handle<Object> receiver,
937 LookupResult* result,
939 PropertyAttributes* attributes);
941 MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
942 LookupResult* result,
944 PropertyAttributes* attributes);
946 MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
949 static Handle<Object> GetElement(Handle<Object> object, uint32_t index);
950 MUST_USE_RESULT inline MaybeObject* GetElement(uint32_t index);
951 // For use when we know that no exception can be thrown.
952 inline Object* GetElementNoExceptionThrown(uint32_t index);
953 MUST_USE_RESULT MaybeObject* GetElementWithReceiver(Object* receiver,
956 // Return the object's prototype (might be Heap::null_value()).
957 Object* GetPrototype();
959 // Returns the permanent hash code associated with this object depending on
960 // the actual object type. Might return a failure in case no hash was
961 // created yet or GC was caused by creation.
962 MUST_USE_RESULT MaybeObject* GetHash(CreationFlag flag);
964 // Checks whether this object has the same value as the given one. This
965 // function is implemented according to ES5, section 9.12 and can be used
966 // to implement the Harmony "egal" function.
967 bool SameValue(Object* other);
969 // Tries to convert an object to an array index. Returns true and sets
970 // the output parameter if it succeeds.
971 inline bool ToArrayIndex(uint32_t* index);
973 // Returns true if this is a JSValue containing a string and the index is
974 // < the length of the string. Used to implement [] on strings.
975 inline bool IsStringObjectWithCharacterAt(uint32_t index);
978 // Verify a pointer is a valid object pointer.
979 static void VerifyPointer(Object* p);
982 // Prints this object without details.
983 inline void ShortPrint() {
986 void ShortPrint(FILE* out);
988 // Prints this object without details to a message accumulator.
989 void ShortPrint(StringStream* accumulator);
991 // Casting: This cast is only needed to satisfy macros in objects-inl.h.
992 static Object* cast(Object* value) { return value; }
994 // Layout description.
995 static const int kHeaderSize = 0; // Object does not take up any space.
998 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1002 // Smi represents integer Numbers that can be stored in 31 bits.
1003 // Smis are immediate which means they are NOT allocated in the heap.
1004 // The this pointer has the following format: [31 bit signed int] 0
1005 // For long smis it has the following format:
1006 // [32 bit signed int] [31 bits zero padding] 0
1007 // Smi stands for small integer.
1008 class Smi: public Object {
1010 // Returns the integer value.
1013 // Convert a value to a Smi object.
1014 static inline Smi* FromInt(int value);
1016 static inline Smi* FromIntptr(intptr_t value);
1018 // Returns whether value can be represented in a Smi.
1019 static inline bool IsValid(intptr_t value);
1022 static inline Smi* cast(Object* object);
1024 // Dispatched behavior.
1025 inline void SmiPrint() {
1028 void SmiPrint(FILE* out);
1029 void SmiPrint(StringStream* accumulator);
1034 static const int kMinValue =
1035 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1036 static const int kMaxValue = -(kMinValue + 1);
1039 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1043 // Failure is used for reporting out of memory situations and
1044 // propagating exceptions through the runtime system. Failure objects
1045 // are transient and cannot occur as part of the object graph.
1047 // Failures are a single word, encoded as follows:
1048 // +-------------------------+---+--+--+
1049 // |.........unused..........|sss|tt|11|
1050 // +-------------------------+---+--+--+
1054 // The low two bits, 0-1, are the failure tag, 11. The next two bits,
1055 // 2-3, are a failure type tag 'tt' with possible values:
1056 // 00 RETRY_AFTER_GC
1058 // 10 INTERNAL_ERROR
1059 // 11 OUT_OF_MEMORY_EXCEPTION
1061 // The next three bits, 4-6, are an allocation space tag 'sss'. The
1062 // allocation space tag is 000 for all failure types except
1063 // RETRY_AFTER_GC. For RETRY_AFTER_GC, the possible values are the
1064 // allocation spaces (the encoding is found in globals.h).
1066 // Failure type tag info.
1067 const int kFailureTypeTagSize = 2;
1068 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1070 class Failure: public MaybeObject {
1072 // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1075 EXCEPTION = 1, // Returning this marker tells the real exception
1076 // is in Isolate::pending_exception.
1078 OUT_OF_MEMORY_EXCEPTION = 3
1081 inline Type type() const;
1083 // Returns the space that needs to be collected for RetryAfterGC failures.
1084 inline AllocationSpace allocation_space() const;
1086 inline bool IsInternalError() const;
1087 inline bool IsOutOfMemoryException() const;
1089 static inline Failure* RetryAfterGC(AllocationSpace space);
1090 static inline Failure* RetryAfterGC(); // NEW_SPACE
1091 static inline Failure* Exception();
1092 static inline Failure* InternalError();
1093 static inline Failure* OutOfMemoryException();
1095 static inline Failure* cast(MaybeObject* object);
1097 // Dispatched behavior.
1098 inline void FailurePrint() {
1099 FailurePrint(stdout);
1101 void FailurePrint(FILE* out);
1102 void FailurePrint(StringStream* accumulator);
1104 void FailureVerify();
1108 inline intptr_t value() const;
1109 static inline Failure* Construct(Type type, intptr_t value = 0);
1111 DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1115 // Heap objects typically have a map pointer in their first word. However,
1116 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1117 // encoded in the first word. The class MapWord is an abstraction of the
1118 // value in a heap object's first word.
1119 class MapWord BASE_EMBEDDED {
1121 // Normal state: the map word contains a map pointer.
1123 // Create a map word from a map pointer.
1124 static inline MapWord FromMap(Map* map);
1126 // View this map word as a map pointer.
1127 inline Map* ToMap();
1130 // Scavenge collection: the map word of live objects in the from space
1131 // contains a forwarding address (a heap object pointer in the to space).
1133 // True if this map word is a forwarding address for a scavenge
1134 // collection. Only valid during a scavenge collection (specifically,
1135 // when all map words are heap object pointers, i.e. not during a full GC).
1136 inline bool IsForwardingAddress();
1138 // Create a map word from a forwarding address.
1139 static inline MapWord FromForwardingAddress(HeapObject* object);
1141 // View this map word as a forwarding address.
1142 inline HeapObject* ToForwardingAddress();
1144 static inline MapWord FromRawValue(uintptr_t value) {
1145 return MapWord(value);
1148 inline uintptr_t ToRawValue() {
1153 // HeapObject calls the private constructor and directly reads the value.
1154 friend class HeapObject;
1156 explicit MapWord(uintptr_t value) : value_(value) {}
1162 // HeapObject is the superclass for all classes describing heap allocated
1164 class HeapObject: public Object {
1166 // [map]: Contains a map which contains the object's reflective
1169 inline void set_map(Map* value);
1170 // The no-write-barrier version. This is OK if the object is white and in
1171 // new space, or if the value is an immortal immutable object, like the maps
1172 // of primitive (non-JS) objects like strings, heap numbers etc.
1173 inline void set_map_no_write_barrier(Map* value);
1175 // During garbage collection, the map word of a heap object does not
1176 // necessarily contain a map pointer.
1177 inline MapWord map_word();
1178 inline void set_map_word(MapWord map_word);
1180 // The Heap the object was allocated in. Used also to access Isolate.
1181 inline Heap* GetHeap();
1183 // Convenience method to get current isolate. This method can be
1184 // accessed only when its result is the same as
1185 // Isolate::Current(), it ASSERTs this. See also comment for GetHeap.
1186 inline Isolate* GetIsolate();
1188 // Converts an address to a HeapObject pointer.
1189 static inline HeapObject* FromAddress(Address address);
1191 // Returns the address of this HeapObject.
1192 inline Address address();
1194 // Iterates over pointers contained in the object (including the Map)
1195 void Iterate(ObjectVisitor* v);
1197 // Iterates over all pointers contained in the object except the
1198 // first map pointer. The object type is given in the first
1199 // parameter. This function does not access the map pointer in the
1200 // object, and so is safe to call while the map pointer is modified.
1201 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1203 // Returns the heap object's size in bytes
1206 // Given a heap object's map pointer, returns the heap size in bytes
1207 // Useful when the map pointer field is used for other purposes.
1209 inline int SizeFromMap(Map* map);
1211 // Returns the field at offset in obj, as a read/write Object* reference.
1212 // Does no checking, and is safe to use during GC, while maps are invalid.
1213 // Does not invoke write barrier, so should only be assigned to
1214 // during marking GC.
1215 static inline Object** RawField(HeapObject* obj, int offset);
1218 static inline HeapObject* cast(Object* obj);
1220 // Return the write barrier mode for this. Callers of this function
1221 // must be able to present a reference to an AssertNoAllocation
1222 // object as a sign that they are not going to use this function
1223 // from code that allocates and thus invalidates the returned write
1225 inline WriteBarrierMode GetWriteBarrierMode(const AssertNoAllocation&);
1227 // Dispatched behavior.
1228 void HeapObjectShortPrint(StringStream* accumulator);
1230 inline void HeapObjectPrint() {
1231 HeapObjectPrint(stdout);
1233 void HeapObjectPrint(FILE* out);
1234 void PrintHeader(FILE* out, const char* id);
1238 void HeapObjectVerify();
1239 inline void VerifyObjectField(int offset);
1240 inline void VerifySmiField(int offset);
1242 // Verify a pointer is a valid HeapObject pointer that points to object
1243 // areas in the heap.
1244 static void VerifyHeapPointer(Object* p);
1247 // Layout description.
1248 // First field in a heap object is map.
1249 static const int kMapOffset = Object::kHeaderSize;
1250 static const int kHeaderSize = kMapOffset + kPointerSize;
1252 STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1255 // helpers for calling an ObjectVisitor to iterate over pointers in the
1256 // half-open range [start, end) specified as integer offsets
1257 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1258 // as above, for the single element at "offset"
1259 inline void IteratePointer(ObjectVisitor* v, int offset);
1262 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1266 #define SLOT_ADDR(obj, offset) \
1267 reinterpret_cast<Object**>((obj)->address() + offset)
1269 // This class describes a body of an object of a fixed size
1270 // in which all pointer fields are located in the [start_offset, end_offset)
1272 template<int start_offset, int end_offset, int size>
1273 class FixedBodyDescriptor {
1275 static const int kStartOffset = start_offset;
1276 static const int kEndOffset = end_offset;
1277 static const int kSize = size;
1279 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1281 template<typename StaticVisitor>
1282 static inline void IterateBody(HeapObject* obj) {
1283 StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1284 SLOT_ADDR(obj, end_offset));
1289 // This class describes a body of an object of a variable size
1290 // in which all pointer fields are located in the [start_offset, object_size)
1292 template<int start_offset>
1293 class FlexibleBodyDescriptor {
1295 static const int kStartOffset = start_offset;
1297 static inline void IterateBody(HeapObject* obj,
1301 template<typename StaticVisitor>
1302 static inline void IterateBody(HeapObject* obj, int object_size) {
1303 StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1304 SLOT_ADDR(obj, object_size));
1311 // The HeapNumber class describes heap allocated numbers that cannot be
1312 // represented in a Smi (small integer)
1313 class HeapNumber: public HeapObject {
1315 // [value]: number value.
1316 inline double value();
1317 inline void set_value(double value);
1320 static inline HeapNumber* cast(Object* obj);
1322 // Dispatched behavior.
1323 Object* HeapNumberToBoolean();
1324 inline void HeapNumberPrint() {
1325 HeapNumberPrint(stdout);
1327 void HeapNumberPrint(FILE* out);
1328 void HeapNumberPrint(StringStream* accumulator);
1330 void HeapNumberVerify();
1333 inline int get_exponent();
1334 inline int get_sign();
1336 // Layout description.
1337 static const int kValueOffset = HeapObject::kHeaderSize;
1338 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1339 // is a mixture of sign, exponent and mantissa. Our current platforms are all
1340 // little endian apart from non-EABI arm which is little endian with big
1341 // endian floating point word ordering!
1342 static const int kMantissaOffset = kValueOffset;
1343 static const int kExponentOffset = kValueOffset + 4;
1345 static const int kSize = kValueOffset + kDoubleSize;
1346 static const uint32_t kSignMask = 0x80000000u;
1347 static const uint32_t kExponentMask = 0x7ff00000u;
1348 static const uint32_t kMantissaMask = 0xfffffu;
1349 static const int kMantissaBits = 52;
1350 static const int kExponentBits = 11;
1351 static const int kExponentBias = 1023;
1352 static const int kExponentShift = 20;
1353 static const int kMantissaBitsInTopWord = 20;
1354 static const int kNonMantissaBitsInTopWord = 12;
1357 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1361 enum EnsureElementsMode {
1362 DONT_ALLOW_DOUBLE_ELEMENTS,
1363 ALLOW_COPIED_DOUBLE_ELEMENTS,
1364 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1368 // Indicates whether a property should be set or (re)defined. Setting of a
1369 // property causes attributes to remain unchanged, writability to be checked
1370 // and callbacks to be called. Defining of a property causes attributes to
1371 // be updated and callbacks to be overridden.
1372 enum SetPropertyMode {
1378 // Indicator for one component of an AccessorPair.
1379 enum AccessorComponent {
1385 // JSReceiver includes types on which properties can be defined, i.e.,
1386 // JSObject and JSProxy.
1387 class JSReceiver: public HeapObject {
1396 static inline JSReceiver* cast(Object* obj);
1398 static Handle<Object> SetProperty(Handle<JSReceiver> object,
1400 Handle<Object> value,
1401 PropertyAttributes attributes,
1402 StrictModeFlag strict_mode,
1403 bool skip_fallback_interceptor = false);
1405 MUST_USE_RESULT MaybeObject* SetProperty(String* key,
1407 PropertyAttributes attributes,
1408 StrictModeFlag strict_mode,
1409 bool skip_fallback_interceptor = false);
1410 MUST_USE_RESULT MaybeObject* SetProperty(LookupResult* result,
1413 PropertyAttributes attributes,
1414 StrictModeFlag strict_mode);
1415 MUST_USE_RESULT MaybeObject* SetPropertyWithDefinedSetter(JSReceiver* setter,
1418 MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1419 MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1421 // Set the index'th array element.
1422 // Can cause GC, or return failure if GC is required.
1423 MUST_USE_RESULT MaybeObject* SetElement(uint32_t index,
1425 PropertyAttributes attributes,
1426 StrictModeFlag strict_mode,
1427 bool check_prototype);
1429 // Tests for the fast common case for property enumeration.
1430 bool IsSimpleEnum();
1432 // Returns the class name ([[Class]] property in the specification).
1433 String* class_name();
1435 // Returns the constructor name (the name (possibly, inferred name) of the
1436 // function that was used to instantiate the object).
1437 String* constructor_name();
1439 inline PropertyAttributes GetPropertyAttribute(String* name);
1440 PropertyAttributes GetPropertyAttributeWithReceiver(JSReceiver* receiver,
1442 PropertyAttributes GetLocalPropertyAttribute(String* name);
1445 inline bool HasProperty(String* name);
1446 inline bool HasLocalProperty(String* name);
1447 inline bool HasElement(uint32_t index);
1449 // Return the object's prototype (might be Heap::null_value()).
1450 inline Object* GetPrototype();
1452 // Set the object's prototype (only JSReceiver and null are allowed).
1453 MUST_USE_RESULT MaybeObject* SetPrototype(Object* value,
1454 bool skip_hidden_prototypes);
1456 // Retrieves a permanent object identity hash code. The undefined value might
1457 // be returned in case no hash was created yet and OMIT_CREATION was used.
1458 inline MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1460 // Lookup a property. If found, the result is valid and has
1461 // detailed information.
1462 void LocalLookup(String* name,
1463 LookupResult* result,
1464 bool skip_fallback_interceptor = false);
1465 void Lookup(String* name,
1466 LookupResult* result,
1467 bool skip_fallback_interceptor = false);
1470 Smi* GenerateIdentityHash();
1473 PropertyAttributes GetPropertyAttribute(JSReceiver* receiver,
1474 LookupResult* result,
1476 bool continue_search);
1478 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1481 // The JSObject describes real heap allocated JavaScript objects with
1483 // Note that the map of JSObject changes during execution to enable inline
1485 class JSObject: public JSReceiver {
1487 // [properties]: Backing storage for properties.
1488 // properties is a FixedArray in the fast case and a Dictionary in the
1490 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1491 inline void initialize_properties();
1492 inline bool HasFastProperties();
1493 inline StringDictionary* property_dictionary(); // Gets slow properties.
1495 // [elements]: The elements (properties with names that are integers).
1497 // Elements can be in two general modes: fast and slow. Each mode
1498 // corrensponds to a set of object representations of elements that
1499 // have something in common.
1501 // In the fast mode elements is a FixedArray and so each element can
1502 // be quickly accessed. This fact is used in the generated code. The
1503 // elements array can have one of three maps in this mode:
1504 // fixed_array_map, non_strict_arguments_elements_map or
1505 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1506 // the elements array may be shared by a few objects and so before
1507 // writing to any element the array must be copied. Use
1508 // EnsureWritableFastElements in this case.
1510 // In the slow mode the elements is either a NumberDictionary, an
1511 // ExternalArray, or a FixedArray parameter map for a (non-strict)
1512 // arguments object.
1513 DECL_ACCESSORS(elements, FixedArrayBase)
1514 inline void initialize_elements();
1515 MUST_USE_RESULT inline MaybeObject* ResetElements();
1516 inline ElementsKind GetElementsKind();
1517 inline ElementsAccessor* GetElementsAccessor();
1518 inline bool HasFastSmiOnlyElements();
1519 inline bool HasFastElements();
1520 // Returns if an object has either FAST_ELEMENT or FAST_SMI_ONLY_ELEMENT
1521 // elements. TODO(danno): Rename HasFastTypeElements to HasFastElements() and
1522 // HasFastElements to HasFastObjectElements.
1523 inline bool HasFastTypeElements();
1524 inline bool HasFastDoubleElements();
1525 inline bool HasNonStrictArgumentsElements();
1526 inline bool HasDictionaryElements();
1527 inline bool HasExternalPixelElements();
1528 inline bool HasExternalArrayElements();
1529 inline bool HasExternalByteElements();
1530 inline bool HasExternalUnsignedByteElements();
1531 inline bool HasExternalShortElements();
1532 inline bool HasExternalUnsignedShortElements();
1533 inline bool HasExternalIntElements();
1534 inline bool HasExternalUnsignedIntElements();
1535 inline bool HasExternalFloatElements();
1536 inline bool HasExternalDoubleElements();
1537 bool HasFastArgumentsElements();
1538 bool HasDictionaryArgumentsElements();
1539 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1541 inline void set_map_and_elements(
1543 FixedArrayBase* value,
1544 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
1546 // Requires: HasFastElements().
1547 MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
1549 // Collects elements starting at index 0.
1550 // Undefined values are placed after non-undefined values.
1551 // Returns the number of non-undefined values.
1552 MUST_USE_RESULT MaybeObject* PrepareElementsForSort(uint32_t limit);
1553 // As PrepareElementsForSort, but only on objects where elements is
1554 // a dictionary, and it will stay a dictionary.
1555 MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
1557 MUST_USE_RESULT MaybeObject* GetPropertyWithCallback(Object* receiver,
1562 MUST_USE_RESULT MaybeObject* SetPropertyForResult(LookupResult* result,
1565 PropertyAttributes attributes,
1566 StrictModeFlag strict_mode);
1567 MUST_USE_RESULT MaybeObject* SetPropertyWithFailedAccessCheck(
1568 LookupResult* result,
1571 bool check_prototype,
1572 StrictModeFlag strict_mode);
1573 MUST_USE_RESULT MaybeObject* SetPropertyWithCallback(
1578 StrictModeFlag strict_mode);
1579 MUST_USE_RESULT MaybeObject* SetPropertyWithInterceptor(
1582 PropertyAttributes attributes,
1583 StrictModeFlag strict_mode);
1584 MUST_USE_RESULT MaybeObject* SetPropertyPostInterceptor(
1587 PropertyAttributes attributes,
1588 StrictModeFlag strict_mode);
1590 static Handle<Object> SetLocalPropertyIgnoreAttributes(
1591 Handle<JSObject> object,
1593 Handle<Object> value,
1594 PropertyAttributes attributes);
1597 MUST_USE_RESULT MaybeObject* SetLocalPropertyIgnoreAttributes(
1600 PropertyAttributes attributes);
1602 // Retrieve a value in a normalized object given a lookup result.
1603 // Handles the special representation of JS global objects.
1604 Object* GetNormalizedProperty(LookupResult* result);
1606 // Sets the property value in a normalized object given a lookup result.
1607 // Handles the special representation of JS global objects.
1608 Object* SetNormalizedProperty(LookupResult* result, Object* value);
1610 // Sets the property value in a normalized object given (key, value, details).
1611 // Handles the special representation of JS global objects.
1612 static Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
1614 Handle<Object> value,
1615 PropertyDetails details);
1617 MUST_USE_RESULT MaybeObject* SetNormalizedProperty(String* name,
1619 PropertyDetails details);
1621 // Deletes the named property in a normalized object.
1622 MUST_USE_RESULT MaybeObject* DeleteNormalizedProperty(String* name,
1625 // Retrieve interceptors.
1626 InterceptorInfo* GetNamedInterceptor();
1627 InterceptorInfo* GetIndexedInterceptor();
1629 // Used from JSReceiver.
1630 PropertyAttributes GetPropertyAttributePostInterceptor(JSObject* receiver,
1632 bool continue_search);
1633 PropertyAttributes GetPropertyAttributeWithInterceptor(JSObject* receiver,
1635 bool continue_search);
1636 PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
1638 LookupResult* result,
1640 bool continue_search);
1642 static void DefineAccessor(Handle<JSObject> object,
1643 Handle<String> name,
1644 Handle<Object> getter,
1645 Handle<Object> setter,
1646 PropertyAttributes attributes);
1647 MUST_USE_RESULT MaybeObject* DefineAccessor(String* name,
1650 PropertyAttributes attributes);
1651 Object* LookupAccessor(String* name, AccessorComponent component);
1653 MUST_USE_RESULT MaybeObject* DefineAccessor(AccessorInfo* info);
1655 // Used from Object::GetProperty().
1656 MUST_USE_RESULT MaybeObject* GetPropertyWithFailedAccessCheck(
1658 LookupResult* result,
1660 PropertyAttributes* attributes);
1661 MUST_USE_RESULT MaybeObject* GetPropertyWithInterceptor(
1662 JSReceiver* receiver,
1664 PropertyAttributes* attributes);
1665 MUST_USE_RESULT MaybeObject* GetPropertyPostInterceptor(
1666 JSReceiver* receiver,
1668 PropertyAttributes* attributes);
1669 MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
1670 JSReceiver* receiver,
1672 PropertyAttributes* attributes);
1674 // Returns true if this is an instance of an api function and has
1675 // been modified since it was created. May give false positives.
1678 // If the receiver is a JSGlobalProxy this method will return its prototype,
1679 // otherwise the result is the receiver itself.
1680 inline Object* BypassGlobalProxy();
1682 // Accessors for hidden properties object.
1684 // Hidden properties are not local properties of the object itself.
1685 // Instead they are stored in an auxiliary structure kept as a local
1686 // property with a special name Heap::hidden_symbol(). But if the
1687 // receiver is a JSGlobalProxy then the auxiliary object is a property
1688 // of its prototype, and if it's a detached proxy, then you can't have
1689 // hidden properties.
1691 // Sets a hidden property on this object. Returns this object if successful,
1692 // undefined if called on a detached proxy.
1693 static Handle<Object> SetHiddenProperty(Handle<JSObject> obj,
1695 Handle<Object> value);
1696 // Returns a failure if a GC is required.
1697 MUST_USE_RESULT MaybeObject* SetHiddenProperty(String* key, Object* value);
1698 // Gets the value of a hidden property with the given key. Returns undefined
1699 // if the property doesn't exist (or if called on a detached proxy),
1700 // otherwise returns the value set for the key.
1701 Object* GetHiddenProperty(String* key);
1702 // Deletes a hidden property. Deleting a non-existing property is
1703 // considered successful.
1704 void DeleteHiddenProperty(String* key);
1705 // Returns true if the object has a property with the hidden symbol as name.
1706 bool HasHiddenProperties();
1708 static int GetIdentityHash(Handle<JSObject> obj);
1709 MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1710 MUST_USE_RESULT MaybeObject* SetIdentityHash(Object* hash, CreationFlag flag);
1712 static Handle<Object> DeleteProperty(Handle<JSObject> obj,
1713 Handle<String> name);
1714 MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1716 static Handle<Object> DeleteElement(Handle<JSObject> obj, uint32_t index);
1717 MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1719 inline void ValidateSmiOnlyElements();
1721 // Makes sure that this object can contain HeapObject as elements.
1722 MUST_USE_RESULT inline MaybeObject* EnsureCanContainHeapObjectElements();
1724 // Makes sure that this object can contain the specified elements.
1725 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1728 EnsureElementsMode mode);
1729 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1730 FixedArrayBase* elements,
1731 EnsureElementsMode mode);
1732 MUST_USE_RESULT MaybeObject* EnsureCanContainElements(
1733 Arguments* arguments,
1736 EnsureElementsMode mode);
1738 // Do we want to keep the elements in fast case when increasing the
1740 bool ShouldConvertToSlowElements(int new_capacity);
1741 // Returns true if the backing storage for the slow-case elements of
1742 // this object takes up nearly as much space as a fast-case backing
1743 // storage would. In that case the JSObject should have fast
1745 bool ShouldConvertToFastElements();
1746 // Returns true if the elements of JSObject contains only values that can be
1747 // represented in a FixedDoubleArray and has at least one value that can only
1748 // be represented as a double and not a Smi.
1749 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1751 // Tells whether the index'th element is present.
1752 bool HasElementWithReceiver(JSReceiver* receiver, uint32_t index);
1754 // Computes the new capacity when expanding the elements of a JSObject.
1755 static int NewElementsCapacity(int old_capacity) {
1756 // (old_capacity + 50%) + 16
1757 return old_capacity + (old_capacity >> 1) + 16;
1760 // Tells whether the index'th element is present and how it is stored.
1761 enum LocalElementType {
1762 // There is no element with given index.
1765 // Element with given index is handled by interceptor.
1766 INTERCEPTED_ELEMENT,
1768 // Element with given index is character in string.
1769 STRING_CHARACTER_ELEMENT,
1771 // Element with given index is stored in fast backing store.
1774 // Element with given index is stored in slow backing store.
1778 LocalElementType HasLocalElement(uint32_t index);
1780 bool HasElementWithInterceptor(JSReceiver* receiver, uint32_t index);
1782 MUST_USE_RESULT MaybeObject* SetFastElement(uint32_t index,
1784 StrictModeFlag strict_mode,
1785 bool check_prototype);
1787 MUST_USE_RESULT MaybeObject* SetDictionaryElement(
1790 PropertyAttributes attributes,
1791 StrictModeFlag strict_mode,
1792 bool check_prototype,
1793 SetPropertyMode set_mode = SET_PROPERTY);
1795 MUST_USE_RESULT MaybeObject* SetFastDoubleElement(
1798 StrictModeFlag strict_mode,
1799 bool check_prototype = true);
1801 static Handle<Object> SetOwnElement(Handle<JSObject> object,
1803 Handle<Object> value,
1804 StrictModeFlag strict_mode);
1806 // Empty handle is returned if the element cannot be set to the given value.
1807 static MUST_USE_RESULT Handle<Object> SetElement(
1808 Handle<JSObject> object,
1810 Handle<Object> value,
1811 PropertyAttributes attr,
1812 StrictModeFlag strict_mode,
1813 SetPropertyMode set_mode = SET_PROPERTY);
1815 // A Failure object is returned if GC is needed.
1816 MUST_USE_RESULT MaybeObject* SetElement(
1819 PropertyAttributes attributes,
1820 StrictModeFlag strict_mode,
1821 bool check_prototype = true,
1822 SetPropertyMode set_mode = SET_PROPERTY);
1824 // Returns the index'th element.
1825 // The undefined object if index is out of bounds.
1826 MUST_USE_RESULT MaybeObject* GetElementWithInterceptor(Object* receiver,
1829 enum SetFastElementsCapacityMode {
1830 kAllowSmiOnlyElements,
1831 kForceSmiOnlyElements,
1832 kDontAllowSmiOnlyElements
1835 // Replace the elements' backing store with fast elements of the given
1836 // capacity. Update the length for JSArrays. Returns the new backing
1838 MUST_USE_RESULT MaybeObject* SetFastElementsCapacityAndLength(
1841 SetFastElementsCapacityMode set_capacity_mode);
1842 MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
1846 // Lookup interceptors are used for handling properties controlled by host
1848 inline bool HasNamedInterceptor();
1849 inline bool HasIndexedInterceptor();
1851 // Support functions for v8 api (needed for correct interceptor behavior).
1852 bool HasRealNamedProperty(String* key);
1853 bool HasRealElementProperty(uint32_t index);
1854 bool HasRealNamedCallbackProperty(String* key);
1856 // Get the header size for a JSObject. Used to compute the index of
1857 // internal fields as well as the number of internal fields.
1858 inline int GetHeaderSize();
1860 inline int GetInternalFieldCount();
1861 inline int GetInternalFieldOffset(int index);
1862 inline Object* GetInternalField(int index);
1863 inline void SetInternalField(int index, Object* value);
1864 inline void SetInternalField(int index, Smi* value);
1866 inline void SetExternalResourceObject(Object *);
1867 inline Object *GetExternalResourceObject();
1869 // The following lookup functions skip interceptors.
1870 void LocalLookupRealNamedProperty(String* name, LookupResult* result);
1871 void LookupRealNamedProperty(String* name, LookupResult* result);
1872 void LookupRealNamedPropertyInPrototypes(String* name, LookupResult* result);
1873 void LookupCallbackSetterInPrototypes(String* name, LookupResult* result);
1874 MUST_USE_RESULT MaybeObject* SetElementWithCallbackSetterInPrototypes(
1875 uint32_t index, Object* value, bool* found, StrictModeFlag strict_mode);
1876 void LookupCallback(String* name, LookupResult* result);
1878 // Returns the number of properties on this object filtering out properties
1879 // with the specified attributes (ignoring interceptors).
1880 int NumberOfLocalProperties(PropertyAttributes filter = NONE);
1881 // Fill in details for properties into storage starting at the specified
1883 void GetLocalPropertyNames(FixedArray* storage, int index);
1885 // Returns the number of properties on this object filtering out properties
1886 // with the specified attributes (ignoring interceptors).
1887 int NumberOfLocalElements(PropertyAttributes filter);
1888 // Returns the number of enumerable elements (ignoring interceptors).
1889 int NumberOfEnumElements();
1890 // Returns the number of elements on this object filtering out elements
1891 // with the specified attributes (ignoring interceptors).
1892 int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
1893 // Count and fill in the enumerable elements into storage.
1894 // (storage->length() == NumberOfEnumElements()).
1895 // If storage is NULL, will count the elements without adding
1896 // them to any storage.
1897 // Returns the number of enumerable elements.
1898 int GetEnumElementKeys(FixedArray* storage);
1900 // Add a property to a fast-case object using a map transition to
1902 MUST_USE_RESULT MaybeObject* AddFastPropertyUsingMap(Map* new_map,
1906 // Add a constant function property to a fast-case object.
1907 // This leaves a CONSTANT_TRANSITION in the old map, and
1908 // if it is called on a second object with this map, a
1909 // normal property is added instead, with a map transition.
1910 // This avoids the creation of many maps with the same constant
1911 // function, all orphaned.
1912 MUST_USE_RESULT MaybeObject* AddConstantFunctionProperty(
1914 JSFunction* function,
1915 PropertyAttributes attributes);
1917 MUST_USE_RESULT MaybeObject* ReplaceSlowProperty(
1920 PropertyAttributes attributes);
1922 // Returns a new map with all transitions dropped from the object's current
1923 // map and the ElementsKind set.
1924 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
1925 ElementsKind to_kind);
1926 inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
1928 ElementsKind elements_kind);
1929 MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
1930 ElementsKind elements_kind);
1932 static Handle<Object> TransitionElementsKind(Handle<JSObject> object,
1933 ElementsKind to_kind);
1935 MUST_USE_RESULT MaybeObject* TransitionElementsKind(ElementsKind to_kind);
1937 // Converts a descriptor of any other type to a real field,
1938 // backed by the properties array. Descriptors of visible
1939 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1940 // Converts the descriptor on the original object's map to a
1941 // map transition, and the the new field is on the object's new map.
1942 MUST_USE_RESULT MaybeObject* ConvertDescriptorToFieldAndMapTransition(
1945 PropertyAttributes attributes);
1947 // Converts a descriptor of any other type to a real field,
1948 // backed by the properties array. Descriptors of visible
1949 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1950 MUST_USE_RESULT MaybeObject* ConvertDescriptorToField(
1953 PropertyAttributes attributes);
1955 // Add a property to a fast-case object.
1956 MUST_USE_RESULT MaybeObject* AddFastProperty(String* name,
1958 PropertyAttributes attributes);
1960 // Add a property to a slow-case object.
1961 MUST_USE_RESULT MaybeObject* AddSlowProperty(String* name,
1963 PropertyAttributes attributes);
1965 // Add a property to an object.
1966 MUST_USE_RESULT MaybeObject* AddProperty(String* name,
1968 PropertyAttributes attributes,
1969 StrictModeFlag strict_mode);
1971 // Convert the object to use the canonical dictionary
1972 // representation. If the object is expected to have additional properties
1973 // added this number can be indicated to have the backing store allocated to
1974 // an initial capacity for holding these properties.
1975 static void NormalizeProperties(Handle<JSObject> object,
1976 PropertyNormalizationMode mode,
1977 int expected_additional_properties);
1979 MUST_USE_RESULT MaybeObject* NormalizeProperties(
1980 PropertyNormalizationMode mode,
1981 int expected_additional_properties);
1983 // Convert and update the elements backing store to be a
1984 // SeededNumberDictionary dictionary. Returns the backing after conversion.
1985 static Handle<SeededNumberDictionary> NormalizeElements(
1986 Handle<JSObject> object);
1988 MUST_USE_RESULT MaybeObject* NormalizeElements();
1990 static void UpdateMapCodeCache(Handle<JSObject> object,
1991 Handle<String> name,
1994 MUST_USE_RESULT MaybeObject* UpdateMapCodeCache(String* name, Code* code);
1996 // Transform slow named properties to fast variants.
1997 // Returns failure if allocation failed.
1998 static void TransformToFastProperties(Handle<JSObject> object,
1999 int unused_property_fields);
2001 MUST_USE_RESULT MaybeObject* TransformToFastProperties(
2002 int unused_property_fields);
2004 // Access fast-case object properties at index.
2005 inline Object* FastPropertyAt(int index);
2006 inline Object* FastPropertyAtPut(int index, Object* value);
2008 // Access to in object properties.
2009 inline int GetInObjectPropertyOffset(int index);
2010 inline Object* InObjectPropertyAt(int index);
2011 inline Object* InObjectPropertyAtPut(int index,
2013 WriteBarrierMode mode
2014 = UPDATE_WRITE_BARRIER);
2016 // Initializes the body after properties slot, properties slot is
2017 // initialized by set_properties. Fill the pre-allocated fields with
2018 // pre_allocated_value and the rest with filler_value.
2019 // Note: this call does not update write barrier, the caller is responsible
2020 // to ensure that |filler_value| can be collected without WB here.
2021 inline void InitializeBody(Map* map,
2022 Object* pre_allocated_value,
2023 Object* filler_value);
2025 // Check whether this object references another object
2026 bool ReferencesObject(Object* obj);
2029 static inline JSObject* cast(Object* obj);
2031 // Disalow further properties to be added to the object.
2032 static Handle<Object> PreventExtensions(Handle<JSObject> object);
2033 MUST_USE_RESULT MaybeObject* PreventExtensions();
2036 // Dispatched behavior.
2037 void JSObjectShortPrint(StringStream* accumulator);
2039 inline void JSObjectPrint() {
2040 JSObjectPrint(stdout);
2042 void JSObjectPrint(FILE* out);
2045 void JSObjectVerify();
2048 inline void PrintProperties() {
2049 PrintProperties(stdout);
2051 void PrintProperties(FILE* out);
2053 inline void PrintElements() {
2054 PrintElements(stdout);
2056 void PrintElements(FILE* out);
2059 void PrintElementsTransition(
2060 FILE* file, ElementsKind from_kind, FixedArrayBase* from_elements,
2061 ElementsKind to_kind, FixedArrayBase* to_elements);
2064 // Structure for collecting spill information about JSObjects.
2065 class SpillInformation {
2069 int number_of_objects_;
2070 int number_of_objects_with_fast_properties_;
2071 int number_of_objects_with_fast_elements_;
2072 int number_of_fast_used_fields_;
2073 int number_of_fast_unused_fields_;
2074 int number_of_slow_used_properties_;
2075 int number_of_slow_unused_properties_;
2076 int number_of_fast_used_elements_;
2077 int number_of_fast_unused_elements_;
2078 int number_of_slow_used_elements_;
2079 int number_of_slow_unused_elements_;
2082 void IncrementSpillStatistics(SpillInformation* info);
2084 Object* SlowReverseLookup(Object* value);
2086 // Maximal number of fast properties for the JSObject. Used to
2087 // restrict the number of map transitions to avoid an explosion in
2088 // the number of maps for objects used as dictionaries.
2089 inline int MaxFastProperties();
2091 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2092 // Also maximal value of JSArray's length property.
2093 static const uint32_t kMaxElementCount = 0xffffffffu;
2095 // Constants for heuristics controlling conversion of fast elements
2096 // to slow elements.
2098 // Maximal gap that can be introduced by adding an element beyond
2099 // the current elements length.
2100 static const uint32_t kMaxGap = 1024;
2102 // Maximal length of fast elements array that won't be checked for
2103 // being dense enough on expansion.
2104 static const int kMaxUncheckedFastElementsLength = 5000;
2106 // Same as above but for old arrays. This limit is more strict. We
2107 // don't want to be wasteful with long lived objects.
2108 static const int kMaxUncheckedOldFastElementsLength = 500;
2110 static const int kInitialMaxFastElementArray = 100000;
2111 static const int kMaxFastProperties = 12;
2112 static const int kMaxInstanceSize = 255 * kPointerSize;
2113 // When extending the backing storage for property values, we increase
2114 // its size by more than the 1 entry necessary, so sequentially adding fields
2115 // to the same object requires fewer allocations and copies.
2116 static const int kFieldsAdded = 3;
2118 // Layout description.
2119 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2120 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2121 static const int kHeaderSize = kElementsOffset + kPointerSize;
2123 STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2125 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2127 static inline int SizeOf(Map* map, HeapObject* object);
2131 friend class DictionaryElementsAccessor;
2133 MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2137 MUST_USE_RESULT MaybeObject* SetElementWithCallback(
2142 StrictModeFlag strict_mode);
2143 MUST_USE_RESULT MaybeObject* SetElementWithInterceptor(
2146 PropertyAttributes attributes,
2147 StrictModeFlag strict_mode,
2148 bool check_prototype,
2149 SetPropertyMode set_mode);
2150 MUST_USE_RESULT MaybeObject* SetElementWithoutInterceptor(
2153 PropertyAttributes attributes,
2154 StrictModeFlag strict_mode,
2155 bool check_prototype,
2156 SetPropertyMode set_mode);
2158 // Searches the prototype chain for a callback setter and sets the property
2159 // with the setter if it finds one. The '*found' flag indicates whether
2160 // a setter was found or not.
2161 // This function can cause GC and can return a failure result with
2163 MUST_USE_RESULT MaybeObject* SetPropertyWithCallbackSetterInPrototypes(
2166 PropertyAttributes attributes,
2168 StrictModeFlag strict_mode);
2170 MUST_USE_RESULT MaybeObject* DeletePropertyPostInterceptor(String* name,
2172 MUST_USE_RESULT MaybeObject* DeletePropertyWithInterceptor(String* name);
2174 MUST_USE_RESULT MaybeObject* DeleteElementWithInterceptor(uint32_t index);
2176 MUST_USE_RESULT MaybeObject* DeleteFastElement(uint32_t index);
2177 MUST_USE_RESULT MaybeObject* DeleteDictionaryElement(uint32_t index,
2180 bool ReferencesObjectFromElements(FixedArray* elements,
2184 // Returns true if most of the elements backing storage is used.
2185 bool HasDenseElements();
2187 // Gets the current elements capacity and the number of used elements.
2188 void GetElementsCapacityAndUsage(int* capacity, int* used);
2190 bool CanSetCallback(String* name);
2191 MUST_USE_RESULT MaybeObject* SetElementCallback(
2194 PropertyAttributes attributes);
2195 MUST_USE_RESULT MaybeObject* SetPropertyCallback(
2198 PropertyAttributes attributes);
2199 MUST_USE_RESULT MaybeObject* DefineElementAccessor(
2203 PropertyAttributes attributes);
2204 MUST_USE_RESULT MaybeObject* CreateAccessorPairFor(String* name);
2205 MUST_USE_RESULT MaybeObject* DefinePropertyAccessor(
2209 PropertyAttributes attributes);
2210 void LookupInDescriptor(String* name, LookupResult* result);
2212 // Returns the hidden properties backing store object, currently
2213 // a StringDictionary, stored on this object.
2214 // If no hidden properties object has been put on this object,
2215 // return undefined, unless create_if_absent is true, in which case
2216 // a new dictionary is created, added to this object, and returned.
2217 MUST_USE_RESULT MaybeObject* GetHiddenPropertiesDictionary(
2218 bool create_if_absent);
2219 // Updates the existing hidden properties dictionary.
2220 MUST_USE_RESULT MaybeObject* SetHiddenPropertiesDictionary(
2221 StringDictionary* dictionary);
2223 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2227 // Common superclass for FixedArrays that allow implementations to share
2228 // common accessors and some code paths.
2229 class FixedArrayBase: public HeapObject {
2231 // [length]: length of the array.
2232 inline int length();
2233 inline void set_length(int value);
2235 inline static FixedArrayBase* cast(Object* object);
2237 // Layout description.
2238 // Length is smi tagged when it is stored.
2239 static const int kLengthOffset = HeapObject::kHeaderSize;
2240 static const int kHeaderSize = kLengthOffset + kPointerSize;
2244 class FixedDoubleArray;
2246 // FixedArray describes fixed-sized arrays with element type Object*.
2247 class FixedArray: public FixedArrayBase {
2249 // Setter and getter for elements.
2250 inline Object* get(int index);
2251 // Setter that uses write barrier.
2252 inline void set(int index, Object* value);
2253 inline bool is_the_hole(int index);
2255 // Setter that doesn't need write barrier).
2256 inline void set(int index, Smi* value);
2257 // Setter with explicit barrier mode.
2258 inline void set(int index, Object* value, WriteBarrierMode mode);
2260 // Setters for frequently used oddballs located in old space.
2261 inline void set_undefined(int index);
2262 // TODO(isolates): duplicate.
2263 inline void set_undefined(Heap* heap, int index);
2264 inline void set_null(int index);
2265 // TODO(isolates): duplicate.
2266 inline void set_null(Heap* heap, int index);
2267 inline void set_the_hole(int index);
2269 // Setters with less debug checks for the GC to use.
2270 inline void set_unchecked(int index, Smi* value);
2271 inline void set_null_unchecked(Heap* heap, int index);
2272 inline void set_unchecked(Heap* heap, int index, Object* value,
2273 WriteBarrierMode mode);
2275 // Gives access to raw memory which stores the array's data.
2276 inline Object** data_start();
2278 inline Object** GetFirstElementAddress();
2279 inline bool ContainsOnlySmisOrHoles();
2282 MUST_USE_RESULT inline MaybeObject* Copy();
2283 MUST_USE_RESULT MaybeObject* CopySize(int new_length);
2285 // Add the elements of a JSArray to this FixedArray.
2286 MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
2288 // Compute the union of this and other.
2289 MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
2291 // Copy a sub array from the receiver to dest.
2292 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2294 // Garbage collection support.
2295 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2297 // Code Generation support.
2298 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2301 static inline FixedArray* cast(Object* obj);
2303 // Maximal allowed size, in bytes, of a single FixedArray.
2304 // Prevents overflowing size computations, as well as extreme memory
2306 static const int kMaxSize = 128 * MB * kPointerSize;
2307 // Maximally allowed length of a FixedArray.
2308 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2310 // Dispatched behavior.
2312 inline void FixedArrayPrint() {
2313 FixedArrayPrint(stdout);
2315 void FixedArrayPrint(FILE* out);
2318 void FixedArrayVerify();
2319 // Checks if two FixedArrays have identical contents.
2320 bool IsEqualTo(FixedArray* other);
2323 // Swap two elements in a pair of arrays. If this array and the
2324 // numbers array are the same object, the elements are only swapped
2326 void SwapPairs(FixedArray* numbers, int i, int j);
2328 // Sort prefix of this array and the numbers array as pairs wrt. the
2329 // numbers. If the numbers array and the this array are the same
2330 // object, the prefix of this array is sorted.
2331 void SortPairs(FixedArray* numbers, uint32_t len);
2333 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2335 static inline int SizeOf(Map* map, HeapObject* object) {
2336 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2341 // Set operation on FixedArray without using write barriers. Can
2342 // only be used for storing old space objects or smis.
2343 static inline void NoWriteBarrierSet(FixedArray* array,
2347 // Set operation on FixedArray without incremental write barrier. Can
2348 // only be used if the object is guaranteed to be white (whiteness witness
2350 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2355 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2359 // FixedDoubleArray describes fixed-sized arrays with element type double.
2360 class FixedDoubleArray: public FixedArrayBase {
2362 // Setter and getter for elements.
2363 inline double get_scalar(int index);
2364 inline int64_t get_representation(int index);
2365 MUST_USE_RESULT inline MaybeObject* get(int index);
2366 inline void set(int index, double value);
2367 inline void set_the_hole(int index);
2369 // Checking for the hole.
2370 inline bool is_the_hole(int index);
2373 MUST_USE_RESULT inline MaybeObject* Copy();
2375 // Garbage collection support.
2376 inline static int SizeFor(int length) {
2377 return kHeaderSize + length * kDoubleSize;
2380 // Code Generation support.
2381 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2383 inline static bool is_the_hole_nan(double value);
2384 inline static double hole_nan_as_double();
2385 inline static double canonical_not_the_hole_nan_as_double();
2388 static inline FixedDoubleArray* cast(Object* obj);
2390 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2391 // Prevents overflowing size computations, as well as extreme memory
2393 static const int kMaxSize = 512 * MB;
2394 // Maximally allowed length of a FixedArray.
2395 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2397 // Dispatched behavior.
2399 inline void FixedDoubleArrayPrint() {
2400 FixedDoubleArrayPrint(stdout);
2402 void FixedDoubleArrayPrint(FILE* out);
2406 void FixedDoubleArrayVerify();
2410 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2414 class IncrementalMarking;
2417 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2418 // The format of the these objects is:
2419 // TODO(1399): It should be possible to make room for bit_field3 in the map
2420 // without overloading the instance descriptors field in the map
2421 // (and storing it in the DescriptorArray when the map has one).
2422 // [0]: storage for bit_field3 for Map owning this object (Smi)
2423 // [1]: point to a fixed array with (value, detail) pairs.
2424 // [2]: next enumeration index (Smi), or pointer to small fixed array:
2425 // [0]: next enumeration index (Smi)
2426 // [1]: pointer to fixed array with enum cache
2428 // [length() - 1]: last key
2430 class DescriptorArray: public FixedArray {
2432 // Returns true for both shared empty_descriptor_array and for smis, which the
2433 // map uses to encode additional bit fields when the descriptor array is not
2435 inline bool IsEmpty();
2437 // Returns the number of descriptors in the array.
2438 int number_of_descriptors() {
2439 ASSERT(length() > kFirstIndex || IsEmpty());
2441 return len <= kFirstIndex ? 0 : len - kFirstIndex;
2444 int NextEnumerationIndex() {
2445 if (IsEmpty()) return PropertyDetails::kInitialIndex;
2446 Object* obj = get(kEnumerationIndexIndex);
2448 return Smi::cast(obj)->value();
2450 Object* index = FixedArray::cast(obj)->get(kEnumCacheBridgeEnumIndex);
2451 return Smi::cast(index)->value();
2455 // Set next enumeration index and flush any enum cache.
2456 void SetNextEnumerationIndex(int value) {
2458 set(kEnumerationIndexIndex, Smi::FromInt(value));
2461 bool HasEnumCache() {
2462 return !IsEmpty() && !get(kEnumerationIndexIndex)->IsSmi();
2465 Object* GetEnumCache() {
2466 ASSERT(HasEnumCache());
2467 FixedArray* bridge = FixedArray::cast(get(kEnumerationIndexIndex));
2468 return bridge->get(kEnumCacheBridgeCacheIndex);
2471 // TODO(1399): It should be possible to make room for bit_field3 in the map
2472 // without overloading the instance descriptors field in the map
2473 // (and storing it in the DescriptorArray when the map has one).
2474 inline int bit_field3_storage();
2475 inline void set_bit_field3_storage(int value);
2477 // Initialize or change the enum cache,
2478 // using the supplied storage for the small "bridge".
2479 void SetEnumCache(FixedArray* bridge_storage,
2480 FixedArray* new_cache,
2481 Object* new_index_cache);
2483 // Accessors for fetching instance descriptor at descriptor number.
2484 inline String* GetKey(int descriptor_number);
2485 inline Object* GetValue(int descriptor_number);
2486 inline PropertyDetails GetDetails(int descriptor_number);
2487 inline PropertyType GetType(int descriptor_number);
2488 inline int GetFieldIndex(int descriptor_number);
2489 inline JSFunction* GetConstantFunction(int descriptor_number);
2490 inline Object* GetCallbacksObject(int descriptor_number);
2491 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2492 inline bool IsProperty(int descriptor_number);
2493 inline bool IsTransitionOnly(int descriptor_number);
2494 inline bool IsNullDescriptor(int descriptor_number);
2496 class WhitenessWitness {
2498 inline explicit WhitenessWitness(DescriptorArray* array);
2499 inline ~WhitenessWitness();
2502 IncrementalMarking* marking_;
2505 // Accessor for complete descriptor.
2506 inline void Get(int descriptor_number, Descriptor* desc);
2507 inline void Set(int descriptor_number,
2509 const WhitenessWitness&);
2511 // Transfer a complete descriptor from the src descriptor array to the dst
2512 // one, dropping map transitions in CALLBACKS.
2513 static void CopyFrom(Handle<DescriptorArray> dst,
2515 Handle<DescriptorArray> src,
2517 const WhitenessWitness& witness);
2519 // Transfer a complete descriptor from the src descriptor array to this
2520 // descriptor array, dropping map transitions in CALLBACKS.
2521 MUST_USE_RESULT MaybeObject* CopyFrom(int dst_index,
2522 DescriptorArray* src,
2524 const WhitenessWitness&);
2526 // Copy the descriptor array, insert a new descriptor and optionally
2527 // remove map transitions. If the descriptor is already present, it is
2528 // replaced. If a replaced descriptor is a real property (not a transition
2529 // or null), its enumeration index is kept as is.
2530 // If adding a real property, map transitions must be removed. If adding
2531 // a transition, they must not be removed. All null descriptors are removed.
2532 MUST_USE_RESULT MaybeObject* CopyInsert(Descriptor* descriptor,
2533 TransitionFlag transition_flag);
2535 // Return a copy of the array with all transitions and null descriptors
2536 // removed. Return a Failure object in case of an allocation failure.
2537 MUST_USE_RESULT MaybeObject* RemoveTransitions();
2539 // Sort the instance descriptors by the hash codes of their keys.
2540 // Does not check for duplicates.
2541 void SortUnchecked(const WhitenessWitness&);
2543 // Sort the instance descriptors by the hash codes of their keys.
2544 // Checks the result for duplicates.
2545 void Sort(const WhitenessWitness&);
2547 // Search the instance descriptors for given name.
2548 inline int Search(String* name);
2550 // As the above, but uses DescriptorLookupCache and updates it when
2552 inline int SearchWithCache(String* name);
2554 // Tells whether the name is present int the array.
2555 bool Contains(String* name) { return kNotFound != Search(name); }
2557 // Perform a binary search in the instance descriptors represented
2558 // by this fixed array. low and high are descriptor indices. If there
2559 // are three instance descriptors in this array it should be called
2560 // with low=0 and high=2.
2561 int BinarySearch(String* name, int low, int high);
2563 // Perform a linear search in the instance descriptors represented
2564 // by this fixed array. len is the number of descriptor indices that are
2565 // valid. Does not require the descriptors to be sorted.
2566 int LinearSearch(String* name, int len);
2568 // Allocates a DescriptorArray, but returns the singleton
2569 // empty descriptor array object if number_of_descriptors is 0.
2570 MUST_USE_RESULT static MaybeObject* Allocate(int number_of_descriptors);
2573 static inline DescriptorArray* cast(Object* obj);
2575 // Constant for denoting key was not found.
2576 static const int kNotFound = -1;
2578 static const int kBitField3StorageIndex = 0;
2579 static const int kContentArrayIndex = 1;
2580 static const int kEnumerationIndexIndex = 2;
2581 static const int kFirstIndex = 3;
2583 // The length of the "bridge" to the enum cache.
2584 static const int kEnumCacheBridgeLength = 3;
2585 static const int kEnumCacheBridgeEnumIndex = 0;
2586 static const int kEnumCacheBridgeCacheIndex = 1;
2587 static const int kEnumCacheBridgeIndicesCacheIndex = 2;
2589 // Layout description.
2590 static const int kBitField3StorageOffset = FixedArray::kHeaderSize;
2591 static const int kContentArrayOffset = kBitField3StorageOffset + kPointerSize;
2592 static const int kEnumerationIndexOffset = kContentArrayOffset + kPointerSize;
2593 static const int kFirstOffset = kEnumerationIndexOffset + kPointerSize;
2595 // Layout description for the bridge array.
2596 static const int kEnumCacheBridgeEnumOffset = FixedArray::kHeaderSize;
2597 static const int kEnumCacheBridgeCacheOffset =
2598 kEnumCacheBridgeEnumOffset + kPointerSize;
2601 // Print all the descriptors.
2602 inline void PrintDescriptors() {
2603 PrintDescriptors(stdout);
2605 void PrintDescriptors(FILE* out);
2609 // Is the descriptor array sorted and without duplicates?
2610 bool IsSortedNoDuplicates();
2612 // Is the descriptor array consistent with the back pointers in targets?
2613 bool IsConsistentWithBackPointers(Map* current_map);
2615 // Are two DescriptorArrays equal?
2616 bool IsEqualTo(DescriptorArray* other);
2619 // The maximum number of descriptors we want in a descriptor array (should
2621 static const int kMaxNumberOfDescriptors = 1024 + 512;
2624 // An entry in a DescriptorArray, represented as an (array, index) pair.
2627 inline explicit Entry(DescriptorArray* descs, int index) :
2628 descs_(descs), index_(index) { }
2630 inline PropertyType type() { return descs_->GetType(index_); }
2631 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2634 DescriptorArray* descs_;
2638 // Conversion from descriptor number to array indices.
2639 static int ToKeyIndex(int descriptor_number) {
2640 return descriptor_number+kFirstIndex;
2643 static int ToDetailsIndex(int descriptor_number) {
2644 return (descriptor_number << 1) + 1;
2647 static int ToValueIndex(int descriptor_number) {
2648 return descriptor_number << 1;
2651 // Swap operation on FixedArray without using write barriers.
2652 static inline void NoIncrementalWriteBarrierSwap(
2653 FixedArray* array, int first, int second);
2655 // Swap descriptor first and second.
2656 inline void NoIncrementalWriteBarrierSwapDescriptors(
2657 int first, int second);
2659 FixedArray* GetContentArray() {
2660 return FixedArray::cast(get(kContentArrayIndex));
2662 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2666 // HashTable is a subclass of FixedArray that implements a hash table
2667 // that uses open addressing and quadratic probing.
2669 // In order for the quadratic probing to work, elements that have not
2670 // yet been used and elements that have been deleted are
2671 // distinguished. Probing continues when deleted elements are
2672 // encountered and stops when unused elements are encountered.
2674 // - Elements with key == undefined have not been used yet.
2675 // - Elements with key == the_hole have been deleted.
2677 // The hash table class is parameterized with a Shape and a Key.
2678 // Shape must be a class with the following interface:
2679 // class ExampleShape {
2681 // // Tells whether key matches other.
2682 // static bool IsMatch(Key key, Object* other);
2683 // // Returns the hash value for key.
2684 // static uint32_t Hash(Key key);
2685 // // Returns the hash value for object.
2686 // static uint32_t HashForObject(Key key, Object* object);
2687 // // Convert key to an object.
2688 // static inline Object* AsObject(Key key);
2689 // // The prefix size indicates number of elements in the beginning
2690 // // of the backing storage.
2691 // static const int kPrefixSize = ..;
2692 // // The Element size indicates number of elements per entry.
2693 // static const int kEntrySize = ..;
2695 // The prefix size indicates an amount of memory in the
2696 // beginning of the backing storage that can be used for non-element
2697 // information by subclasses.
2699 template<typename Key>
2702 static const bool UsesSeed = false;
2703 static uint32_t Hash(Key key) { return 0; }
2704 static uint32_t SeededHash(Key key, uint32_t seed) {
2708 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2709 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2711 return HashForObject(key, object);
2715 template<typename Shape, typename Key>
2716 class HashTable: public FixedArray {
2719 inline uint32_t Hash(Key key) {
2720 if (Shape::UsesSeed) {
2721 return Shape::SeededHash(key,
2722 GetHeap()->HashSeed());
2724 return Shape::Hash(key);
2728 inline uint32_t HashForObject(Key key, Object* object) {
2729 if (Shape::UsesSeed) {
2730 return Shape::SeededHashForObject(key,
2731 GetHeap()->HashSeed(), object);
2733 return Shape::HashForObject(key, object);
2737 // Returns the number of elements in the hash table.
2738 int NumberOfElements() {
2739 return Smi::cast(get(kNumberOfElementsIndex))->value();
2742 // Returns the number of deleted elements in the hash table.
2743 int NumberOfDeletedElements() {
2744 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2747 // Returns the capacity of the hash table.
2749 return Smi::cast(get(kCapacityIndex))->value();
2752 // ElementAdded should be called whenever an element is added to a
2754 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2756 // ElementRemoved should be called whenever an element is removed from
2758 void ElementRemoved() {
2759 SetNumberOfElements(NumberOfElements() - 1);
2760 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2762 void ElementsRemoved(int n) {
2763 SetNumberOfElements(NumberOfElements() - n);
2764 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2767 // Returns a new HashTable object. Might return Failure.
2768 MUST_USE_RESULT static MaybeObject* Allocate(
2769 int at_least_space_for,
2770 PretenureFlag pretenure = NOT_TENURED);
2772 // Computes the required capacity for a table holding the given
2773 // number of elements. May be more than HashTable::kMaxCapacity.
2774 static int ComputeCapacity(int at_least_space_for);
2776 // Returns the key at entry.
2777 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2779 // Tells whether k is a real key. The hole and undefined are not allowed
2780 // as keys and can be used to indicate missing or deleted elements.
2781 bool IsKey(Object* k) {
2782 return !k->IsTheHole() && !k->IsUndefined();
2785 // Garbage collection support.
2786 void IteratePrefix(ObjectVisitor* visitor);
2787 void IterateElements(ObjectVisitor* visitor);
2790 static inline HashTable* cast(Object* obj);
2792 // Compute the probe offset (quadratic probing).
2793 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2794 return (n + n * n) >> 1;
2797 static const int kNumberOfElementsIndex = 0;
2798 static const int kNumberOfDeletedElementsIndex = 1;
2799 static const int kCapacityIndex = 2;
2800 static const int kPrefixStartIndex = 3;
2801 static const int kElementsStartIndex =
2802 kPrefixStartIndex + Shape::kPrefixSize;
2803 static const int kEntrySize = Shape::kEntrySize;
2804 static const int kElementsStartOffset =
2805 kHeaderSize + kElementsStartIndex * kPointerSize;
2806 static const int kCapacityOffset =
2807 kHeaderSize + kCapacityIndex * kPointerSize;
2809 // Constant used for denoting a absent entry.
2810 static const int kNotFound = -1;
2812 // Maximal capacity of HashTable. Based on maximal length of underlying
2813 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
2815 static const int kMaxCapacity =
2816 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
2818 // Find entry for key otherwise return kNotFound.
2819 inline int FindEntry(Key key);
2820 int FindEntry(Isolate* isolate, Key key);
2823 // Find the entry at which to insert element with the given key that
2824 // has the given hash value.
2825 uint32_t FindInsertionEntry(uint32_t hash);
2827 // Returns the index for an entry (of the key)
2828 static inline int EntryToIndex(int entry) {
2829 return (entry * kEntrySize) + kElementsStartIndex;
2832 // Update the number of elements in the hash table.
2833 void SetNumberOfElements(int nof) {
2834 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2837 // Update the number of deleted elements in the hash table.
2838 void SetNumberOfDeletedElements(int nod) {
2839 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2842 // Sets the capacity of the hash table.
2843 void SetCapacity(int capacity) {
2844 // To scale a computed hash code to fit within the hash table, we
2845 // use bit-wise AND with a mask, so the capacity must be positive
2847 ASSERT(capacity > 0);
2848 ASSERT(capacity <= kMaxCapacity);
2849 set(kCapacityIndex, Smi::FromInt(capacity));
2853 // Returns probe entry.
2854 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2855 ASSERT(IsPowerOf2(size));
2856 return (hash + GetProbeOffset(number)) & (size - 1);
2859 static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2860 return hash & (size - 1);
2863 static uint32_t NextProbe(uint32_t last, uint32_t number, uint32_t size) {
2864 return (last + number) & (size - 1);
2867 // Rehashes this hash-table into the new table.
2868 MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
2870 // Attempt to shrink hash table after removal of key.
2871 MUST_USE_RESULT MaybeObject* Shrink(Key key);
2873 // Ensure enough space for n additional elements.
2874 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
2878 // HashTableKey is an abstract superclass for virtual key behavior.
2879 class HashTableKey {
2881 // Returns whether the other object matches this key.
2882 virtual bool IsMatch(Object* other) = 0;
2883 // Returns the hash value for this key.
2884 virtual uint32_t Hash() = 0;
2885 // Returns the hash value for object.
2886 virtual uint32_t HashForObject(Object* key) = 0;
2887 // Returns the key object for storing into the hash table.
2888 // If allocations fails a failure object is returned.
2889 MUST_USE_RESULT virtual MaybeObject* AsObject() = 0;
2891 virtual ~HashTableKey() {}
2895 class SymbolTableShape : public BaseShape<HashTableKey*> {
2897 static inline bool IsMatch(HashTableKey* key, Object* value) {
2898 return key->IsMatch(value);
2900 static inline uint32_t Hash(HashTableKey* key) {
2903 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2904 return key->HashForObject(object);
2906 MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2907 return key->AsObject();
2910 static const int kPrefixSize = 0;
2911 static const int kEntrySize = 1;
2914 class SeqAsciiString;
2918 // No special elements in the prefix and the element size is 1
2919 // because only the symbol itself (the key) needs to be stored.
2920 class SymbolTable: public HashTable<SymbolTableShape, HashTableKey*> {
2922 // Find symbol in the symbol table. If it is not there yet, it is
2923 // added. The return value is the symbol table which might have
2924 // been enlarged. If the return value is not a failure, the symbol
2925 // pointer *s is set to the symbol found.
2926 MUST_USE_RESULT MaybeObject* LookupSymbol(Vector<const char> str, Object** s);
2927 MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Vector<const char> str,
2929 MUST_USE_RESULT MaybeObject* LookupSubStringAsciiSymbol(
2930 Handle<SeqAsciiString> str,
2934 MUST_USE_RESULT MaybeObject* LookupTwoByteSymbol(Vector<const uc16> str,
2936 MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
2938 // Looks up a symbol that is equal to the given string and returns
2939 // true if it is found, assigning the symbol to the given output
2941 bool LookupSymbolIfExists(String* str, String** symbol);
2942 bool LookupTwoCharsSymbolIfExists(uint32_t c1, uint32_t c2, String** symbol);
2945 static inline SymbolTable* cast(Object* obj);
2948 MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
2950 DISALLOW_IMPLICIT_CONSTRUCTORS(SymbolTable);
2954 class MapCacheShape : public BaseShape<HashTableKey*> {
2956 static inline bool IsMatch(HashTableKey* key, Object* value) {
2957 return key->IsMatch(value);
2959 static inline uint32_t Hash(HashTableKey* key) {
2963 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2964 return key->HashForObject(object);
2967 MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2968 return key->AsObject();
2971 static const int kPrefixSize = 0;
2972 static const int kEntrySize = 2;
2978 // Maps keys that are a fixed array of symbols to a map.
2979 // Used for canonicalize maps for object literals.
2980 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
2982 // Find cached value for a string key, otherwise return null.
2983 Object* Lookup(FixedArray* key);
2984 MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
2985 static inline MapCache* cast(Object* obj);
2988 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
2992 template <typename Shape, typename Key>
2993 class Dictionary: public HashTable<Shape, Key> {
2995 static inline Dictionary<Shape, Key>* cast(Object* obj) {
2996 return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
2999 // Returns the value at entry.
3000 Object* ValueAt(int entry) {
3001 return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
3004 // Set the value for entry.
3005 void ValueAtPut(int entry, Object* value) {
3006 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
3009 // Returns the property details for the property at entry.
3010 PropertyDetails DetailsAt(int entry) {
3011 ASSERT(entry >= 0); // Not found is -1, which is not caught by get().
3012 return PropertyDetails(
3013 Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
3016 // Set the details for entry.
3017 void DetailsAtPut(int entry, PropertyDetails value) {
3018 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
3022 void CopyValuesTo(FixedArray* elements);
3024 // Delete a property from the dictionary.
3025 Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
3027 // Attempt to shrink the dictionary after deletion of key.
3028 MUST_USE_RESULT MaybeObject* Shrink(Key key);
3030 // Returns the number of elements in the dictionary filtering out properties
3031 // with the specified attributes.
3032 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3034 // Returns the number of enumerable elements in the dictionary.
3035 int NumberOfEnumElements();
3037 enum SortMode { UNSORTED, SORTED };
3038 // Copies keys to preallocated fixed array.
3039 void CopyKeysTo(FixedArray* storage,
3040 PropertyAttributes filter,
3041 SortMode sort_mode);
3042 // Fill in details for properties into storage.
3043 void CopyKeysTo(FixedArray* storage, int index, SortMode sort_mode);
3045 // Accessors for next enumeration index.
3046 void SetNextEnumerationIndex(int index) {
3047 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3050 int NextEnumerationIndex() {
3051 return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
3054 // Returns a new array for dictionary usage. Might return Failure.
3055 MUST_USE_RESULT static MaybeObject* Allocate(int at_least_space_for);
3057 // Ensure enough space for n additional elements.
3058 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
3061 inline void Print() {
3064 void Print(FILE* out);
3066 // Returns the key (slow).
3067 Object* SlowReverseLookup(Object* value);
3069 // Sets the entry to (key, value) pair.
3070 inline void SetEntry(int entry,
3073 inline void SetEntry(int entry,
3076 PropertyDetails details);
3078 MUST_USE_RESULT MaybeObject* Add(Key key,
3080 PropertyDetails details);
3083 // Generic at put operation.
3084 MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
3086 // Add entry to dictionary.
3087 MUST_USE_RESULT MaybeObject* AddEntry(Key key,
3089 PropertyDetails details,
3092 // Generate new enumeration indices to avoid enumeration index overflow.
3093 MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
3094 static const int kMaxNumberKeyIndex =
3095 HashTable<Shape, Key>::kPrefixStartIndex;
3096 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3100 class StringDictionaryShape : public BaseShape<String*> {
3102 static inline bool IsMatch(String* key, Object* other);
3103 static inline uint32_t Hash(String* key);
3104 static inline uint32_t HashForObject(String* key, Object* object);
3105 MUST_USE_RESULT static inline MaybeObject* AsObject(String* key);
3106 static const int kPrefixSize = 2;
3107 static const int kEntrySize = 3;
3108 static const bool kIsEnumerable = true;
3112 class StringDictionary: public Dictionary<StringDictionaryShape, String*> {
3114 static inline StringDictionary* cast(Object* obj) {
3115 ASSERT(obj->IsDictionary());
3116 return reinterpret_cast<StringDictionary*>(obj);
3119 // Copies enumerable keys to preallocated fixed array.
3120 void CopyEnumKeysTo(FixedArray* storage, FixedArray* sort_array);
3122 // For transforming properties of a JSObject.
3123 MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
3125 int unused_property_fields);
3127 // Find entry for key, otherwise return kNotFound. Optimized version of
3128 // HashTable::FindEntry.
3129 int FindEntry(String* key);
3131 bool ContainsTransition(int entry);
3135 class NumberDictionaryShape : public BaseShape<uint32_t> {
3137 static inline bool IsMatch(uint32_t key, Object* other);
3138 MUST_USE_RESULT static inline MaybeObject* AsObject(uint32_t key);
3139 static const int kEntrySize = 3;
3140 static const bool kIsEnumerable = false;
3144 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3146 static const bool UsesSeed = true;
3147 static const int kPrefixSize = 2;
3149 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3150 static inline uint32_t SeededHashForObject(uint32_t key,
3156 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3158 static const int kPrefixSize = 0;
3160 static inline uint32_t Hash(uint32_t key);
3161 static inline uint32_t HashForObject(uint32_t key, Object* object);
3165 class SeededNumberDictionary
3166 : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
3168 static SeededNumberDictionary* cast(Object* obj) {
3169 ASSERT(obj->IsDictionary());
3170 return reinterpret_cast<SeededNumberDictionary*>(obj);
3173 // Type specific at put (default NONE attributes is used when adding).
3174 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3175 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
3177 PropertyDetails details);
3179 // Set an existing entry or add a new one if needed.
3180 // Return the updated dictionary.
3181 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3182 Handle<SeededNumberDictionary> dictionary,
3184 Handle<Object> value,
3185 PropertyDetails details);
3187 MUST_USE_RESULT MaybeObject* Set(uint32_t key,
3189 PropertyDetails details);
3191 void UpdateMaxNumberKey(uint32_t key);
3193 // If slow elements are required we will never go back to fast-case
3194 // for the elements kept in this dictionary. We require slow
3195 // elements if an element has been added at an index larger than
3196 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3197 // when defining a getter or setter with a number key.
3198 inline bool requires_slow_elements();
3199 inline void set_requires_slow_elements();
3201 // Get the value of the max number key that has been added to this
3202 // dictionary. max_number_key can only be called if
3203 // requires_slow_elements returns false.
3204 inline uint32_t max_number_key();
3207 static const int kRequiresSlowElementsMask = 1;
3208 static const int kRequiresSlowElementsTagSize = 1;
3209 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3213 class UnseededNumberDictionary
3214 : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
3216 static UnseededNumberDictionary* cast(Object* obj) {
3217 ASSERT(obj->IsDictionary());
3218 return reinterpret_cast<UnseededNumberDictionary*>(obj);
3221 // Type specific at put (default NONE attributes is used when adding).
3222 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3223 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
3225 // Set an existing entry or add a new one if needed.
3226 // Return the updated dictionary.
3227 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3228 Handle<UnseededNumberDictionary> dictionary,
3230 Handle<Object> value);
3232 MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
3236 template <int entrysize>
3237 class ObjectHashTableShape : public BaseShape<Object*> {
3239 static inline bool IsMatch(Object* key, Object* other);
3240 static inline uint32_t Hash(Object* key);
3241 static inline uint32_t HashForObject(Object* key, Object* object);
3242 MUST_USE_RESULT static inline MaybeObject* AsObject(Object* key);
3243 static const int kPrefixSize = 0;
3244 static const int kEntrySize = entrysize;
3248 // ObjectHashSet holds keys that are arbitrary objects by using the identity
3249 // hash of the key for hashing purposes.
3250 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
3252 static inline ObjectHashSet* cast(Object* obj) {
3253 ASSERT(obj->IsHashTable());
3254 return reinterpret_cast<ObjectHashSet*>(obj);
3257 // Looks up whether the given key is part of this hash set.
3258 bool Contains(Object* key);
3260 // Adds the given key to this hash set.
3261 MUST_USE_RESULT MaybeObject* Add(Object* key);
3263 // Removes the given key from this hash set.
3264 MUST_USE_RESULT MaybeObject* Remove(Object* key);
3268 // ObjectHashTable maps keys that are arbitrary objects to object values by
3269 // using the identity hash of the key for hashing purposes.
3270 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
3272 static inline ObjectHashTable* cast(Object* obj) {
3273 ASSERT(obj->IsHashTable());
3274 return reinterpret_cast<ObjectHashTable*>(obj);
3277 // Looks up the value associated with the given key. The undefined value is
3278 // returned in case the key is not present.
3279 Object* Lookup(Object* key);
3281 // Adds (or overwrites) the value associated with the given key. Mapping a
3282 // key to the undefined value causes removal of the whole entry.
3283 MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
3286 friend class MarkCompactCollector;
3288 void AddEntry(int entry, Object* key, Object* value);
3289 void RemoveEntry(int entry);
3291 // Returns the index to the value of an entry.
3292 static inline int EntryToValueIndex(int entry) {
3293 return EntryToIndex(entry) + 1;
3298 // JSFunctionResultCache caches results of some JSFunction invocation.
3299 // It is a fixed array with fixed structure:
3300 // [0]: factory function
3301 // [1]: finger index
3302 // [2]: current cache size
3303 // [3]: dummy field.
3304 // The rest of array are key/value pairs.
3305 class JSFunctionResultCache: public FixedArray {
3307 static const int kFactoryIndex = 0;
3308 static const int kFingerIndex = kFactoryIndex + 1;
3309 static const int kCacheSizeIndex = kFingerIndex + 1;
3310 static const int kDummyIndex = kCacheSizeIndex + 1;
3311 static const int kEntriesIndex = kDummyIndex + 1;
3313 static const int kEntrySize = 2; // key + value
3315 static const int kFactoryOffset = kHeaderSize;
3316 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3317 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3319 inline void MakeZeroSize();
3320 inline void Clear();
3323 inline void set_size(int size);
3324 inline int finger_index();
3325 inline void set_finger_index(int finger_index);
3328 static inline JSFunctionResultCache* cast(Object* obj);
3331 void JSFunctionResultCacheVerify();
3336 // ScopeInfo represents information about different scopes of a source
3337 // program and the allocation of the scope's variables. Scope information
3338 // is stored in a compressed form in ScopeInfo objects and is used
3339 // at runtime (stack dumps, deoptimization, etc.).
3341 // This object provides quick access to scope info details for runtime
3343 class ScopeInfo : public FixedArray {
3345 static inline ScopeInfo* cast(Object* object);
3347 // Return the type of this scope.
3350 // Does this scope call eval?
3353 // Return the language mode of this scope.
3354 LanguageMode language_mode();
3356 // Does this scope make a non-strict eval call?
3357 bool CallsNonStrictEval() {
3358 return CallsEval() && (language_mode() == CLASSIC_MODE);
3361 // Return the total number of locals allocated on the stack and in the
3362 // context. This includes the parameters that are allocated in the context.
3365 // Return the number of stack slots for code. This number consists of two
3367 // 1. One stack slot per stack allocated local.
3368 // 2. One stack slot for the function name if it is stack allocated.
3369 int StackSlotCount();
3371 // Return the number of context slots for code if a context is allocated. This
3372 // number consists of three parts:
3373 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3374 // 2. One context slot per context allocated local.
3375 // 3. One context slot for the function name if it is context allocated.
3376 // Parameters allocated in the context count as context allocated locals. If
3377 // no contexts are allocated for this scope ContextLength returns 0.
3378 int ContextLength();
3380 // Is this scope the scope of a named function expression?
3381 bool HasFunctionName();
3383 // Return if this has context allocated locals.
3384 bool HasHeapAllocatedLocals();
3386 // Return if contexts are allocated for this scope.
3389 // Return the function_name if present.
3390 String* FunctionName();
3392 // Return the name of the given parameter.
3393 String* ParameterName(int var);
3395 // Return the name of the given local.
3396 String* LocalName(int var);
3398 // Return the name of the given stack local.
3399 String* StackLocalName(int var);
3401 // Return the name of the given context local.
3402 String* ContextLocalName(int var);
3404 // Return the mode of the given context local.
3405 VariableMode ContextLocalMode(int var);
3407 // Return the initialization flag of the given context local.
3408 InitializationFlag ContextLocalInitFlag(int var);
3410 // Lookup support for serialized scope info. Returns the
3411 // the stack slot index for a given slot name if the slot is
3412 // present; otherwise returns a value < 0. The name must be a symbol
3414 int StackSlotIndex(String* name);
3416 // Lookup support for serialized scope info. Returns the
3417 // context slot index for a given slot name if the slot is present; otherwise
3418 // returns a value < 0. The name must be a symbol (canonicalized).
3419 // If the slot is present and mode != NULL, sets *mode to the corresponding
3420 // mode for that variable.
3421 int ContextSlotIndex(String* name,
3423 InitializationFlag* init_flag);
3425 // Lookup support for serialized scope info. Returns the
3426 // parameter index for a given parameter name if the parameter is present;
3427 // otherwise returns a value < 0. The name must be a symbol (canonicalized).
3428 int ParameterIndex(String* name);
3430 // Lookup support for serialized scope info. Returns the function context
3431 // slot index if the function name is present and context-allocated (named
3432 // function expressions, only), otherwise returns a value < 0. The name
3433 // must be a symbol (canonicalized).
3434 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3436 static Handle<ScopeInfo> Create(Scope* scope);
3438 // Serializes empty scope info.
3439 static ScopeInfo* Empty();
3445 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3446 // numeric and occupies one array slot.
3447 // 1. A set of properties of the scope
3448 // 2. The number of parameters. This only applies to function scopes. For
3449 // non-function scopes this is 0.
3450 // 3. The number of non-parameter variables allocated on the stack.
3451 // 4. The number of non-parameter and parameter variables allocated in the
3453 #define FOR_EACH_NUMERIC_FIELD(V) \
3456 V(StackLocalCount) \
3457 V(ContextLocalCount)
3459 #define FIELD_ACCESSORS(name) \
3460 void Set##name(int value) { \
3461 set(k##name, Smi::FromInt(value)); \
3464 if (length() > 0) { \
3465 return Smi::cast(get(k##name))->value(); \
3470 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3471 #undef FIELD_ACCESSORS
3475 #define DECL_INDEX(name) k##name,
3476 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
3478 #undef FOR_EACH_NUMERIC_FIELD
3482 // The layout of the variable part of a ScopeInfo is as follows:
3483 // 1. ParameterEntries:
3484 // This part stores the names of the parameters for function scopes. One
3485 // slot is used per parameter, so in total this part occupies
3486 // ParameterCount() slots in the array. For other scopes than function
3487 // scopes ParameterCount() is 0.
3488 // 2. StackLocalEntries:
3489 // Contains the names of local variables that are allocated on the stack,
3490 // in increasing order of the stack slot index. One slot is used per stack
3491 // local, so in total this part occupies StackLocalCount() slots in the
3493 // 3. ContextLocalNameEntries:
3494 // Contains the names of local variables and parameters that are allocated
3495 // in the context. They are stored in increasing order of the context slot
3496 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3497 // context local, so in total this part occupies ContextLocalCount() slots
3499 // 4. ContextLocalInfoEntries:
3500 // Contains the variable modes and initialization flags corresponding to
3501 // the context locals in ContextLocalNameEntries. One slot is used per
3502 // context local, so in total this part occupies ContextLocalCount()
3503 // slots in the array.
3504 // 5. FunctionNameEntryIndex:
3505 // If the scope belongs to a named function expression this part contains
3506 // information about the function variable. It always occupies two array
3507 // slots: a. The name of the function variable.
3508 // b. The context or stack slot index for the variable.
3509 int ParameterEntriesIndex();
3510 int StackLocalEntriesIndex();
3511 int ContextLocalNameEntriesIndex();
3512 int ContextLocalInfoEntriesIndex();
3513 int FunctionNameEntryIndex();
3515 // Location of the function variable for named function expressions.
3516 enum FunctionVariableInfo {
3517 NONE, // No function name present.
3523 // Properties of scopes.
3524 class TypeField: public BitField<ScopeType, 0, 3> {};
3525 class CallsEvalField: public BitField<bool, 3, 1> {};
3526 class LanguageModeField: public BitField<LanguageMode, 4, 2> {};
3527 class FunctionVariableField: public BitField<FunctionVariableInfo, 6, 2> {};
3528 class FunctionVariableMode: public BitField<VariableMode, 8, 3> {};
3530 // BitFields representing the encoded information for context locals in the
3531 // ContextLocalInfoEntries part.
3532 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
3533 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
3537 // The cache for maps used by normalized (dictionary mode) objects.
3538 // Such maps do not have property descriptors, so a typical program
3539 // needs very limited number of distinct normalized maps.
3540 class NormalizedMapCache: public FixedArray {
3542 static const int kEntries = 64;
3544 MUST_USE_RESULT MaybeObject* Get(JSObject* object,
3545 PropertyNormalizationMode mode);
3550 static inline NormalizedMapCache* cast(Object* obj);
3553 void NormalizedMapCacheVerify();
3558 // ByteArray represents fixed sized byte arrays. Used for the relocation info
3559 // that is attached to code objects.
3560 class ByteArray: public FixedArrayBase {
3562 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
3564 // Setter and getter.
3565 inline byte get(int index);
3566 inline void set(int index, byte value);
3568 // Treat contents as an int array.
3569 inline int get_int(int index);
3571 static int SizeFor(int length) {
3572 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
3574 // We use byte arrays for free blocks in the heap. Given a desired size in
3575 // bytes that is a multiple of the word size and big enough to hold a byte
3576 // array, this function returns the number of elements a byte array should
3578 static int LengthFor(int size_in_bytes) {
3579 ASSERT(IsAligned(size_in_bytes, kPointerSize));
3580 ASSERT(size_in_bytes >= kHeaderSize);
3581 return size_in_bytes - kHeaderSize;
3584 // Returns data start address.
3585 inline Address GetDataStartAddress();
3587 // Returns a pointer to the ByteArray object for a given data start address.
3588 static inline ByteArray* FromDataStartAddress(Address address);
3591 static inline ByteArray* cast(Object* obj);
3593 // Dispatched behavior.
3594 inline int ByteArraySize() {
3595 return SizeFor(this->length());
3598 inline void ByteArrayPrint() {
3599 ByteArrayPrint(stdout);
3601 void ByteArrayPrint(FILE* out);
3604 void ByteArrayVerify();
3607 // Layout description.
3608 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3610 // Maximal memory consumption for a single ByteArray.
3611 static const int kMaxSize = 512 * MB;
3612 // Maximal length of a single ByteArray.
3613 static const int kMaxLength = kMaxSize - kHeaderSize;
3616 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
3620 // FreeSpace represents fixed sized areas of the heap that are not currently in
3621 // use. Used by the heap and GC.
3622 class FreeSpace: public HeapObject {
3624 // [size]: size of the free space including the header.
3626 inline void set_size(int value);
3628 inline int Size() { return size(); }
3631 static inline FreeSpace* cast(Object* obj);
3634 inline void FreeSpacePrint() {
3635 FreeSpacePrint(stdout);
3637 void FreeSpacePrint(FILE* out);
3640 void FreeSpaceVerify();
3643 // Layout description.
3644 // Size is smi tagged when it is stored.
3645 static const int kSizeOffset = HeapObject::kHeaderSize;
3646 static const int kHeaderSize = kSizeOffset + kPointerSize;
3648 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3651 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
3655 // An ExternalArray represents a fixed-size array of primitive values
3656 // which live outside the JavaScript heap. Its subclasses are used to
3657 // implement the CanvasArray types being defined in the WebGL
3658 // specification. As of this writing the first public draft is not yet
3659 // available, but Khronos members can access the draft at:
3660 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
3662 // The semantics of these arrays differ from CanvasPixelArray.
3663 // Out-of-range values passed to the setter are converted via a C
3664 // cast, not clamping. Out-of-range indices cause exceptions to be
3665 // raised rather than being silently ignored.
3666 class ExternalArray: public FixedArrayBase {
3668 inline bool is_the_hole(int index) { return false; }
3670 // [external_pointer]: The pointer to the external memory area backing this
3672 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
3675 static inline ExternalArray* cast(Object* obj);
3677 // Maximal acceptable length for an external array.
3678 static const int kMaxLength = 0x3fffffff;
3680 // ExternalArray headers are not quadword aligned.
3681 static const int kExternalPointerOffset =
3682 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
3683 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
3684 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3687 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
3691 // A ExternalPixelArray represents a fixed-size byte array with special
3692 // semantics used for implementing the CanvasPixelArray object. Please see the
3693 // specification at:
3695 // http://www.whatwg.org/specs/web-apps/current-work/
3696 // multipage/the-canvas-element.html#canvaspixelarray
3697 // In particular, write access clamps the value written to 0 or 255 if the
3698 // value written is outside this range.
3699 class ExternalPixelArray: public ExternalArray {
3701 inline uint8_t* external_pixel_pointer();
3703 // Setter and getter.
3704 inline uint8_t get_scalar(int index);
3705 MUST_USE_RESULT inline MaybeObject* get(int index);
3706 inline void set(int index, uint8_t value);
3708 // This accessor applies the correct conversion from Smi, HeapNumber and
3709 // undefined and clamps the converted value between 0 and 255.
3710 Object* SetValue(uint32_t index, Object* value);
3713 static inline ExternalPixelArray* cast(Object* obj);
3716 inline void ExternalPixelArrayPrint() {
3717 ExternalPixelArrayPrint(stdout);
3719 void ExternalPixelArrayPrint(FILE* out);
3722 void ExternalPixelArrayVerify();
3726 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalPixelArray);
3730 class ExternalByteArray: public ExternalArray {
3732 // Setter and getter.
3733 inline int8_t get_scalar(int index);
3734 MUST_USE_RESULT inline MaybeObject* get(int index);
3735 inline void set(int index, int8_t value);
3737 // This accessor applies the correct conversion from Smi, HeapNumber
3739 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3742 static inline ExternalByteArray* cast(Object* obj);
3745 inline void ExternalByteArrayPrint() {
3746 ExternalByteArrayPrint(stdout);
3748 void ExternalByteArrayPrint(FILE* out);
3751 void ExternalByteArrayVerify();
3755 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalByteArray);
3759 class ExternalUnsignedByteArray: public ExternalArray {
3761 // Setter and getter.
3762 inline uint8_t get_scalar(int index);
3763 MUST_USE_RESULT inline MaybeObject* get(int index);
3764 inline void set(int index, uint8_t value);
3766 // This accessor applies the correct conversion from Smi, HeapNumber
3768 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3771 static inline ExternalUnsignedByteArray* cast(Object* obj);
3774 inline void ExternalUnsignedByteArrayPrint() {
3775 ExternalUnsignedByteArrayPrint(stdout);
3777 void ExternalUnsignedByteArrayPrint(FILE* out);
3780 void ExternalUnsignedByteArrayVerify();
3784 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedByteArray);
3788 class ExternalShortArray: public ExternalArray {
3790 // Setter and getter.
3791 inline int16_t get_scalar(int index);
3792 MUST_USE_RESULT inline MaybeObject* get(int index);
3793 inline void set(int index, int16_t value);
3795 // This accessor applies the correct conversion from Smi, HeapNumber
3797 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3800 static inline ExternalShortArray* cast(Object* obj);
3803 inline void ExternalShortArrayPrint() {
3804 ExternalShortArrayPrint(stdout);
3806 void ExternalShortArrayPrint(FILE* out);
3809 void ExternalShortArrayVerify();
3813 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalShortArray);
3817 class ExternalUnsignedShortArray: public ExternalArray {
3819 // Setter and getter.
3820 inline uint16_t get_scalar(int index);
3821 MUST_USE_RESULT inline MaybeObject* get(int index);
3822 inline void set(int index, uint16_t value);
3824 // This accessor applies the correct conversion from Smi, HeapNumber
3826 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3829 static inline ExternalUnsignedShortArray* cast(Object* obj);
3832 inline void ExternalUnsignedShortArrayPrint() {
3833 ExternalUnsignedShortArrayPrint(stdout);
3835 void ExternalUnsignedShortArrayPrint(FILE* out);
3838 void ExternalUnsignedShortArrayVerify();
3842 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedShortArray);
3846 class ExternalIntArray: public ExternalArray {
3848 // Setter and getter.
3849 inline int32_t get_scalar(int index);
3850 MUST_USE_RESULT inline MaybeObject* get(int index);
3851 inline void set(int index, int32_t value);
3853 // This accessor applies the correct conversion from Smi, HeapNumber
3855 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3858 static inline ExternalIntArray* cast(Object* obj);
3861 inline void ExternalIntArrayPrint() {
3862 ExternalIntArrayPrint(stdout);
3864 void ExternalIntArrayPrint(FILE* out);
3867 void ExternalIntArrayVerify();
3871 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalIntArray);
3875 class ExternalUnsignedIntArray: public ExternalArray {
3877 // Setter and getter.
3878 inline uint32_t get_scalar(int index);
3879 MUST_USE_RESULT inline MaybeObject* get(int index);
3880 inline void set(int index, uint32_t value);
3882 // This accessor applies the correct conversion from Smi, HeapNumber
3884 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3887 static inline ExternalUnsignedIntArray* cast(Object* obj);
3890 inline void ExternalUnsignedIntArrayPrint() {
3891 ExternalUnsignedIntArrayPrint(stdout);
3893 void ExternalUnsignedIntArrayPrint(FILE* out);
3896 void ExternalUnsignedIntArrayVerify();
3900 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedIntArray);
3904 class ExternalFloatArray: public ExternalArray {
3906 // Setter and getter.
3907 inline float get_scalar(int index);
3908 MUST_USE_RESULT inline MaybeObject* get(int index);
3909 inline void set(int index, float value);
3911 // This accessor applies the correct conversion from Smi, HeapNumber
3913 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3916 static inline ExternalFloatArray* cast(Object* obj);
3919 inline void ExternalFloatArrayPrint() {
3920 ExternalFloatArrayPrint(stdout);
3922 void ExternalFloatArrayPrint(FILE* out);
3925 void ExternalFloatArrayVerify();
3929 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloatArray);
3933 class ExternalDoubleArray: public ExternalArray {
3935 // Setter and getter.
3936 inline double get_scalar(int index);
3937 MUST_USE_RESULT inline MaybeObject* get(int index);
3938 inline void set(int index, double value);
3940 // This accessor applies the correct conversion from Smi, HeapNumber
3942 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3945 static inline ExternalDoubleArray* cast(Object* obj);
3948 inline void ExternalDoubleArrayPrint() {
3949 ExternalDoubleArrayPrint(stdout);
3951 void ExternalDoubleArrayPrint(FILE* out);
3952 #endif // OBJECT_PRINT
3954 void ExternalDoubleArrayVerify();
3958 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalDoubleArray);
3962 // DeoptimizationInputData is a fixed array used to hold the deoptimization
3963 // data for code generated by the Hydrogen/Lithium compiler. It also
3964 // contains information about functions that were inlined. If N different
3965 // functions were inlined then first N elements of the literal array will
3966 // contain these functions.
3969 class DeoptimizationInputData: public FixedArray {
3971 // Layout description. Indices in the array.
3972 static const int kTranslationByteArrayIndex = 0;
3973 static const int kInlinedFunctionCountIndex = 1;
3974 static const int kLiteralArrayIndex = 2;
3975 static const int kOsrAstIdIndex = 3;
3976 static const int kOsrPcOffsetIndex = 4;
3977 static const int kFirstDeoptEntryIndex = 5;
3979 // Offsets of deopt entry elements relative to the start of the entry.
3980 static const int kAstIdOffset = 0;
3981 static const int kTranslationIndexOffset = 1;
3982 static const int kArgumentsStackHeightOffset = 2;
3983 static const int kPcOffset = 3;
3984 static const int kDeoptEntrySize = 4;
3986 // Simple element accessors.
3987 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
3989 return type::cast(get(k##name##Index)); \
3991 void Set##name(type* value) { \
3992 set(k##name##Index, value); \
3995 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
3996 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
3997 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
3998 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
3999 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4001 #undef DEFINE_ELEMENT_ACCESSORS
4003 // Accessors for elements of the ith deoptimization entry.
4004 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4005 type* name(int i) { \
4006 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4008 void Set##name(int i, type* value) { \
4009 set(IndexForEntry(i) + k##name##Offset, value); \
4012 DEFINE_ENTRY_ACCESSORS(AstId, Smi)
4013 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4014 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4015 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4017 #undef DEFINE_ENTRY_ACCESSORS
4020 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4023 // Allocates a DeoptimizationInputData.
4024 MUST_USE_RESULT static MaybeObject* Allocate(int deopt_entry_count,
4025 PretenureFlag pretenure);
4028 static inline DeoptimizationInputData* cast(Object* obj);
4030 #ifdef ENABLE_DISASSEMBLER
4031 void DeoptimizationInputDataPrint(FILE* out);
4035 static int IndexForEntry(int i) {
4036 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4039 static int LengthFor(int entry_count) {
4040 return IndexForEntry(entry_count);
4045 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4046 // data for code generated by the full compiler.
4047 // The format of the these objects is
4048 // [i * 2]: Ast ID for ith deoptimization.
4049 // [i * 2 + 1]: PC and state of ith deoptimization
4050 class DeoptimizationOutputData: public FixedArray {
4052 int DeoptPoints() { return length() / 2; }
4053 Smi* AstId(int index) { return Smi::cast(get(index * 2)); }
4054 void SetAstId(int index, Smi* id) { set(index * 2, id); }
4055 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4056 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4058 static int LengthOfFixedArray(int deopt_points) {
4059 return deopt_points * 2;
4062 // Allocates a DeoptimizationOutputData.
4063 MUST_USE_RESULT static MaybeObject* Allocate(int number_of_deopt_points,
4064 PretenureFlag pretenure);
4067 static inline DeoptimizationOutputData* cast(Object* obj);
4069 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4070 void DeoptimizationOutputDataPrint(FILE* out);
4075 // Forward declaration.
4076 class JSGlobalPropertyCell;
4078 // TypeFeedbackCells is a fixed array used to hold the association between
4079 // cache cells and AST ids for code generated by the full compiler.
4080 // The format of the these objects is
4081 // [i * 2]: Global property cell of ith cache cell.
4082 // [i * 2 + 1]: Ast ID for ith cache cell.
4083 class TypeFeedbackCells: public FixedArray {
4085 int CellCount() { return length() / 2; }
4086 static int LengthOfFixedArray(int cell_count) { return cell_count * 2; }
4088 // Accessors for AST ids associated with cache values.
4089 inline Smi* AstId(int index);
4090 inline void SetAstId(int index, Smi* id);
4092 // Accessors for global property cells holding the cache values.
4093 inline JSGlobalPropertyCell* Cell(int index);
4094 inline void SetCell(int index, JSGlobalPropertyCell* cell);
4096 // The object that indicates an uninitialized cache.
4097 static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
4099 // The object that indicates a megamorphic state.
4100 static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
4102 // A raw version of the uninitialized sentinel that's safe to read during
4103 // garbage collection (e.g., for patching the cache).
4104 static inline Object* RawUninitializedSentinel(Heap* heap);
4107 static inline TypeFeedbackCells* cast(Object* obj);
4109 static const int kForInFastCaseMarker = 0;
4110 static const int kForInSlowCaseMarker = 1;
4114 // Forward declaration.
4115 class SafepointEntry;
4116 class TypeFeedbackInfo;
4118 // Code describes objects with on-the-fly generated machine code.
4119 class Code: public HeapObject {
4121 // Opaque data type for encapsulating code flags like kind, inline
4122 // cache state, and arguments count.
4123 // FLAGS_MIN_VALUE and FLAGS_MAX_VALUE are specified to ensure that
4124 // enumeration type has correct value range (see Issue 830 for more details).
4126 FLAGS_MIN_VALUE = kMinInt,
4127 FLAGS_MAX_VALUE = kMaxInt
4145 // No more than 16 kinds. The value currently encoded in four bits in
4150 FIRST_IC_KIND = LOAD_IC,
4151 LAST_IC_KIND = TO_BOOLEAN_IC
4155 NUMBER_OF_KINDS = LAST_IC_KIND + 1
4158 typedef int ExtraICState;
4160 static const ExtraICState kNoExtraICState = 0;
4162 #ifdef ENABLE_DISASSEMBLER
4164 static const char* Kind2String(Kind kind);
4165 static const char* ICState2String(InlineCacheState state);
4166 static const char* PropertyType2String(PropertyType type);
4167 static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
4168 inline void Disassemble(const char* name) {
4169 Disassemble(name, stdout);
4171 void Disassemble(const char* name, FILE* out);
4172 #endif // ENABLE_DISASSEMBLER
4174 // [instruction_size]: Size of the native instructions
4175 inline int instruction_size();
4176 inline void set_instruction_size(int value);
4178 // [relocation_info]: Code relocation information
4179 DECL_ACCESSORS(relocation_info, ByteArray)
4180 void InvalidateRelocation();
4182 // [handler_table]: Fixed array containing offsets of exception handlers.
4183 DECL_ACCESSORS(handler_table, FixedArray)
4185 // [deoptimization_data]: Array containing data for deopt.
4186 DECL_ACCESSORS(deoptimization_data, FixedArray)
4188 // [type_feedback_info]: Struct containing type feedback information.
4189 // Will contain either a TypeFeedbackInfo object, or undefined.
4190 DECL_ACCESSORS(type_feedback_info, Object)
4192 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4193 // field does not have to be traced during garbage collection since
4194 // it is only used by the garbage collector itself.
4195 DECL_ACCESSORS(gc_metadata, Object)
4197 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4198 // at the moment when this object was created.
4199 inline void set_ic_age(int count);
4200 inline int ic_age();
4202 // Unchecked accessors to be used during GC.
4203 inline ByteArray* unchecked_relocation_info();
4204 inline FixedArray* unchecked_deoptimization_data();
4206 inline int relocation_size();
4208 // [flags]: Various code flags.
4209 inline Flags flags();
4210 inline void set_flags(Flags flags);
4212 // [flags]: Access to specific code flags.
4214 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4215 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4216 inline PropertyType type(); // Only valid for monomorphic IC stubs.
4217 inline int arguments_count(); // Only valid for call IC stubs.
4219 // Testers for IC stub kinds.
4220 inline bool is_inline_cache_stub();
4221 inline bool is_load_stub() { return kind() == LOAD_IC; }
4222 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4223 inline bool is_store_stub() { return kind() == STORE_IC; }
4224 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4225 inline bool is_call_stub() { return kind() == CALL_IC; }
4226 inline bool is_keyed_call_stub() { return kind() == KEYED_CALL_IC; }
4227 inline bool is_unary_op_stub() { return kind() == UNARY_OP_IC; }
4228 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4229 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4230 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4232 // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
4233 inline int major_key();
4234 inline void set_major_key(int value);
4236 // For stubs, tells whether they should always exist, so that they can be
4237 // called from other stubs.
4238 inline bool is_pregenerated();
4239 inline void set_is_pregenerated(bool value);
4241 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
4242 inline bool optimizable();
4243 inline void set_optimizable(bool value);
4245 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4246 // deoptimization support.
4247 inline bool has_deoptimization_support();
4248 inline void set_has_deoptimization_support(bool value);
4250 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4251 // been compiled with debug break slots.
4252 inline bool has_debug_break_slots();
4253 inline void set_has_debug_break_slots(bool value);
4255 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
4256 // been compiled with IsOptimizing set to true.
4257 inline bool is_compiled_optimizable();
4258 inline void set_compiled_optimizable(bool value);
4260 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4261 // how long the function has been marked for OSR and therefore which
4262 // level of loop nesting we are willing to do on-stack replacement
4264 inline void set_allow_osr_at_loop_nesting_level(int level);
4265 inline int allow_osr_at_loop_nesting_level();
4267 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4268 // the code object was seen on the stack with no IC patching going on.
4269 inline int profiler_ticks();
4270 inline void set_profiler_ticks(int ticks);
4272 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4273 // reserved in the code prologue.
4274 inline unsigned stack_slots();
4275 inline void set_stack_slots(unsigned slots);
4277 // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
4278 // the instruction stream where the safepoint table starts.
4279 inline unsigned safepoint_table_offset();
4280 inline void set_safepoint_table_offset(unsigned offset);
4282 // [stack_check_table_start]: For kind FUNCTION, the offset in the
4283 // instruction stream where the stack check table starts.
4284 inline unsigned stack_check_table_offset();
4285 inline void set_stack_check_table_offset(unsigned offset);
4287 // [check type]: For kind CALL_IC, tells how to check if the
4288 // receiver is valid for the given call.
4289 inline CheckType check_type();
4290 inline void set_check_type(CheckType value);
4292 // [type-recording unary op type]: For kind UNARY_OP_IC.
4293 inline byte unary_op_type();
4294 inline void set_unary_op_type(byte value);
4296 // [type-recording binary op type]: For kind BINARY_OP_IC.
4297 inline byte binary_op_type();
4298 inline void set_binary_op_type(byte value);
4299 inline byte binary_op_result_type();
4300 inline void set_binary_op_result_type(byte value);
4302 // [compare state]: For kind COMPARE_IC, tells what state the stub is in.
4303 inline byte compare_state();
4304 inline void set_compare_state(byte value);
4306 // [compare_operation]: For kind COMPARE_IC tells what compare operation the
4307 // stub was generated for.
4308 inline byte compare_operation();
4309 inline void set_compare_operation(byte value);
4311 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4312 inline byte to_boolean_state();
4313 inline void set_to_boolean_state(byte value);
4315 // [has_function_cache]: For kind STUB tells whether there is a function
4316 // cache is passed to the stub.
4317 inline bool has_function_cache();
4318 inline void set_has_function_cache(bool flag);
4320 // Get the safepoint entry for the given pc.
4321 SafepointEntry GetSafepointEntry(Address pc);
4323 // Mark this code object as not having a stack check table. Assumes kind
4325 void SetNoStackCheckTable();
4327 // Find the first map in an IC stub.
4328 Map* FindFirstMap();
4330 class ExtraICStateStrictMode: public BitField<StrictModeFlag, 0, 1> {};
4331 class ExtraICStateKeyedAccessGrowMode:
4332 public BitField<KeyedAccessGrowMode, 1, 1> {}; // NOLINT
4334 static const int kExtraICStateGrowModeShift = 1;
4336 static inline StrictModeFlag GetStrictMode(ExtraICState extra_ic_state) {
4337 return ExtraICStateStrictMode::decode(extra_ic_state);
4340 static inline KeyedAccessGrowMode GetKeyedAccessGrowMode(
4341 ExtraICState extra_ic_state) {
4342 return ExtraICStateKeyedAccessGrowMode::decode(extra_ic_state);
4345 static inline ExtraICState ComputeExtraICState(
4346 KeyedAccessGrowMode grow_mode,
4347 StrictModeFlag strict_mode) {
4348 return ExtraICStateKeyedAccessGrowMode::encode(grow_mode) |
4349 ExtraICStateStrictMode::encode(strict_mode);
4352 // Flags operations.
4353 static inline Flags ComputeFlags(
4355 InlineCacheState ic_state = UNINITIALIZED,
4356 ExtraICState extra_ic_state = kNoExtraICState,
4357 PropertyType type = NORMAL,
4359 InlineCacheHolderFlag holder = OWN_MAP);
4361 static inline Flags ComputeMonomorphicFlags(
4364 ExtraICState extra_ic_state = kNoExtraICState,
4365 InlineCacheHolderFlag holder = OWN_MAP,
4368 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4369 static inline PropertyType ExtractTypeFromFlags(Flags flags);
4370 static inline Kind ExtractKindFromFlags(Flags flags);
4371 static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4372 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4373 static inline int ExtractArgumentsCountFromFlags(Flags flags);
4375 static inline Flags RemoveTypeFromFlags(Flags flags);
4377 // Convert a target address into a code object.
4378 static inline Code* GetCodeFromTargetAddress(Address address);
4380 // Convert an entry address into an object.
4381 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4383 // Returns the address of the first instruction.
4384 inline byte* instruction_start();
4386 // Returns the address right after the last instruction.
4387 inline byte* instruction_end();
4389 // Returns the size of the instructions, padding, and relocation information.
4390 inline int body_size();
4392 // Returns the address of the first relocation info (read backwards!).
4393 inline byte* relocation_start();
4395 // Code entry point.
4396 inline byte* entry();
4398 // Returns true if pc is inside this object's instructions.
4399 inline bool contains(byte* pc);
4401 // Relocate the code by delta bytes. Called to signal that this code
4402 // object has been moved by delta bytes.
4403 void Relocate(intptr_t delta);
4405 // Migrate code described by desc.
4406 void CopyFrom(const CodeDesc& desc);
4408 // Returns the object size for a given body (used for allocation).
4409 static int SizeFor(int body_size) {
4410 ASSERT_SIZE_TAG_ALIGNED(body_size);
4411 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4414 // Calculate the size of the code object to report for log events. This takes
4415 // the layout of the code object into account.
4416 int ExecutableSize() {
4417 // Check that the assumptions about the layout of the code object holds.
4418 ASSERT_EQ(static_cast<int>(instruction_start() - address()),
4420 return instruction_size() + Code::kHeaderSize;
4423 // Locating source position.
4424 int SourcePosition(Address pc);
4425 int SourceStatementPosition(Address pc);
4428 static inline Code* cast(Object* obj);
4430 // Dispatched behavior.
4431 int CodeSize() { return SizeFor(body_size()); }
4432 inline void CodeIterateBody(ObjectVisitor* v);
4434 template<typename StaticVisitor>
4435 inline void CodeIterateBody(Heap* heap);
4437 inline void CodePrint() {
4440 void CodePrint(FILE* out);
4445 void ClearInlineCaches();
4446 void ClearTypeFeedbackCells(Heap* heap);
4448 // Max loop nesting marker used to postpose OSR. We don't take loop
4449 // nesting that is deeper than 5 levels into account.
4450 static const int kMaxLoopNestingMarker = 6;
4452 // Layout description.
4453 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
4454 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
4455 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4456 static const int kDeoptimizationDataOffset =
4457 kHandlerTableOffset + kPointerSize;
4458 static const int kTypeFeedbackInfoOffset =
4459 kDeoptimizationDataOffset + kPointerSize;
4460 static const int kGCMetadataOffset = kTypeFeedbackInfoOffset + kPointerSize;
4461 static const int kICAgeOffset =
4462 kGCMetadataOffset + kPointerSize;
4463 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4464 static const int kKindSpecificFlagsOffset = kFlagsOffset + kIntSize;
4465 static const int kKindSpecificFlagsSize = 2 * kIntSize;
4467 static const int kHeaderPaddingStart = kKindSpecificFlagsOffset +
4468 kKindSpecificFlagsSize;
4470 // Add padding to align the instruction start following right after
4471 // the Code object header.
4472 static const int kHeaderSize =
4473 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4475 // Byte offsets within kKindSpecificFlagsOffset.
4476 static const int kStubMajorKeyOffset = kKindSpecificFlagsOffset;
4477 static const int kOptimizableOffset = kKindSpecificFlagsOffset;
4478 static const int kStackSlotsOffset = kKindSpecificFlagsOffset;
4479 static const int kCheckTypeOffset = kKindSpecificFlagsOffset;
4481 static const int kUnaryOpTypeOffset = kStubMajorKeyOffset + 1;
4482 static const int kBinaryOpTypeOffset = kStubMajorKeyOffset + 1;
4483 static const int kCompareStateOffset = kStubMajorKeyOffset + 1;
4484 static const int kToBooleanTypeOffset = kStubMajorKeyOffset + 1;
4485 static const int kHasFunctionCacheOffset = kStubMajorKeyOffset + 1;
4487 static const int kFullCodeFlags = kOptimizableOffset + 1;
4488 class FullCodeFlagsHasDeoptimizationSupportField:
4489 public BitField<bool, 0, 1> {}; // NOLINT
4490 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4491 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
4493 static const int kBinaryOpReturnTypeOffset = kBinaryOpTypeOffset + 1;
4495 static const int kCompareOperationOffset = kCompareStateOffset + 1;
4497 static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
4498 static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
4500 static const int kSafepointTableOffsetOffset = kStackSlotsOffset + kIntSize;
4501 static const int kStackCheckTableOffsetOffset = kStackSlotsOffset + kIntSize;
4503 // Flags layout. BitField<type, shift, size>.
4504 class ICStateField: public BitField<InlineCacheState, 0, 3> {};
4505 class TypeField: public BitField<PropertyType, 3, 4> {};
4506 class CacheHolderField: public BitField<InlineCacheHolderFlag, 7, 1> {};
4507 class KindField: public BitField<Kind, 8, 4> {};
4508 class ExtraICStateField: public BitField<ExtraICState, 12, 2> {};
4509 class IsPregeneratedField: public BitField<bool, 14, 1> {};
4511 // Signed field cannot be encoded using the BitField class.
4512 static const int kArgumentsCountShift = 15;
4513 static const int kArgumentsCountMask = ~((1 << kArgumentsCountShift) - 1);
4515 // This constant should be encodable in an ARM instruction.
4516 static const int kFlagsNotUsedInLookup =
4517 TypeField::kMask | CacheHolderField::kMask;
4520 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
4524 // All heap objects have a Map that describes their structure.
4525 // A Map contains information about:
4526 // - Size information about the object
4527 // - How to iterate over an object (for garbage collection)
4528 class Map: public HeapObject {
4531 // Size in bytes or kVariableSizeSentinel if instances do not have
4533 inline int instance_size();
4534 inline void set_instance_size(int value);
4536 // Count of properties allocated in the object.
4537 inline int inobject_properties();
4538 inline void set_inobject_properties(int value);
4540 // Count of property fields pre-allocated in the object when first allocated.
4541 inline int pre_allocated_property_fields();
4542 inline void set_pre_allocated_property_fields(int value);
4545 inline InstanceType instance_type();
4546 inline void set_instance_type(InstanceType value);
4548 // Tells how many unused property fields are available in the
4549 // instance (only used for JSObject in fast mode).
4550 inline int unused_property_fields();
4551 inline void set_unused_property_fields(int value);
4554 inline byte bit_field();
4555 inline void set_bit_field(byte value);
4558 inline byte bit_field2();
4559 inline void set_bit_field2(byte value);
4562 // TODO(1399): It should be possible to make room for bit_field3 in the map
4563 // without overloading the instance descriptors field (and storing it in the
4564 // DescriptorArray when the map has one).
4565 inline int bit_field3();
4566 inline void set_bit_field3(int value);
4568 // Tells whether the object in the prototype property will be used
4569 // for instances created from this function. If the prototype
4570 // property is set to a value that is not a JSObject, the prototype
4571 // property will not be used to create instances of the function.
4572 // See ECMA-262, 13.2.2.
4573 inline void set_non_instance_prototype(bool value);
4574 inline bool has_non_instance_prototype();
4576 // Tells whether function has special prototype property. If not, prototype
4577 // property will not be created when accessed (will return undefined),
4578 // and construction from this function will not be allowed.
4579 inline void set_function_with_prototype(bool value);
4580 inline bool function_with_prototype();
4582 // Tells whether the instance with this map should be ignored by the
4583 // __proto__ accessor.
4584 inline void set_is_hidden_prototype() {
4585 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
4588 inline bool is_hidden_prototype() {
4589 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
4592 // Records and queries whether the instance has a named interceptor.
4593 inline void set_has_named_interceptor() {
4594 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
4597 inline bool has_named_interceptor() {
4598 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
4601 // Records and queries whether the instance has an indexed interceptor.
4602 inline void set_has_indexed_interceptor() {
4603 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
4606 inline bool has_indexed_interceptor() {
4607 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
4610 // Tells whether the instance is undetectable.
4611 // An undetectable object is a special class of JSObject: 'typeof' operator
4612 // returns undefined, ToBoolean returns false. Otherwise it behaves like
4613 // a normal JS object. It is useful for implementing undetectable
4614 // document.all in Firefox & Safari.
4615 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
4616 inline void set_is_undetectable() {
4617 set_bit_field(bit_field() | (1 << kIsUndetectable));
4620 inline bool is_undetectable() {
4621 return ((1 << kIsUndetectable) & bit_field()) != 0;
4624 // Tells whether the instance has a call-as-function handler.
4625 inline void set_has_instance_call_handler() {
4626 set_bit_field3(bit_field3() | (1 << kHasInstanceCallHandler));
4629 inline bool has_instance_call_handler() {
4630 return ((1 << kHasInstanceCallHandler) & bit_field3()) != 0;
4633 inline void set_is_extensible(bool value);
4634 inline bool is_extensible();
4636 inline void set_elements_kind(ElementsKind elements_kind) {
4637 ASSERT(elements_kind < kElementsKindCount);
4638 ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
4639 set_bit_field2((bit_field2() & ~kElementsKindMask) |
4640 (elements_kind << kElementsKindShift));
4641 ASSERT(this->elements_kind() == elements_kind);
4644 inline ElementsKind elements_kind() {
4645 return static_cast<ElementsKind>(
4646 (bit_field2() & kElementsKindMask) >> kElementsKindShift);
4649 // Tells whether the instance has fast elements that are only Smis.
4650 inline bool has_fast_smi_only_elements() {
4651 return elements_kind() == FAST_SMI_ONLY_ELEMENTS;
4654 // Tells whether the instance has fast elements.
4655 inline bool has_fast_elements() {
4656 return elements_kind() == FAST_ELEMENTS;
4659 inline bool has_fast_double_elements() {
4660 return elements_kind() == FAST_DOUBLE_ELEMENTS;
4663 inline bool has_non_strict_arguments_elements() {
4664 return elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4667 inline bool has_external_array_elements() {
4668 ElementsKind kind(elements_kind());
4669 return kind >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
4670 kind <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND;
4673 inline bool has_dictionary_elements() {
4674 return elements_kind() == DICTIONARY_ELEMENTS;
4677 inline bool has_slow_elements_kind() {
4678 return elements_kind() == DICTIONARY_ELEMENTS
4679 || elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4682 static bool IsValidElementsTransition(ElementsKind from_kind,
4683 ElementsKind to_kind);
4685 // Tells whether the map is attached to SharedFunctionInfo
4686 // (for inobject slack tracking).
4687 inline void set_attached_to_shared_function_info(bool value);
4689 inline bool attached_to_shared_function_info();
4691 // Tells whether the map is shared between objects that may have different
4692 // behavior. If true, the map should never be modified, instead a clone
4693 // should be created and modified.
4694 inline void set_is_shared(bool value);
4696 inline bool is_shared();
4698 // Tells whether the instance needs security checks when accessing its
4700 inline void set_is_access_check_needed(bool access_check_needed);
4701 inline bool is_access_check_needed();
4703 // Whether the named interceptor is a fallback interceptor or not
4704 inline void set_named_interceptor_is_fallback(bool value);
4705 inline bool named_interceptor_is_fallback();
4707 // Tells whether the instance has the space for an external resource
4709 inline void set_has_external_resource(bool value);
4710 inline bool has_external_resource();
4712 // [prototype]: implicit prototype object.
4713 DECL_ACCESSORS(prototype, Object)
4715 // [constructor]: points back to the function responsible for this map.
4716 DECL_ACCESSORS(constructor, Object)
4718 inline JSFunction* unchecked_constructor();
4720 // Should only be called by the code that initializes map to set initial valid
4721 // value of the instance descriptor member.
4722 inline void init_instance_descriptors();
4724 // [instance descriptors]: describes the object.
4725 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
4727 // Sets the instance descriptor array for the map to be an empty descriptor
4729 inline void clear_instance_descriptors();
4731 // [stub cache]: contains stubs compiled for this map.
4732 DECL_ACCESSORS(code_cache, Object)
4734 // [back pointer]: points back to the parent map from which a transition
4735 // leads to this map. The field overlaps with prototype transitions and the
4736 // back pointer will be moved into the prototype transitions array if
4738 inline Object* GetBackPointer();
4739 inline void SetBackPointer(Object* value,
4740 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4742 // [prototype transitions]: cache of prototype transitions.
4743 // Prototype transition is a transition that happens
4744 // when we change object's prototype to a new one.
4746 // 0: finger - index of the first free cell in the cache
4747 // 1: back pointer that overlaps with prototype transitions field.
4748 // 2 + 2 * i: prototype
4749 // 3 + 2 * i: target map
4750 DECL_ACCESSORS(prototype_transitions, FixedArray)
4752 inline void init_prototype_transitions(Object* undefined);
4753 inline HeapObject* unchecked_prototype_transitions();
4755 static const int kProtoTransitionHeaderSize = 2;
4756 static const int kProtoTransitionNumberOfEntriesOffset = 0;
4757 static const int kProtoTransitionBackPointerOffset = 1;
4758 static const int kProtoTransitionElementsPerEntry = 2;
4759 static const int kProtoTransitionPrototypeOffset = 0;
4760 static const int kProtoTransitionMapOffset = 1;
4762 inline int NumberOfProtoTransitions() {
4763 FixedArray* cache = prototype_transitions();
4764 if (cache->length() == 0) return 0;
4766 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
4769 inline void SetNumberOfProtoTransitions(int value) {
4770 FixedArray* cache = prototype_transitions();
4771 ASSERT(cache->length() != 0);
4772 cache->set_unchecked(kProtoTransitionNumberOfEntriesOffset,
4773 Smi::FromInt(value));
4776 // Lookup in the map's instance descriptors and fill out the result
4777 // with the given holder if the name is found. The holder may be
4778 // NULL when this function is used from the compiler.
4779 void LookupInDescriptors(JSObject* holder,
4781 LookupResult* result);
4783 MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
4785 MUST_USE_RESULT MaybeObject* CopyNormalized(PropertyNormalizationMode mode,
4786 NormalizedMapSharingMode sharing);
4788 // Returns a copy of the map, with all transitions dropped from the
4789 // instance descriptors.
4790 MUST_USE_RESULT MaybeObject* CopyDropTransitions();
4792 // Returns the property index for name (only valid for FAST MODE).
4793 int PropertyIndexFor(String* name);
4795 // Returns the next free property index (only valid for FAST MODE).
4796 int NextFreePropertyIndex();
4798 // Returns the number of properties described in instance_descriptors
4799 // filtering out properties with the specified attributes.
4800 int NumberOfDescribedProperties(PropertyAttributes filter = NONE);
4803 static inline Map* cast(Object* obj);
4805 // Locate an accessor in the instance descriptor.
4806 AccessorDescriptor* FindAccessor(String* name);
4808 // Code cache operations.
4810 // Clears the code cache.
4811 inline void ClearCodeCache(Heap* heap);
4813 // Update code cache.
4814 static void UpdateCodeCache(Handle<Map> map,
4815 Handle<String> name,
4817 MUST_USE_RESULT MaybeObject* UpdateCodeCache(String* name, Code* code);
4819 // Returns the found code or undefined if absent.
4820 Object* FindInCodeCache(String* name, Code::Flags flags);
4822 // Returns the non-negative index of the code object if it is in the
4823 // cache and -1 otherwise.
4824 int IndexInCodeCache(Object* name, Code* code);
4826 // Removes a code object from the code cache at the given index.
4827 void RemoveFromCodeCache(String* name, Code* code, int index);
4829 // Set all map transitions from this map to dead maps to null. Also clear
4830 // back pointers in transition targets so that we do not process this map
4831 // again while following back pointers.
4832 void ClearNonLiveTransitions(Heap* heap);
4834 // Computes a hash value for this map, to be used in HashTables and such.
4837 // Compares this map to another to see if they describe equivalent objects.
4838 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
4839 // it had exactly zero inobject properties.
4840 // The "shared" flags of both this map and |other| are ignored.
4841 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
4843 // Returns the contents of this map's descriptor array for the given string.
4844 // May return NULL. |safe_to_add_transition| is set to false and NULL
4845 // is returned if adding transitions is not allowed.
4846 Object* GetDescriptorContents(String* sentinel_name,
4847 bool* safe_to_add_transitions);
4849 // Returns the map that this map transitions to if its elements_kind
4850 // is changed to |elements_kind|, or NULL if no such map is cached yet.
4851 // |safe_to_add_transitions| is set to false if adding transitions is not
4853 Map* LookupElementsTransitionMap(ElementsKind elements_kind,
4854 bool* safe_to_add_transition);
4856 // Adds an entry to this map's descriptor array for a transition to
4857 // |transitioned_map| when its elements_kind is changed to |elements_kind|.
4858 MUST_USE_RESULT MaybeObject* AddElementsTransition(
4859 ElementsKind elements_kind, Map* transitioned_map);
4861 // Returns the transitioned map for this map with the most generic
4862 // elements_kind that's found in |candidates|, or null handle if no match is
4864 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
4865 Map* FindTransitionedMap(MapList* candidates);
4867 // Zaps the contents of backing data structures in debug mode. Note that the
4868 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
4869 // holding weak references when incremental marking is used, because it also
4870 // iterates over objects that are otherwise unreachable.
4872 void ZapInstanceDescriptors();
4873 void ZapPrototypeTransitions();
4876 // Dispatched behavior.
4878 inline void MapPrint() {
4881 void MapPrint(FILE* out);
4885 void SharedMapVerify();
4888 inline int visitor_id();
4889 inline void set_visitor_id(int visitor_id);
4891 typedef void (*TraverseCallback)(Map* map, void* data);
4893 void TraverseTransitionTree(TraverseCallback callback, void* data);
4895 static const int kMaxCachedPrototypeTransitions = 256;
4897 Object* GetPrototypeTransition(Object* prototype);
4899 MUST_USE_RESULT MaybeObject* PutPrototypeTransition(Object* prototype,
4902 static const int kMaxPreAllocatedPropertyFields = 255;
4904 // Layout description.
4905 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
4906 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
4907 static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
4908 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
4909 // Storage for instance descriptors is overloaded to also contain additional
4910 // map flags when unused (bit_field3). When the map has instance descriptors,
4911 // the flags are transferred to the instance descriptor array and accessed
4912 // through an extra indirection.
4913 // TODO(1399): It should be possible to make room for bit_field3 in the map
4914 // without overloading the instance descriptors field, but the map is
4915 // currently perfectly aligned to 32 bytes and extending it at all would
4916 // double its size. After the increment GC work lands, this size restriction
4917 // could be loosened and bit_field3 moved directly back in the map.
4918 static const int kInstanceDescriptorsOrBitField3Offset =
4919 kConstructorOffset + kPointerSize;
4920 static const int kCodeCacheOffset =
4921 kInstanceDescriptorsOrBitField3Offset + kPointerSize;
4922 static const int kPrototypeTransitionsOrBackPointerOffset =
4923 kCodeCacheOffset + kPointerSize;
4924 static const int kPadStart =
4925 kPrototypeTransitionsOrBackPointerOffset + kPointerSize;
4926 static const int kSize = MAP_POINTER_ALIGN(kPadStart);
4928 // Layout of pointer fields. Heap iteration code relies on them
4929 // being continuously allocated.
4930 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
4931 static const int kPointerFieldsEndOffset =
4932 kPrototypeTransitionsOrBackPointerOffset + kPointerSize;
4934 // Byte offsets within kInstanceSizesOffset.
4935 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
4936 static const int kInObjectPropertiesByte = 1;
4937 static const int kInObjectPropertiesOffset =
4938 kInstanceSizesOffset + kInObjectPropertiesByte;
4939 static const int kPreAllocatedPropertyFieldsByte = 2;
4940 static const int kPreAllocatedPropertyFieldsOffset =
4941 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
4942 static const int kVisitorIdByte = 3;
4943 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
4945 // Byte offsets within kInstanceAttributesOffset attributes.
4946 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
4947 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
4948 static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
4949 static const int kBitField2Offset = kInstanceAttributesOffset + 3;
4951 STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
4953 // Bit positions for bit field.
4954 static const int kUnused = 0; // To be used for marking recently used maps.
4955 static const int kHasNonInstancePrototype = 1;
4956 static const int kIsHiddenPrototype = 2;
4957 static const int kHasNamedInterceptor = 3;
4958 static const int kHasIndexedInterceptor = 4;
4959 static const int kIsUndetectable = 5;
4960 static const int kHasExternalResource = 6;
4961 static const int kIsAccessCheckNeeded = 7;
4963 // Bit positions for bit field 2
4964 static const int kIsExtensible = 0;
4965 static const int kFunctionWithPrototype = 1;
4966 static const int kStringWrapperSafeForDefaultValueOf = 2;
4967 static const int kAttachedToSharedFunctionInfo = 3;
4968 // No bits can be used after kElementsKindFirstBit, they are all reserved for
4969 // storing ElementKind.
4970 static const int kElementsKindShift = 4;
4971 static const int kElementsKindBitCount = 4;
4973 // Derived values from bit field 2
4974 static const int kElementsKindMask = (-1 << kElementsKindShift) &
4975 ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
4976 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
4977 (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
4978 static const int8_t kMaximumBitField2FastSmiOnlyElementValue =
4979 static_cast<int8_t>((FAST_SMI_ONLY_ELEMENTS + 1) <<
4980 Map::kElementsKindShift) - 1;
4982 // Bit positions for bit field 3
4983 static const int kIsShared = 0;
4984 static const int kNamedInterceptorIsFallback = 1;
4985 static const int kHasInstanceCallHandler = 2;
4987 // Layout of the default cache. It holds alternating name and code objects.
4988 static const int kCodeCacheEntrySize = 2;
4989 static const int kCodeCacheEntryNameOffset = 0;
4990 static const int kCodeCacheEntryCodeOffset = 1;
4992 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
4993 kPointerFieldsEndOffset,
4994 kSize> BodyDescriptor;
4997 String* elements_transition_sentinel_name();
4998 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5002 // An abstract superclass, a marker class really, for simple structure classes.
5003 // It doesn't carry much functionality but allows struct classes to be
5004 // identified in the type system.
5005 class Struct: public HeapObject {
5007 inline void InitializeBody(int object_size);
5008 static inline Struct* cast(Object* that);
5012 // Script describes a script which has been added to the VM.
5013 class Script: public Struct {
5022 // Script compilation types.
5023 enum CompilationType {
5024 COMPILATION_TYPE_HOST = 0,
5025 COMPILATION_TYPE_EVAL = 1
5028 // Script compilation state.
5029 enum CompilationState {
5030 COMPILATION_STATE_INITIAL = 0,
5031 COMPILATION_STATE_COMPILED = 1
5034 // [source]: the script source.
5035 DECL_ACCESSORS(source, Object)
5037 // [name]: the script name.
5038 DECL_ACCESSORS(name, Object)
5040 // [id]: the script id.
5041 DECL_ACCESSORS(id, Object)
5043 // [line_offset]: script line offset in resource from where it was extracted.
5044 DECL_ACCESSORS(line_offset, Smi)
5046 // [column_offset]: script column offset in resource from where it was
5048 DECL_ACCESSORS(column_offset, Smi)
5050 // [data]: additional data associated with this script.
5051 DECL_ACCESSORS(data, Object)
5053 // [context_data]: context data for the context this script was compiled in.
5054 DECL_ACCESSORS(context_data, Object)
5056 // [wrapper]: the wrapper cache.
5057 DECL_ACCESSORS(wrapper, Foreign)
5059 // [type]: the script type.
5060 DECL_ACCESSORS(type, Smi)
5062 // [compilation]: how the the script was compiled.
5063 DECL_ACCESSORS(compilation_type, Smi)
5065 // [is_compiled]: determines whether the script has already been compiled.
5066 DECL_ACCESSORS(compilation_state, Smi)
5068 // [line_ends]: FixedArray of line ends positions.
5069 DECL_ACCESSORS(line_ends, Object)
5071 // [eval_from_shared]: for eval scripts the shared funcion info for the
5072 // function from which eval was called.
5073 DECL_ACCESSORS(eval_from_shared, Object)
5075 // [eval_from_instructions_offset]: the instruction offset in the code for the
5076 // function from which eval was called where eval was called.
5077 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5079 static inline Script* cast(Object* obj);
5081 // If script source is an external string, check that the underlying
5082 // resource is accessible. Otherwise, always return true.
5083 inline bool HasValidSource();
5086 inline void ScriptPrint() {
5087 ScriptPrint(stdout);
5089 void ScriptPrint(FILE* out);
5092 void ScriptVerify();
5095 static const int kSourceOffset = HeapObject::kHeaderSize;
5096 static const int kNameOffset = kSourceOffset + kPointerSize;
5097 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5098 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5099 static const int kDataOffset = kColumnOffsetOffset + kPointerSize;
5100 static const int kContextOffset = kDataOffset + kPointerSize;
5101 static const int kWrapperOffset = kContextOffset + kPointerSize;
5102 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5103 static const int kCompilationTypeOffset = kTypeOffset + kPointerSize;
5104 static const int kCompilationStateOffset =
5105 kCompilationTypeOffset + kPointerSize;
5106 static const int kLineEndsOffset = kCompilationStateOffset + kPointerSize;
5107 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5108 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5109 static const int kEvalFrominstructionsOffsetOffset =
5110 kEvalFromSharedOffset + kPointerSize;
5111 static const int kSize = kEvalFrominstructionsOffsetOffset + kPointerSize;
5114 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
5118 // List of builtin functions we want to identify to improve code
5121 // Each entry has a name of a global object property holding an object
5122 // optionally followed by ".prototype", a name of a builtin function
5123 // on the object (the one the id is set for), and a label.
5125 // Installation of ids for the selected builtin functions is handled
5126 // by the bootstrapper.
5128 // NOTE: Order is important: math functions should be at the end of
5129 // the list and MathFloor should be the first math function.
5130 #define FUNCTIONS_WITH_ID_LIST(V) \
5131 V(Array.prototype, push, ArrayPush) \
5132 V(Array.prototype, pop, ArrayPop) \
5133 V(Function.prototype, apply, FunctionApply) \
5134 V(String.prototype, charCodeAt, StringCharCodeAt) \
5135 V(String.prototype, charAt, StringCharAt) \
5136 V(String, fromCharCode, StringFromCharCode) \
5137 V(Math, floor, MathFloor) \
5138 V(Math, round, MathRound) \
5139 V(Math, ceil, MathCeil) \
5140 V(Math, abs, MathAbs) \
5141 V(Math, log, MathLog) \
5142 V(Math, sin, MathSin) \
5143 V(Math, cos, MathCos) \
5144 V(Math, tan, MathTan) \
5145 V(Math, asin, MathASin) \
5146 V(Math, acos, MathACos) \
5147 V(Math, atan, MathATan) \
5148 V(Math, exp, MathExp) \
5149 V(Math, sqrt, MathSqrt) \
5150 V(Math, pow, MathPow) \
5151 V(Math, random, MathRandom) \
5152 V(Math, max, MathMax) \
5153 V(Math, min, MathMin)
5156 enum BuiltinFunctionId {
5157 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
5159 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
5160 #undef DECLARE_FUNCTION_ID
5161 // Fake id for a special case of Math.pow. Note, it continues the
5162 // list of math functions.
5164 kFirstMathFunctionId = kMathFloor
5168 // SharedFunctionInfo describes the JSFunction information that can be
5169 // shared by multiple instances of the function.
5170 class SharedFunctionInfo: public HeapObject {
5172 // [name]: Function name.
5173 DECL_ACCESSORS(name, Object)
5175 // [code]: Function code.
5176 DECL_ACCESSORS(code, Code)
5178 // [scope_info]: Scope info.
5179 DECL_ACCESSORS(scope_info, ScopeInfo)
5181 // [construct stub]: Code stub for constructing instances of this function.
5182 DECL_ACCESSORS(construct_stub, Code)
5184 inline Code* unchecked_code();
5186 // Returns if this function has been compiled to native code yet.
5187 inline bool is_compiled();
5189 // [length]: The function length - usually the number of declared parameters.
5190 // Use up to 2^30 parameters.
5191 inline int length();
5192 inline void set_length(int value);
5194 // [formal parameter count]: The declared number of parameters.
5195 inline int formal_parameter_count();
5196 inline void set_formal_parameter_count(int value);
5198 // Set the formal parameter count so the function code will be
5199 // called without using argument adaptor frames.
5200 inline void DontAdaptArguments();
5202 // [expected_nof_properties]: Expected number of properties for the function.
5203 inline int expected_nof_properties();
5204 inline void set_expected_nof_properties(int value);
5206 // Inobject slack tracking is the way to reclaim unused inobject space.
5208 // The instance size is initially determined by adding some slack to
5209 // expected_nof_properties (to allow for a few extra properties added
5210 // after the constructor). There is no guarantee that the extra space
5211 // will not be wasted.
5213 // Here is the algorithm to reclaim the unused inobject space:
5214 // - Detect the first constructor call for this SharedFunctionInfo.
5215 // When it happens enter the "in progress" state: remember the
5216 // constructor's initial_map and install a special construct stub that
5217 // counts constructor calls.
5218 // - While the tracking is in progress create objects filled with
5219 // one_pointer_filler_map instead of undefined_value. This way they can be
5220 // resized quickly and safely.
5221 // - Once enough (kGenerousAllocationCount) objects have been created
5222 // compute the 'slack' (traverse the map transition tree starting from the
5223 // initial_map and find the lowest value of unused_property_fields).
5224 // - Traverse the transition tree again and decrease the instance size
5225 // of every map. Existing objects will resize automatically (they are
5226 // filled with one_pointer_filler_map). All further allocations will
5227 // use the adjusted instance size.
5228 // - Decrease expected_nof_properties so that an allocations made from
5229 // another context will use the adjusted instance size too.
5230 // - Exit "in progress" state by clearing the reference to the initial_map
5231 // and setting the regular construct stub (generic or inline).
5233 // The above is the main event sequence. Some special cases are possible
5234 // while the tracking is in progress:
5237 // Check if the initial_map is referenced by any live objects (except this
5238 // SharedFunctionInfo). If it is, continue tracking as usual.
5239 // If it is not, clear the reference and reset the tracking state. The
5240 // tracking will be initiated again on the next constructor call.
5242 // - The constructor is called from another context.
5243 // Immediately complete the tracking, perform all the necessary changes
5244 // to maps. This is necessary because there is no efficient way to track
5245 // multiple initial_maps.
5246 // Proceed to create an object in the current context (with the adjusted
5249 // - A different constructor function sharing the same SharedFunctionInfo is
5250 // called in the same context. This could be another closure in the same
5251 // context, or the first function could have been disposed.
5252 // This is handled the same way as the previous case.
5254 // Important: inobject slack tracking is not attempted during the snapshot
5257 static const int kGenerousAllocationCount = 8;
5259 // [construction_count]: Counter for constructor calls made during
5260 // the tracking phase.
5261 inline int construction_count();
5262 inline void set_construction_count(int value);
5264 // [initial_map]: initial map of the first function called as a constructor.
5265 // Saved for the duration of the tracking phase.
5266 // This is a weak link (GC resets it to undefined_value if no other live
5267 // object reference this map).
5268 DECL_ACCESSORS(initial_map, Object)
5270 // True if the initial_map is not undefined and the countdown stub is
5272 inline bool IsInobjectSlackTrackingInProgress();
5274 // Starts the tracking.
5275 // Stores the initial map and installs the countdown stub.
5276 // IsInobjectSlackTrackingInProgress is normally true after this call,
5277 // except when tracking have not been started (e.g. the map has no unused
5278 // properties or the snapshot is being built).
5279 void StartInobjectSlackTracking(Map* map);
5281 // Completes the tracking.
5282 // IsInobjectSlackTrackingInProgress is false after this call.
5283 void CompleteInobjectSlackTracking();
5285 // Clears the initial_map before the GC marking phase to ensure the reference
5286 // is weak. IsInobjectSlackTrackingInProgress is false after this call.
5287 void DetachInitialMap();
5289 // Restores the link to the initial map after the GC marking phase.
5290 // IsInobjectSlackTrackingInProgress is true after this call.
5291 void AttachInitialMap(Map* map);
5293 // False if there are definitely no live objects created from this function.
5294 // True if live objects _may_ exist (existence not guaranteed).
5295 // May go back from true to false after GC.
5296 DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
5298 // [instance class name]: class name for instances.
5299 DECL_ACCESSORS(instance_class_name, Object)
5301 // [function data]: This field holds some additional data for function.
5302 // Currently it either has FunctionTemplateInfo to make benefit the API
5303 // or Smi identifying a builtin function.
5304 // In the long run we don't want all functions to have this field but
5305 // we can fix that when we have a better model for storing hidden data
5307 DECL_ACCESSORS(function_data, Object)
5309 inline bool IsApiFunction();
5310 inline FunctionTemplateInfo* get_api_func_data();
5311 inline bool HasBuiltinFunctionId();
5312 inline BuiltinFunctionId builtin_function_id();
5314 // [script info]: Script from which the function originates.
5315 DECL_ACCESSORS(script, Object)
5317 // [num_literals]: Number of literals used by this function.
5318 inline int num_literals();
5319 inline void set_num_literals(int value);
5321 // [start_position_and_type]: Field used to store both the source code
5322 // position, whether or not the function is a function expression,
5323 // and whether or not the function is a toplevel function. The two
5324 // least significants bit indicates whether the function is an
5325 // expression and the rest contains the source code position.
5326 inline int start_position_and_type();
5327 inline void set_start_position_and_type(int value);
5329 // [debug info]: Debug information.
5330 DECL_ACCESSORS(debug_info, Object)
5332 // [inferred name]: Name inferred from variable or property
5333 // assignment of this function. Used to facilitate debugging and
5334 // profiling of JavaScript code written in OO style, where almost
5335 // all functions are anonymous but are assigned to object
5337 DECL_ACCESSORS(inferred_name, String)
5339 // The function's name if it is non-empty, otherwise the inferred name.
5340 String* DebugName();
5342 // Position of the 'function' token in the script source.
5343 inline int function_token_position();
5344 inline void set_function_token_position(int function_token_position);
5346 // Position of this function in the script source.
5347 inline int start_position();
5348 inline void set_start_position(int start_position);
5350 // End position of this function in the script source.
5351 inline int end_position();
5352 inline void set_end_position(int end_position);
5354 // Is this function a function expression in the source code.
5355 DECL_BOOLEAN_ACCESSORS(is_expression)
5357 // Is this function a top-level function (scripts, evals).
5358 DECL_BOOLEAN_ACCESSORS(is_toplevel)
5360 // Bit field containing various information collected by the compiler to
5361 // drive optimization.
5362 inline int compiler_hints();
5363 inline void set_compiler_hints(int value);
5365 inline int ast_node_count();
5366 inline void set_ast_node_count(int count);
5368 // A counter used to determine when to stress the deoptimizer with a
5370 inline int deopt_counter();
5371 inline void set_deopt_counter(int counter);
5373 inline int profiler_ticks();
5375 // Inline cache age is used to infer whether the function survived a context
5376 // disposal or not. In the former case we reset the opt_count.
5377 inline int ic_age();
5378 inline void set_ic_age(int age);
5380 // Add information on assignments of the form this.x = ...;
5381 void SetThisPropertyAssignmentsInfo(
5382 bool has_only_simple_this_property_assignments,
5383 FixedArray* this_property_assignments);
5385 // Clear information on assignments of the form this.x = ...;
5386 void ClearThisPropertyAssignmentsInfo();
5388 // Indicate that this function only consists of assignments of the form
5389 // this.x = y; where y is either a constant or refers to an argument.
5390 inline bool has_only_simple_this_property_assignments();
5392 // Indicates if this function can be lazy compiled.
5393 // This is used to determine if we can safely flush code from a function
5394 // when doing GC if we expect that the function will no longer be used.
5395 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
5397 // Indicates how many full GCs this function has survived with assigned
5398 // code object. Used to determine when it is relatively safe to flush
5399 // this code object and replace it with lazy compilation stub.
5400 // Age is reset when GC notices that the code object is referenced
5401 // from the stack or compilation cache.
5402 inline int code_age();
5403 inline void set_code_age(int age);
5405 // Indicates whether optimizations have been disabled for this
5406 // shared function info. If a function is repeatedly optimized or if
5407 // we cannot optimize the function we disable optimization to avoid
5408 // spending time attempting to optimize it again.
5409 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
5411 // Indicates the language mode of the function's code as defined by the
5412 // current harmony drafts for the next ES language standard. Possible
5414 // 1. CLASSIC_MODE - Unrestricted syntax and semantics, same as in ES5.
5415 // 2. STRICT_MODE - Restricted syntax and semantics, same as in ES5.
5416 // 3. EXTENDED_MODE - Only available under the harmony flag, not part of ES5.
5417 inline LanguageMode language_mode();
5418 inline void set_language_mode(LanguageMode language_mode);
5420 // Indicates whether the language mode of this function is CLASSIC_MODE.
5421 inline bool is_classic_mode();
5423 // Indicates whether the language mode of this function is EXTENDED_MODE.
5424 inline bool is_extended_mode();
5426 // False if the function definitely does not allocate an arguments object.
5427 DECL_BOOLEAN_ACCESSORS(uses_arguments)
5429 // True if the function has any duplicated parameter names.
5430 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
5432 // Indicates whether the function is a native function.
5433 // These needs special treatment in .call and .apply since
5434 // null passed as the receiver should not be translated to the
5436 DECL_BOOLEAN_ACCESSORS(native)
5438 // Indicates that the function was created by the Function function.
5439 // Though it's anonymous, toString should treat it as if it had the name
5440 // "anonymous". We don't set the name itself so that the system does not
5441 // see a binding for it.
5442 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
5444 // Indicates whether the function is a bound function created using
5445 // the bind function.
5446 DECL_BOOLEAN_ACCESSORS(bound)
5448 // Indicates that the function is anonymous (the name field can be set
5449 // through the API, which does not change this flag).
5450 DECL_BOOLEAN_ACCESSORS(is_anonymous)
5452 // Is this a function or top-level/eval code.
5453 DECL_BOOLEAN_ACCESSORS(is_function)
5455 // Indicates that the function cannot be optimized.
5456 DECL_BOOLEAN_ACCESSORS(dont_optimize)
5458 // Indicates that the function cannot be inlined.
5459 DECL_BOOLEAN_ACCESSORS(dont_inline)
5461 // Indicates whether or not the code in the shared function support
5463 inline bool has_deoptimization_support();
5465 // Enable deoptimization support through recompiled code.
5466 void EnableDeoptimizationSupport(Code* recompiled);
5468 // Disable (further) attempted optimization of all functions sharing this
5469 // shared function info.
5470 void DisableOptimization();
5472 // Lookup the bailout ID and ASSERT that it exists in the non-optimized
5473 // code, returns whether it asserted (i.e., always true if assertions are
5475 bool VerifyBailoutId(int id);
5477 // Check whether a inlined constructor can be generated with the given
5479 bool CanGenerateInlineConstructor(Object* prototype);
5481 // Prevents further attempts to generate inline constructors.
5482 // To be called if generation failed for any reason.
5483 void ForbidInlineConstructor();
5485 // For functions which only contains this property assignments this provides
5486 // access to the names for the properties assigned.
5487 DECL_ACCESSORS(this_property_assignments, Object)
5488 inline int this_property_assignments_count();
5489 inline void set_this_property_assignments_count(int value);
5490 String* GetThisPropertyAssignmentName(int index);
5491 bool IsThisPropertyAssignmentArgument(int index);
5492 int GetThisPropertyAssignmentArgument(int index);
5493 Object* GetThisPropertyAssignmentConstant(int index);
5495 // [source code]: Source code for the function.
5496 bool HasSourceCode();
5497 Handle<Object> GetSourceCode();
5499 inline int opt_count();
5500 inline void set_opt_count(int opt_count);
5502 // Source size of this function.
5505 // Calculate the instance size.
5506 int CalculateInstanceSize();
5508 // Calculate the number of in-object properties.
5509 int CalculateInObjectProperties();
5511 // Dispatched behavior.
5512 // Set max_length to -1 for unlimited length.
5513 void SourceCodePrint(StringStream* accumulator, int max_length);
5515 inline void SharedFunctionInfoPrint() {
5516 SharedFunctionInfoPrint(stdout);
5518 void SharedFunctionInfoPrint(FILE* out);
5521 void SharedFunctionInfoVerify();
5524 void ResetForNewContext(int new_ic_age);
5526 // Helpers to compile the shared code. Returns true on success, false on
5527 // failure (e.g., stack overflow during compilation).
5528 static bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
5529 ClearExceptionFlag flag);
5530 static bool CompileLazy(Handle<SharedFunctionInfo> shared,
5531 ClearExceptionFlag flag);
5533 void SharedFunctionInfoIterateBody(ObjectVisitor* v);
5536 static inline SharedFunctionInfo* cast(Object* obj);
5539 static const int kDontAdaptArgumentsSentinel = -1;
5541 // Layout description.
5543 static const int kNameOffset = HeapObject::kHeaderSize;
5544 static const int kCodeOffset = kNameOffset + kPointerSize;
5545 static const int kScopeInfoOffset = kCodeOffset + kPointerSize;
5546 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
5547 static const int kInstanceClassNameOffset =
5548 kConstructStubOffset + kPointerSize;
5549 static const int kFunctionDataOffset =
5550 kInstanceClassNameOffset + kPointerSize;
5551 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
5552 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
5553 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
5554 static const int kInitialMapOffset =
5555 kInferredNameOffset + kPointerSize;
5556 static const int kThisPropertyAssignmentsOffset =
5557 kInitialMapOffset + kPointerSize;
5558 // ic_age is a Smi field. It could be grouped with another Smi field into a
5559 // PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
5560 static const int kICAgeOffset = kThisPropertyAssignmentsOffset + kPointerSize;
5561 #if V8_HOST_ARCH_32_BIT
5563 static const int kLengthOffset =
5564 kICAgeOffset + kPointerSize;
5565 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
5566 static const int kExpectedNofPropertiesOffset =
5567 kFormalParameterCountOffset + kPointerSize;
5568 static const int kNumLiteralsOffset =
5569 kExpectedNofPropertiesOffset + kPointerSize;
5570 static const int kStartPositionAndTypeOffset =
5571 kNumLiteralsOffset + kPointerSize;
5572 static const int kEndPositionOffset =
5573 kStartPositionAndTypeOffset + kPointerSize;
5574 static const int kFunctionTokenPositionOffset =
5575 kEndPositionOffset + kPointerSize;
5576 static const int kCompilerHintsOffset =
5577 kFunctionTokenPositionOffset + kPointerSize;
5578 static const int kThisPropertyAssignmentsCountOffset =
5579 kCompilerHintsOffset + kPointerSize;
5580 static const int kOptCountOffset =
5581 kThisPropertyAssignmentsCountOffset + kPointerSize;
5582 static const int kAstNodeCountOffset = kOptCountOffset + kPointerSize;
5583 static const int kDeoptCounterOffset = kAstNodeCountOffset + kPointerSize;
5587 static const int kSize = kDeoptCounterOffset + kPointerSize;
5589 // The only reason to use smi fields instead of int fields
5590 // is to allow iteration without maps decoding during
5591 // garbage collections.
5592 // To avoid wasting space on 64-bit architectures we use
5593 // the following trick: we group integer fields into pairs
5594 // First integer in each pair is shifted left by 1.
5595 // By doing this we guarantee that LSB of each kPointerSize aligned
5596 // word is not set and thus this word cannot be treated as pointer
5597 // to HeapObject during old space traversal.
5598 static const int kLengthOffset =
5599 kICAgeOffset + kPointerSize;
5600 static const int kFormalParameterCountOffset =
5601 kLengthOffset + kIntSize;
5603 static const int kExpectedNofPropertiesOffset =
5604 kFormalParameterCountOffset + kIntSize;
5605 static const int kNumLiteralsOffset =
5606 kExpectedNofPropertiesOffset + kIntSize;
5608 static const int kEndPositionOffset =
5609 kNumLiteralsOffset + kIntSize;
5610 static const int kStartPositionAndTypeOffset =
5611 kEndPositionOffset + kIntSize;
5613 static const int kFunctionTokenPositionOffset =
5614 kStartPositionAndTypeOffset + kIntSize;
5615 static const int kCompilerHintsOffset =
5616 kFunctionTokenPositionOffset + kIntSize;
5618 static const int kThisPropertyAssignmentsCountOffset =
5619 kCompilerHintsOffset + kIntSize;
5620 static const int kOptCountOffset =
5621 kThisPropertyAssignmentsCountOffset + kIntSize;
5623 static const int kAstNodeCountOffset = kOptCountOffset + kIntSize;
5624 static const int kDeoptCounterOffset = kAstNodeCountOffset + kIntSize;
5627 static const int kSize = kDeoptCounterOffset + kIntSize;
5631 // The construction counter for inobject slack tracking is stored in the
5632 // most significant byte of compiler_hints which is otherwise unused.
5633 // Its offset depends on the endian-ness of the architecture.
5634 #if __BYTE_ORDER == __LITTLE_ENDIAN
5635 static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
5636 #elif __BYTE_ORDER == __BIG_ENDIAN
5637 static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
5639 #error Unknown byte ordering
5642 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
5644 typedef FixedBodyDescriptor<kNameOffset,
5645 kThisPropertyAssignmentsOffset + kPointerSize,
5646 kSize> BodyDescriptor;
5648 // Bit positions in start_position_and_type.
5649 // The source code start position is in the 30 most significant bits of
5650 // the start_position_and_type field.
5651 static const int kIsExpressionBit = 0;
5652 static const int kIsTopLevelBit = 1;
5653 static const int kStartPositionShift = 2;
5654 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
5656 // Bit positions in compiler_hints.
5657 static const int kCodeAgeSize = 3;
5658 static const int kCodeAgeMask = (1 << kCodeAgeSize) - 1;
5660 enum CompilerHints {
5661 kHasOnlySimpleThisPropertyAssignments,
5662 kAllowLazyCompilation,
5663 kLiveObjectsMayExist,
5665 kOptimizationDisabled = kCodeAgeShift + kCodeAgeSize,
5666 kStrictModeFunction,
5667 kExtendedModeFunction,
5669 kHasDuplicateParameters,
5673 kNameShouldPrintAsAnonymous,
5677 kCompilerHintsCount // Pseudo entry
5681 #if V8_HOST_ARCH_32_BIT
5682 // On 32 bit platforms, compiler hints is a smi.
5683 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
5684 static const int kCompilerHintsSize = kPointerSize;
5686 // On 64 bit platforms, compiler hints is not a smi, see comment above.
5687 static const int kCompilerHintsSmiTagSize = 0;
5688 static const int kCompilerHintsSize = kIntSize;
5691 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
5692 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
5695 // Constants for optimizing codegen for strict mode function and
5697 // Allows to use byte-width instructions.
5698 static const int kStrictModeBitWithinByte =
5699 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5701 static const int kExtendedModeBitWithinByte =
5702 (kExtendedModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5704 static const int kNativeBitWithinByte =
5705 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
5707 #if __BYTE_ORDER == __LITTLE_ENDIAN
5708 static const int kStrictModeByteOffset = kCompilerHintsOffset +
5709 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5710 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5711 (kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5712 static const int kNativeByteOffset = kCompilerHintsOffset +
5713 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
5714 #elif __BYTE_ORDER == __BIG_ENDIAN
5715 static const int kStrictModeByteOffset = kCompilerHintsOffset +
5716 (kCompilerHintsSize - 1) -
5717 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5718 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5719 (kCompilerHintsSize - 1) -
5720 ((kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5721 static const int kNativeByteOffset = kCompilerHintsOffset +
5722 (kCompilerHintsSize - 1) -
5723 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
5725 #error Unknown byte ordering
5729 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
5733 // Representation for module instance objects.
5734 class JSModule: public JSObject {
5736 // [context]: the context holding the module's locals, or undefined if none.
5737 DECL_ACCESSORS(context, Object)
5740 static inline JSModule* cast(Object* obj);
5742 // Dispatched behavior.
5744 inline void JSModulePrint() {
5745 JSModulePrint(stdout);
5747 void JSModulePrint(FILE* out);
5750 void JSModuleVerify();
5753 // Layout description.
5754 static const int kContextOffset = JSObject::kHeaderSize;
5755 static const int kSize = kContextOffset + kPointerSize;
5758 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
5762 // JSFunction describes JavaScript functions.
5763 class JSFunction: public JSObject {
5765 // [prototype_or_initial_map]:
5766 DECL_ACCESSORS(prototype_or_initial_map, Object)
5768 // [shared]: The information about the function that
5769 // can be shared by instances.
5770 DECL_ACCESSORS(shared, SharedFunctionInfo)
5772 inline SharedFunctionInfo* unchecked_shared();
5774 // [context]: The context for this function.
5775 inline Context* context();
5776 inline Object* unchecked_context();
5777 inline void set_context(Object* context);
5779 // [code]: The generated code object for this function. Executed
5780 // when the function is invoked, e.g. foo() or new foo(). See
5781 // [[Call]] and [[Construct]] description in ECMA-262, section
5783 inline Code* code();
5784 inline void set_code(Code* code);
5785 inline void ReplaceCode(Code* code);
5787 inline Code* unchecked_code();
5789 // Tells whether this function is builtin.
5790 inline bool IsBuiltin();
5792 // Tells whether or not the function needs arguments adaption.
5793 inline bool NeedsArgumentsAdaption();
5795 // Tells whether or not this function has been optimized.
5796 inline bool IsOptimized();
5798 // Tells whether or not this function can be optimized.
5799 inline bool IsOptimizable();
5801 // Mark this function for lazy recompilation. The function will be
5802 // recompiled the next time it is executed.
5803 void MarkForLazyRecompilation();
5805 // Helpers to compile this function. Returns true on success, false on
5806 // failure (e.g., stack overflow during compilation).
5807 static bool CompileLazy(Handle<JSFunction> function,
5808 ClearExceptionFlag flag);
5809 static bool CompileOptimized(Handle<JSFunction> function,
5811 ClearExceptionFlag flag);
5813 // Tells whether or not the function is already marked for lazy
5815 inline bool IsMarkedForLazyRecompilation();
5817 // Check whether or not this function is inlineable.
5818 bool IsInlineable();
5820 // [literals_or_bindings]: Fixed array holding either
5821 // the materialized literals or the bindings of a bound function.
5823 // If the function contains object, regexp or array literals, the
5824 // literals array prefix contains the object, regexp, and array
5825 // function to be used when creating these literals. This is
5826 // necessary so that we do not dynamically lookup the object, regexp
5827 // or array functions. Performing a dynamic lookup, we might end up
5828 // using the functions from a new context that we should not have
5831 // On bound functions, the array is a (copy-on-write) fixed-array containing
5832 // the function that was bound, bound this-value and any bound
5833 // arguments. Bound functions never contain literals.
5834 DECL_ACCESSORS(literals_or_bindings, FixedArray)
5836 inline FixedArray* literals();
5837 inline void set_literals(FixedArray* literals);
5839 inline FixedArray* function_bindings();
5840 inline void set_function_bindings(FixedArray* bindings);
5842 // The initial map for an object created by this constructor.
5843 inline Map* initial_map();
5844 inline void set_initial_map(Map* value);
5845 MUST_USE_RESULT inline MaybeObject* set_initial_map_and_cache_transitions(
5847 inline bool has_initial_map();
5849 // Get and set the prototype property on a JSFunction. If the
5850 // function has an initial map the prototype is set on the initial
5851 // map. Otherwise, the prototype is put in the initial map field
5852 // until an initial map is needed.
5853 inline bool has_prototype();
5854 inline bool has_instance_prototype();
5855 inline Object* prototype();
5856 inline Object* instance_prototype();
5857 MUST_USE_RESULT MaybeObject* SetInstancePrototype(Object* value);
5858 MUST_USE_RESULT MaybeObject* SetPrototype(Object* value);
5860 // After prototype is removed, it will not be created when accessed, and
5861 // [[Construct]] from this function will not be allowed.
5862 Object* RemovePrototype();
5863 inline bool should_have_prototype();
5865 // Accessor for this function's initial map's [[class]]
5866 // property. This is primarily used by ECMA native functions. This
5867 // method sets the class_name field of this function's initial map
5868 // to a given value. It creates an initial map if this function does
5869 // not have one. Note that this method does not copy the initial map
5870 // if it has one already, but simply replaces it with the new value.
5871 // Instances created afterwards will have a map whose [[class]] is
5872 // set to 'value', but there is no guarantees on instances created
5874 Object* SetInstanceClassName(String* name);
5876 // Returns if this function has been compiled to native code yet.
5877 inline bool is_compiled();
5879 // [next_function_link]: Field for linking functions. This list is treated as
5880 // a weak list by the GC.
5881 DECL_ACCESSORS(next_function_link, Object)
5883 // Prints the name of the function using PrintF.
5884 inline void PrintName() {
5887 void PrintName(FILE* out);
5890 static inline JSFunction* cast(Object* obj);
5892 // Iterates the objects, including code objects indirectly referenced
5893 // through pointers to the first instruction in the code object.
5894 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
5896 // Dispatched behavior.
5898 inline void JSFunctionPrint() {
5899 JSFunctionPrint(stdout);
5901 void JSFunctionPrint(FILE* out);
5904 void JSFunctionVerify();
5907 // Returns the number of allocated literals.
5908 inline int NumberOfLiterals();
5910 // Retrieve the global context from a function's literal array.
5911 static Context* GlobalContextFromLiterals(FixedArray* literals);
5913 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
5914 // kSize) is weak and has special handling during garbage collection.
5915 static const int kCodeEntryOffset = JSObject::kHeaderSize;
5916 static const int kPrototypeOrInitialMapOffset =
5917 kCodeEntryOffset + kPointerSize;
5918 static const int kSharedFunctionInfoOffset =
5919 kPrototypeOrInitialMapOffset + kPointerSize;
5920 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
5921 static const int kLiteralsOffset = kContextOffset + kPointerSize;
5922 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
5923 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
5924 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
5926 // Layout of the literals array.
5927 static const int kLiteralsPrefixSize = 1;
5928 static const int kLiteralGlobalContextIndex = 0;
5930 // Layout of the bound-function binding array.
5931 static const int kBoundFunctionIndex = 0;
5932 static const int kBoundThisIndex = 1;
5933 static const int kBoundArgumentsStartIndex = 2;
5936 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
5940 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
5941 // and the prototype is hidden. JSGlobalProxy always delegates
5942 // property accesses to its prototype if the prototype is not null.
5944 // A JSGlobalProxy can be reinitialized which will preserve its identity.
5946 // Accessing a JSGlobalProxy requires security check.
5948 class JSGlobalProxy : public JSObject {
5950 // [context]: the owner global context of this global proxy object.
5951 // It is null value if this object is not used by any context.
5952 DECL_ACCESSORS(context, Object)
5955 static inline JSGlobalProxy* cast(Object* obj);
5957 // Dispatched behavior.
5959 inline void JSGlobalProxyPrint() {
5960 JSGlobalProxyPrint(stdout);
5962 void JSGlobalProxyPrint(FILE* out);
5965 void JSGlobalProxyVerify();
5968 // Layout description.
5969 static const int kContextOffset = JSObject::kHeaderSize;
5970 static const int kSize = kContextOffset + kPointerSize;
5973 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
5977 // Forward declaration.
5978 class JSBuiltinsObject;
5980 // Common super class for JavaScript global objects and the special
5981 // builtins global objects.
5982 class GlobalObject: public JSObject {
5984 // [builtins]: the object holding the runtime routines written in JS.
5985 DECL_ACCESSORS(builtins, JSBuiltinsObject)
5987 // [global context]: the global context corresponding to this global object.
5988 DECL_ACCESSORS(global_context, Context)
5990 // [global receiver]: the global receiver object of the context
5991 DECL_ACCESSORS(global_receiver, JSObject)
5993 // Retrieve the property cell used to store a property.
5994 JSGlobalPropertyCell* GetPropertyCell(LookupResult* result);
5996 // This is like GetProperty, but is used when you know the lookup won't fail
5997 // by throwing an exception. This is for the debug and builtins global
5998 // objects, where it is known which properties can be expected to be present
6000 Object* GetPropertyNoExceptionThrown(String* key) {
6001 Object* answer = GetProperty(key)->ToObjectUnchecked();
6005 // Ensure that the global object has a cell for the given property name.
6006 static Handle<JSGlobalPropertyCell> EnsurePropertyCell(
6007 Handle<GlobalObject> global,
6008 Handle<String> name);
6009 // TODO(kmillikin): This function can be eliminated once the stub cache is
6010 // full handlified (and the static helper can be written directly).
6011 MUST_USE_RESULT MaybeObject* EnsurePropertyCell(String* name);
6014 static inline GlobalObject* cast(Object* obj);
6016 // Layout description.
6017 static const int kBuiltinsOffset = JSObject::kHeaderSize;
6018 static const int kGlobalContextOffset = kBuiltinsOffset + kPointerSize;
6019 static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
6020 static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
6023 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
6027 // JavaScript global object.
6028 class JSGlobalObject: public GlobalObject {
6031 static inline JSGlobalObject* cast(Object* obj);
6033 // Dispatched behavior.
6035 inline void JSGlobalObjectPrint() {
6036 JSGlobalObjectPrint(stdout);
6038 void JSGlobalObjectPrint(FILE* out);
6041 void JSGlobalObjectVerify();
6044 // Layout description.
6045 static const int kSize = GlobalObject::kHeaderSize;
6048 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
6052 // Builtins global object which holds the runtime routines written in
6054 class JSBuiltinsObject: public GlobalObject {
6056 // Accessors for the runtime routines written in JavaScript.
6057 inline Object* javascript_builtin(Builtins::JavaScript id);
6058 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
6060 // Accessors for code of the runtime routines written in JavaScript.
6061 inline Code* javascript_builtin_code(Builtins::JavaScript id);
6062 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
6065 static inline JSBuiltinsObject* cast(Object* obj);
6067 // Dispatched behavior.
6069 inline void JSBuiltinsObjectPrint() {
6070 JSBuiltinsObjectPrint(stdout);
6072 void JSBuiltinsObjectPrint(FILE* out);
6075 void JSBuiltinsObjectVerify();
6078 // Layout description. The size of the builtins object includes
6079 // room for two pointers per runtime routine written in javascript
6080 // (function and code object).
6081 static const int kJSBuiltinsCount = Builtins::id_count;
6082 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
6083 static const int kJSBuiltinsCodeOffset =
6084 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
6085 static const int kSize =
6086 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
6088 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
6089 return kJSBuiltinsOffset + id * kPointerSize;
6092 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
6093 return kJSBuiltinsCodeOffset + id * kPointerSize;
6097 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
6101 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
6102 class JSValue: public JSObject {
6104 // [value]: the object being wrapped.
6105 DECL_ACCESSORS(value, Object)
6108 static inline JSValue* cast(Object* obj);
6110 // Dispatched behavior.
6112 inline void JSValuePrint() {
6113 JSValuePrint(stdout);
6115 void JSValuePrint(FILE* out);
6118 void JSValueVerify();
6121 // Layout description.
6122 static const int kValueOffset = JSObject::kHeaderSize;
6123 static const int kSize = kValueOffset + kPointerSize;
6126 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
6132 // Representation for JS date objects.
6133 class JSDate: public JSObject {
6135 // If one component is NaN, all of them are, indicating a NaN time value.
6136 // [value]: the time value.
6137 DECL_ACCESSORS(value, Object)
6138 // [year]: caches year. Either undefined, smi, or NaN.
6139 DECL_ACCESSORS(year, Object)
6140 // [month]: caches month. Either undefined, smi, or NaN.
6141 DECL_ACCESSORS(month, Object)
6142 // [day]: caches day. Either undefined, smi, or NaN.
6143 DECL_ACCESSORS(day, Object)
6144 // [weekday]: caches day of week. Either undefined, smi, or NaN.
6145 DECL_ACCESSORS(weekday, Object)
6146 // [hour]: caches hours. Either undefined, smi, or NaN.
6147 DECL_ACCESSORS(hour, Object)
6148 // [min]: caches minutes. Either undefined, smi, or NaN.
6149 DECL_ACCESSORS(min, Object)
6150 // [sec]: caches seconds. Either undefined, smi, or NaN.
6151 DECL_ACCESSORS(sec, Object)
6152 // [cache stamp]: sample of the date cache stamp at the
6153 // moment when local fields were cached.
6154 DECL_ACCESSORS(cache_stamp, Object)
6157 static inline JSDate* cast(Object* obj);
6159 // Returns the date field with the specified index.
6160 // See FieldIndex for the list of date fields.
6161 static Object* GetField(Object* date, Smi* index);
6163 void SetValue(Object* value, bool is_value_nan);
6166 // Dispatched behavior.
6168 inline void JSDatePrint() {
6169 JSDatePrint(stdout);
6171 void JSDatePrint(FILE* out);
6174 void JSDateVerify();
6176 // The order is important. It must be kept in sync with date macros
6187 kFirstUncachedField,
6188 kMillisecond = kFirstUncachedField,
6192 kYearUTC = kFirstUTCField,
6205 // Layout description.
6206 static const int kValueOffset = JSObject::kHeaderSize;
6207 static const int kYearOffset = kValueOffset + kPointerSize;
6208 static const int kMonthOffset = kYearOffset + kPointerSize;
6209 static const int kDayOffset = kMonthOffset + kPointerSize;
6210 static const int kWeekdayOffset = kDayOffset + kPointerSize;
6211 static const int kHourOffset = kWeekdayOffset + kPointerSize;
6212 static const int kMinOffset = kHourOffset + kPointerSize;
6213 static const int kSecOffset = kMinOffset + kPointerSize;
6214 static const int kCacheStampOffset = kSecOffset + kPointerSize;
6215 static const int kSize = kCacheStampOffset + kPointerSize;
6218 inline Object* DoGetField(FieldIndex index);
6220 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
6222 // Computes and caches the cacheable fields of the date.
6223 inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
6226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
6230 // Representation of message objects used for error reporting through
6231 // the API. The messages are formatted in JavaScript so this object is
6232 // a real JavaScript object. The information used for formatting the
6233 // error messages are not directly accessible from JavaScript to
6234 // prevent leaking information to user code called during error
6236 class JSMessageObject: public JSObject {
6238 // [type]: the type of error message.
6239 DECL_ACCESSORS(type, String)
6241 // [arguments]: the arguments for formatting the error message.
6242 DECL_ACCESSORS(arguments, JSArray)
6244 // [script]: the script from which the error message originated.
6245 DECL_ACCESSORS(script, Object)
6247 // [stack_trace]: the stack trace for this error message.
6248 DECL_ACCESSORS(stack_trace, Object)
6250 // [stack_frames]: an array of stack frames for this error object.
6251 DECL_ACCESSORS(stack_frames, Object)
6253 // [start_position]: the start position in the script for the error message.
6254 inline int start_position();
6255 inline void set_start_position(int value);
6257 // [end_position]: the end position in the script for the error message.
6258 inline int end_position();
6259 inline void set_end_position(int value);
6262 static inline JSMessageObject* cast(Object* obj);
6264 // Dispatched behavior.
6266 inline void JSMessageObjectPrint() {
6267 JSMessageObjectPrint(stdout);
6269 void JSMessageObjectPrint(FILE* out);
6272 void JSMessageObjectVerify();
6275 // Layout description.
6276 static const int kTypeOffset = JSObject::kHeaderSize;
6277 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
6278 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
6279 static const int kStackTraceOffset = kScriptOffset + kPointerSize;
6280 static const int kStackFramesOffset = kStackTraceOffset + kPointerSize;
6281 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
6282 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
6283 static const int kSize = kEndPositionOffset + kPointerSize;
6285 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
6286 kStackFramesOffset + kPointerSize,
6287 kSize> BodyDescriptor;
6291 // Regular expressions
6292 // The regular expression holds a single reference to a FixedArray in
6293 // the kDataOffset field.
6294 // The FixedArray contains the following data:
6295 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
6296 // - reference to the original source string
6297 // - reference to the original flag string
6298 // If it is an atom regexp
6299 // - a reference to a literal string to search for
6300 // If it is an irregexp regexp:
6301 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
6302 // used for tracking the last usage (used for code flushing).
6303 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
6304 // used for tracking the last usage (used for code flushing)..
6305 // - max number of registers used by irregexp implementations.
6306 // - number of capture registers (output values) of the regexp.
6307 class JSRegExp: public JSObject {
6310 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
6311 // ATOM: A simple string to match against using an indexOf operation.
6312 // IRREGEXP: Compiled with Irregexp.
6313 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
6314 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
6315 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
6319 explicit Flags(uint32_t value) : value_(value) { }
6320 bool is_global() { return (value_ & GLOBAL) != 0; }
6321 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
6322 bool is_multiline() { return (value_ & MULTILINE) != 0; }
6323 uint32_t value() { return value_; }
6328 DECL_ACCESSORS(data, Object)
6330 inline Type TypeTag();
6331 inline int CaptureCount();
6332 inline Flags GetFlags();
6333 inline String* Pattern();
6334 inline Object* DataAt(int index);
6335 // Set implementation data after the object has been prepared.
6336 inline void SetDataAt(int index, Object* value);
6338 // Used during GC when flushing code or setting age.
6339 inline Object* DataAtUnchecked(int index);
6340 inline void SetDataAtUnchecked(int index, Object* value, Heap* heap);
6341 inline Type TypeTagUnchecked();
6343 static int code_index(bool is_ascii) {
6345 return kIrregexpASCIICodeIndex;
6347 return kIrregexpUC16CodeIndex;
6351 static int saved_code_index(bool is_ascii) {
6353 return kIrregexpASCIICodeSavedIndex;
6355 return kIrregexpUC16CodeSavedIndex;
6359 static inline JSRegExp* cast(Object* obj);
6361 // Dispatched behavior.
6363 void JSRegExpVerify();
6366 static const int kDataOffset = JSObject::kHeaderSize;
6367 static const int kSize = kDataOffset + kPointerSize;
6369 // Indices in the data array.
6370 static const int kTagIndex = 0;
6371 static const int kSourceIndex = kTagIndex + 1;
6372 static const int kFlagsIndex = kSourceIndex + 1;
6373 static const int kDataIndex = kFlagsIndex + 1;
6374 // The data fields are used in different ways depending on the
6375 // value of the tag.
6376 // Atom regexps (literal strings).
6377 static const int kAtomPatternIndex = kDataIndex;
6379 static const int kAtomDataSize = kAtomPatternIndex + 1;
6381 // Irregexp compiled code or bytecode for ASCII. If compilation
6382 // fails, this fields hold an exception object that should be
6383 // thrown if the regexp is used again.
6384 static const int kIrregexpASCIICodeIndex = kDataIndex;
6385 // Irregexp compiled code or bytecode for UC16. If compilation
6386 // fails, this fields hold an exception object that should be
6387 // thrown if the regexp is used again.
6388 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
6390 // Saved instance of Irregexp compiled code or bytecode for ASCII that
6391 // is a potential candidate for flushing.
6392 static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
6393 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
6394 // a potential candidate for flushing.
6395 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
6397 // Maximal number of registers used by either ASCII or UC16.
6398 // Only used to check that there is enough stack space
6399 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
6400 // Number of captures in the compiled regexp.
6401 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
6403 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
6405 // Offsets directly into the data fixed array.
6406 static const int kDataTagOffset =
6407 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
6408 static const int kDataAsciiCodeOffset =
6409 FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
6410 static const int kDataUC16CodeOffset =
6411 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
6412 static const int kIrregexpCaptureCountOffset =
6413 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
6415 // In-object fields.
6416 static const int kSourceFieldIndex = 0;
6417 static const int kGlobalFieldIndex = 1;
6418 static const int kIgnoreCaseFieldIndex = 2;
6419 static const int kMultilineFieldIndex = 3;
6420 static const int kLastIndexFieldIndex = 4;
6421 static const int kInObjectFieldCount = 5;
6423 // The uninitialized value for a regexp code object.
6424 static const int kUninitializedValue = -1;
6426 // The compilation error value for the regexp code object. The real error
6427 // object is in the saved code field.
6428 static const int kCompilationErrorValue = -2;
6430 // When we store the sweep generation at which we moved the code from the
6431 // code index to the saved code index we mask it of to be in the [0:255]
6433 static const int kCodeAgeMask = 0xff;
6437 class CompilationCacheShape : public BaseShape<HashTableKey*> {
6439 static inline bool IsMatch(HashTableKey* key, Object* value) {
6440 return key->IsMatch(value);
6443 static inline uint32_t Hash(HashTableKey* key) {
6447 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6448 return key->HashForObject(object);
6451 MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6452 return key->AsObject();
6455 static const int kPrefixSize = 0;
6456 static const int kEntrySize = 2;
6460 class CompilationCacheTable: public HashTable<CompilationCacheShape,
6463 // Find cached value for a string key, otherwise return null.
6464 Object* Lookup(String* src);
6465 Object* LookupEval(String* src,
6467 LanguageMode language_mode,
6468 int scope_position);
6469 Object* LookupRegExp(String* source, JSRegExp::Flags flags);
6470 MUST_USE_RESULT MaybeObject* Put(String* src, Object* value);
6471 MUST_USE_RESULT MaybeObject* PutEval(String* src,
6473 SharedFunctionInfo* value,
6474 int scope_position);
6475 MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
6476 JSRegExp::Flags flags,
6479 // Remove given value from cache.
6480 void Remove(Object* value);
6482 static inline CompilationCacheTable* cast(Object* obj);
6485 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
6489 class CodeCache: public Struct {
6491 DECL_ACCESSORS(default_cache, FixedArray)
6492 DECL_ACCESSORS(normal_type_cache, Object)
6494 // Add the code object to the cache.
6495 MUST_USE_RESULT MaybeObject* Update(String* name, Code* code);
6497 // Lookup code object in the cache. Returns code object if found and undefined
6499 Object* Lookup(String* name, Code::Flags flags);
6501 // Get the internal index of a code object in the cache. Returns -1 if the
6502 // code object is not in that cache. This index can be used to later call
6503 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
6505 int GetIndex(Object* name, Code* code);
6507 // Remove an object from the cache with the provided internal index.
6508 void RemoveByIndex(Object* name, Code* code, int index);
6510 static inline CodeCache* cast(Object* obj);
6513 inline void CodeCachePrint() {
6514 CodeCachePrint(stdout);
6516 void CodeCachePrint(FILE* out);
6519 void CodeCacheVerify();
6522 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
6523 static const int kNormalTypeCacheOffset =
6524 kDefaultCacheOffset + kPointerSize;
6525 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
6528 MUST_USE_RESULT MaybeObject* UpdateDefaultCache(String* name, Code* code);
6529 MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(String* name, Code* code);
6530 Object* LookupDefaultCache(String* name, Code::Flags flags);
6531 Object* LookupNormalTypeCache(String* name, Code::Flags flags);
6533 // Code cache layout of the default cache. Elements are alternating name and
6534 // code objects for non normal load/store/call IC's.
6535 static const int kCodeCacheEntrySize = 2;
6536 static const int kCodeCacheEntryNameOffset = 0;
6537 static const int kCodeCacheEntryCodeOffset = 1;
6539 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
6543 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
6545 static inline bool IsMatch(HashTableKey* key, Object* value) {
6546 return key->IsMatch(value);
6549 static inline uint32_t Hash(HashTableKey* key) {
6553 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6554 return key->HashForObject(object);
6557 MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6558 return key->AsObject();
6561 static const int kPrefixSize = 0;
6562 static const int kEntrySize = 2;
6566 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
6569 Object* Lookup(String* name, Code::Flags flags);
6570 MUST_USE_RESULT MaybeObject* Put(String* name, Code* code);
6572 int GetIndex(String* name, Code::Flags flags);
6573 void RemoveByIndex(int index);
6575 static inline CodeCacheHashTable* cast(Object* obj);
6577 // Initial size of the fixed array backing the hash table.
6578 static const int kInitialSize = 64;
6581 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
6585 class PolymorphicCodeCache: public Struct {
6587 DECL_ACCESSORS(cache, Object)
6589 static void Update(Handle<PolymorphicCodeCache> cache,
6590 MapHandleList* maps,
6594 MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
6598 // Returns an undefined value if the entry is not found.
6599 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
6601 static inline PolymorphicCodeCache* cast(Object* obj);
6604 inline void PolymorphicCodeCachePrint() {
6605 PolymorphicCodeCachePrint(stdout);
6607 void PolymorphicCodeCachePrint(FILE* out);
6610 void PolymorphicCodeCacheVerify();
6613 static const int kCacheOffset = HeapObject::kHeaderSize;
6614 static const int kSize = kCacheOffset + kPointerSize;
6617 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
6621 class PolymorphicCodeCacheHashTable
6622 : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
6624 Object* Lookup(MapHandleList* maps, int code_kind);
6626 MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
6630 static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
6632 static const int kInitialSize = 64;
6634 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
6638 class TypeFeedbackInfo: public Struct {
6640 inline int ic_total_count();
6641 inline void set_ic_total_count(int count);
6643 inline int ic_with_type_info_count();
6644 inline void set_ic_with_type_info_count(int count);
6646 DECL_ACCESSORS(type_feedback_cells, TypeFeedbackCells)
6648 static inline TypeFeedbackInfo* cast(Object* obj);
6651 inline void TypeFeedbackInfoPrint() {
6652 TypeFeedbackInfoPrint(stdout);
6654 void TypeFeedbackInfoPrint(FILE* out);
6657 void TypeFeedbackInfoVerify();
6660 static const int kIcTotalCountOffset = HeapObject::kHeaderSize;
6661 static const int kIcWithTypeinfoCountOffset =
6662 kIcTotalCountOffset + kPointerSize;
6663 static const int kTypeFeedbackCellsOffset =
6664 kIcWithTypeinfoCountOffset + kPointerSize;
6665 static const int kSize = kTypeFeedbackCellsOffset + kPointerSize;
6668 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
6672 // Representation of a slow alias as part of a non-strict arguments objects.
6673 // For fast aliases (if HasNonStrictArgumentsElements()):
6674 // - the parameter map contains an index into the context
6675 // - all attributes of the element have default values
6676 // For slow aliases (if HasDictionaryArgumentsElements()):
6677 // - the parameter map contains no fast alias mapping (i.e. the hole)
6678 // - this struct (in the slow backing store) contains an index into the context
6679 // - all attributes are available as part if the property details
6680 class AliasedArgumentsEntry: public Struct {
6682 inline int aliased_context_slot();
6683 inline void set_aliased_context_slot(int count);
6685 static inline AliasedArgumentsEntry* cast(Object* obj);
6688 inline void AliasedArgumentsEntryPrint() {
6689 AliasedArgumentsEntryPrint(stdout);
6691 void AliasedArgumentsEntryPrint(FILE* out);
6694 void AliasedArgumentsEntryVerify();
6697 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
6698 static const int kSize = kAliasedContextSlot + kPointerSize;
6701 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
6705 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
6706 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
6709 class StringHasher {
6711 explicit inline StringHasher(int length, uint32_t seed);
6713 // Returns true if the hash of this string can be computed without
6714 // looking at the contents.
6715 inline bool has_trivial_hash();
6717 // Add a character to the hash and update the array index calculation.
6718 inline void AddCharacter(uint32_t c);
6720 // Adds a character to the hash but does not update the array index
6721 // calculation. This can only be called when it has been verified
6722 // that the input is not an array index.
6723 inline void AddCharacterNoIndex(uint32_t c);
6725 // Add a character above 0xffff as a surrogate pair. These can get into
6726 // the hasher through the routines that take a UTF-8 string and make a symbol.
6727 void AddSurrogatePair(uc32 c);
6728 void AddSurrogatePairNoIndex(uc32 c);
6730 // Returns the value to store in the hash field of a string with
6731 // the given length and contents.
6732 uint32_t GetHashField();
6734 // Returns true if the characters seen so far make up a legal array
6736 bool is_array_index() { return is_array_index_; }
6738 bool is_valid() { return is_valid_; }
6740 void invalidate() { is_valid_ = false; }
6742 // Calculated hash value for a string consisting of 1 to
6743 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
6744 // value is represented decimal value.
6745 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
6747 // No string is allowed to have a hash of zero. That value is reserved
6748 // for internal properties. If the hash calculation yields zero then we
6750 static const int kZeroHash = 27;
6753 uint32_t array_index() {
6754 ASSERT(is_array_index());
6755 return array_index_;
6758 inline uint32_t GetHash();
6761 uint32_t raw_running_hash_;
6762 uint32_t array_index_;
6763 bool is_array_index_;
6764 bool is_first_char_;
6766 friend class TwoCharHashTableKey;
6770 // Calculates string hash.
6771 template <typename schar>
6772 inline uint32_t HashSequentialString(const schar* chars,
6777 // The characteristics of a string are stored in its map. Retrieving these
6778 // few bits of information is moderately expensive, involving two memory
6779 // loads where the second is dependent on the first. To improve efficiency
6780 // the shape of the string is given its own class so that it can be retrieved
6781 // once and used for several string operations. A StringShape is small enough
6782 // to be passed by value and is immutable, but be aware that flattening a
6783 // string can potentially alter its shape. Also be aware that a GC caused by
6784 // something else can alter the shape of a string due to ConsString
6785 // shortcutting. Keeping these restrictions in mind has proven to be error-
6786 // prone and so we no longer put StringShapes in variables unless there is a
6787 // concrete performance benefit at that particular point in the code.
6788 class StringShape BASE_EMBEDDED {
6790 inline explicit StringShape(String* s);
6791 inline explicit StringShape(Map* s);
6792 inline explicit StringShape(InstanceType t);
6793 inline bool IsSequential();
6794 inline bool IsExternal();
6795 inline bool IsCons();
6796 inline bool IsSliced();
6797 inline bool IsIndirect();
6798 inline bool IsExternalAscii();
6799 inline bool IsExternalTwoByte();
6800 inline bool IsSequentialAscii();
6801 inline bool IsSequentialTwoByte();
6802 inline bool IsSymbol();
6803 inline StringRepresentationTag representation_tag();
6804 inline uint32_t encoding_tag();
6805 inline uint32_t full_representation_tag();
6806 inline uint32_t size_tag();
6808 inline uint32_t type() { return type_; }
6809 inline void invalidate() { valid_ = false; }
6810 inline bool valid() { return valid_; }
6812 inline void invalidate() { }
6818 inline void set_valid() { valid_ = true; }
6821 inline void set_valid() { }
6826 // The String abstract class captures JavaScript string values:
6829 // 4.3.16 String Value
6830 // A string value is a member of the type String and is a finite
6831 // ordered sequence of zero or more 16-bit unsigned integer values.
6833 // All string values have a length field.
6834 class String: public HeapObject {
6836 // Representation of the flat content of a String.
6837 // A non-flat string doesn't have flat content.
6838 // A flat string has content that's encoded as a sequence of either
6839 // ASCII chars or two-byte UC16.
6840 // Returned by String::GetFlatContent().
6843 // Returns true if the string is flat and this structure contains content.
6844 bool IsFlat() { return state_ != NON_FLAT; }
6845 // Returns true if the structure contains ASCII content.
6846 bool IsAscii() { return state_ == ASCII; }
6847 // Returns true if the structure contains two-byte content.
6848 bool IsTwoByte() { return state_ == TWO_BYTE; }
6850 // Return the ASCII content of the string. Only use if IsAscii() returns
6852 Vector<const char> ToAsciiVector() {
6853 ASSERT_EQ(ASCII, state_);
6854 return Vector<const char>::cast(buffer_);
6856 // Return the two-byte content of the string. Only use if IsTwoByte()
6858 Vector<const uc16> ToUC16Vector() {
6859 ASSERT_EQ(TWO_BYTE, state_);
6860 return Vector<const uc16>::cast(buffer_);
6864 enum State { NON_FLAT, ASCII, TWO_BYTE };
6866 // Constructors only used by String::GetFlatContent().
6867 explicit FlatContent(Vector<const char> chars)
6868 : buffer_(Vector<const byte>::cast(chars)),
6870 explicit FlatContent(Vector<const uc16> chars)
6871 : buffer_(Vector<const byte>::cast(chars)),
6872 state_(TWO_BYTE) { }
6873 FlatContent() : buffer_(), state_(NON_FLAT) { }
6875 Vector<const byte> buffer_;
6878 friend class String;
6881 // Get and set the length of the string.
6882 inline int length();
6883 inline void set_length(int value);
6885 // Get and set the hash field of the string.
6886 inline uint32_t hash_field();
6887 inline void set_hash_field(uint32_t value);
6889 // Returns whether this string has only ASCII chars, i.e. all of them can
6890 // be ASCII encoded. This might be the case even if the string is
6891 // two-byte. Such strings may appear when the embedder prefers
6892 // two-byte external representations even for ASCII data.
6893 inline bool IsAsciiRepresentation();
6894 inline bool IsTwoByteRepresentation();
6896 // Cons and slices have an encoding flag that may not represent the actual
6897 // encoding of the underlying string. This is taken into account here.
6898 // Requires: this->IsFlat()
6899 inline bool IsAsciiRepresentationUnderneath();
6900 inline bool IsTwoByteRepresentationUnderneath();
6902 // NOTE: this should be considered only a hint. False negatives are
6904 inline bool HasOnlyAsciiChars();
6906 // Get and set individual two byte chars in the string.
6907 inline void Set(int index, uint16_t value);
6908 // Get individual two byte char in the string. Repeated calls
6909 // to this method are not efficient unless the string is flat.
6910 INLINE(uint16_t Get(int index));
6912 // Try to flatten the string. Checks first inline to see if it is
6913 // necessary. Does nothing if the string is not a cons string.
6914 // Flattening allocates a sequential string with the same data as
6915 // the given string and mutates the cons string to a degenerate
6916 // form, where the first component is the new sequential string and
6917 // the second component is the empty string. If allocation fails,
6918 // this function returns a failure. If flattening succeeds, this
6919 // function returns the sequential string that is now the first
6920 // component of the cons string.
6922 // Degenerate cons strings are handled specially by the garbage
6923 // collector (see IsShortcutCandidate).
6925 // Use FlattenString from Handles.cc to flatten even in case an
6926 // allocation failure happens.
6927 inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
6929 // Convenience function. Has exactly the same behavior as
6930 // TryFlatten(), except in the case of failure returns the original
6932 inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
6934 // Tries to return the content of a flat string as a structure holding either
6935 // a flat vector of char or of uc16.
6936 // If the string isn't flat, and therefore doesn't have flat content, the
6937 // returned structure will report so, and can't provide a vector of either
6939 FlatContent GetFlatContent();
6941 // Returns the parent of a sliced string or first part of a flat cons string.
6942 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
6943 inline String* GetUnderlying();
6945 // Mark the string as an undetectable object. It only applies to
6946 // ASCII and two byte string types.
6947 bool MarkAsUndetectable();
6949 // Return a substring.
6950 MUST_USE_RESULT MaybeObject* SubString(int from,
6952 PretenureFlag pretenure = NOT_TENURED);
6954 // String equality operations.
6955 inline bool Equals(String* other);
6956 bool IsEqualTo(Vector<const char> str);
6957 bool IsAsciiEqualTo(Vector<const char> str);
6958 bool IsTwoByteEqualTo(Vector<const uc16> str);
6960 bool SlowEqualsExternal(uc16 *string, int length);
6961 bool SlowEqualsExternal(char *string, int length);
6963 // Return a UTF8 representation of the string. The string is null
6964 // terminated but may optionally contain nulls. Length is returned
6965 // in length_output if length_output is not a null pointer The string
6966 // should be nearly flat, otherwise the performance of this method may
6967 // be very slow (quadratic in the length). Setting robustness_flag to
6968 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
6969 // handles unexpected data without causing assert failures and it does not
6970 // do any heap allocations. This is useful when printing stack traces.
6971 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
6972 RobustnessFlag robustness_flag,
6975 int* length_output = 0);
6976 SmartArrayPointer<char> ToCString(
6977 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
6978 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
6979 int* length_output = 0);
6981 // Return a 16 bit Unicode representation of the string.
6982 // The string should be nearly flat, otherwise the performance of
6983 // of this method may be very bad. Setting robustness_flag to
6984 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
6985 // handles unexpected data without causing assert failures and it does not
6986 // do any heap allocations. This is useful when printing stack traces.
6987 SmartArrayPointer<uc16> ToWideCString(
6988 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
6990 // Tells whether the hash code has been computed.
6991 inline bool HasHashCode();
6993 // Returns a hash value used for the property table
6994 inline uint32_t Hash();
6996 static uint32_t ComputeHashField(unibrow::CharacterStream* buffer,
7000 static bool ComputeArrayIndex(unibrow::CharacterStream* buffer,
7005 bool MakeExternal(v8::String::ExternalStringResource* resource);
7006 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
7009 inline bool AsArrayIndex(uint32_t* index);
7012 static inline String* cast(Object* obj);
7014 void PrintOn(FILE* out);
7016 // For use during stack traces. Performs rudimentary sanity check.
7019 // Dispatched behavior.
7020 void StringShortPrint(StringStream* accumulator);
7022 inline void StringPrint() {
7023 StringPrint(stdout);
7025 void StringPrint(FILE* out);
7027 char* ToAsciiArray();
7030 void StringVerify();
7032 inline bool IsFlat();
7034 // Layout description.
7035 static const int kLengthOffset = HeapObject::kHeaderSize;
7036 static const int kHashFieldOffset = kLengthOffset + kPointerSize;
7037 static const int kSize = kHashFieldOffset + kPointerSize;
7039 // Maximum number of characters to consider when trying to convert a string
7040 // value into an array index.
7041 static const int kMaxArrayIndexSize = 10;
7043 // Max ASCII char code.
7044 static const int kMaxAsciiCharCode = unibrow::Utf8::kMaxOneByteChar;
7045 static const unsigned kMaxAsciiCharCodeU = unibrow::Utf8::kMaxOneByteChar;
7046 static const int kMaxUtf16CodeUnit = 0xffff;
7048 // Mask constant for checking if a string has a computed hash code
7049 // and if it is an array index. The least significant bit indicates
7050 // whether a hash code has been computed. If the hash code has been
7051 // computed the 2nd bit tells whether the string can be used as an
7053 static const int kHashNotComputedMask = 1;
7054 static const int kIsNotArrayIndexMask = 1 << 1;
7055 static const int kNofHashBitFields = 2;
7057 // Shift constant retrieving hash code from hash field.
7058 static const int kHashShift = kNofHashBitFields;
7060 // Only these bits are relevant in the hash, since the top two are shifted
7062 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
7064 // Array index strings this short can keep their index in the hash
7066 static const int kMaxCachedArrayIndexLength = 7;
7068 // For strings which are array indexes the hash value has the string length
7069 // mixed into the hash, mainly to avoid a hash value of zero which would be
7070 // the case for the string '0'. 24 bits are used for the array index value.
7071 static const int kArrayIndexValueBits = 24;
7072 static const int kArrayIndexLengthBits =
7073 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
7075 STATIC_CHECK((kArrayIndexLengthBits > 0));
7076 STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
7078 static const int kArrayIndexHashLengthShift =
7079 kArrayIndexValueBits + kNofHashBitFields;
7081 static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
7083 static const int kArrayIndexValueMask =
7084 ((1 << kArrayIndexValueBits) - 1) << kHashShift;
7086 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
7087 // could use a mask to test if the length of string is less than or equal to
7088 // kMaxCachedArrayIndexLength.
7089 STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
7091 static const int kContainsCachedArrayIndexMask =
7092 (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
7093 kIsNotArrayIndexMask;
7095 // Value of empty hash field indicating that the hash is not computed.
7096 static const int kEmptyHashField =
7097 kIsNotArrayIndexMask | kHashNotComputedMask;
7099 // Value of hash field containing computed hash equal to zero.
7100 static const int kZeroHash = kIsNotArrayIndexMask;
7102 // Maximal string length.
7103 static const int kMaxLength = (1 << (32 - 2)) - 1;
7105 // Max length for computing hash. For strings longer than this limit the
7106 // string length is used as the hash value.
7107 static const int kMaxHashCalcLength = 16383;
7109 // Limit for truncation in short printing.
7110 static const int kMaxShortPrintLength = 1024;
7112 // Support for regular expressions.
7113 const uc16* GetTwoByteData();
7114 const uc16* GetTwoByteData(unsigned start);
7116 // Support for StringInputBuffer
7117 static const unibrow::byte* ReadBlock(String* input,
7118 unibrow::byte* util_buffer,
7120 unsigned* remaining,
7122 static const unibrow::byte* ReadBlock(String** input,
7123 unibrow::byte* util_buffer,
7125 unsigned* remaining,
7128 // Helper function for flattening strings.
7129 template <typename sinkchar>
7130 static void WriteToFlat(String* source,
7135 static inline bool IsAscii(const char* chars, int length) {
7136 const char* limit = chars + length;
7137 #ifdef V8_HOST_CAN_READ_UNALIGNED
7138 ASSERT(kMaxAsciiCharCode == 0x7F);
7139 const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
7140 while (chars <= limit - sizeof(uintptr_t)) {
7141 if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
7144 chars += sizeof(uintptr_t);
7147 while (chars < limit) {
7148 if (static_cast<uint8_t>(*chars) > kMaxAsciiCharCodeU) return false;
7154 static inline bool IsAscii(const uc16* chars, int length) {
7155 const uc16* limit = chars + length;
7156 while (chars < limit) {
7157 if (*chars > kMaxAsciiCharCodeU) return false;
7164 class ReadBlockBuffer {
7166 ReadBlockBuffer(unibrow::byte* util_buffer_,
7169 unsigned remaining_) :
7170 util_buffer(util_buffer_),
7172 capacity(capacity_),
7173 remaining(remaining_) {
7175 unibrow::byte* util_buffer;
7181 static inline const unibrow::byte* ReadBlock(String* input,
7182 ReadBlockBuffer* buffer,
7184 unsigned max_chars);
7185 static void ReadBlockIntoBuffer(String* input,
7186 ReadBlockBuffer* buffer,
7187 unsigned* offset_ptr,
7188 unsigned max_chars);
7191 // Try to flatten the top level ConsString that is hiding behind this
7192 // string. This is a no-op unless the string is a ConsString. Flatten
7193 // mutates the ConsString and might return a failure.
7194 MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
7196 static inline bool IsHashFieldComputed(uint32_t field);
7198 // Slow case of String::Equals. This implementation works on any strings
7199 // but it is most efficient on strings that are almost flat.
7200 bool SlowEquals(String* other);
7202 // Slow case of AsArrayIndex.
7203 bool SlowAsArrayIndex(uint32_t* index);
7205 // Compute and set the hash code.
7206 uint32_t ComputeAndSetHash();
7208 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
7212 // The SeqString abstract class captures sequential string values.
7213 class SeqString: public String {
7216 static inline SeqString* cast(Object* obj);
7218 // Get and set the symbol id of the string
7219 inline int symbol_id();
7220 inline void set_symbol_id(int value);
7222 // Layout description.
7223 static const int kSymbolIdOffset = String::kSize;
7224 static const int kHeaderSize = kSymbolIdOffset + kPointerSize;
7227 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
7231 // The AsciiString class captures sequential ASCII string objects.
7232 // Each character in the AsciiString is an ASCII character.
7233 class SeqAsciiString: public SeqString {
7235 static const bool kHasAsciiEncoding = true;
7237 // Dispatched behavior.
7238 inline uint16_t SeqAsciiStringGet(int index);
7239 inline void SeqAsciiStringSet(int index, uint16_t value);
7241 // Get the address of the characters in this string.
7242 inline Address GetCharsAddress();
7244 inline char* GetChars();
7247 static inline SeqAsciiString* cast(Object* obj);
7249 // Garbage collection support. This method is called by the
7250 // garbage collector to compute the actual size of an AsciiString
7252 inline int SeqAsciiStringSize(InstanceType instance_type);
7254 // Computes the size for an AsciiString instance of a given length.
7255 static int SizeFor(int length) {
7256 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
7259 // Maximal memory usage for a single sequential ASCII string.
7260 static const int kMaxSize = 512 * MB - 1;
7261 // Maximal length of a single sequential ASCII string.
7262 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7263 static const int kMaxLength = (kMaxSize - kHeaderSize);
7265 // Support for StringInputBuffer.
7266 inline void SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7269 inline const unibrow::byte* SeqAsciiStringReadBlock(unsigned* remaining,
7274 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqAsciiString);
7278 // The TwoByteString class captures sequential unicode string objects.
7279 // Each character in the TwoByteString is a two-byte uint16_t.
7280 class SeqTwoByteString: public SeqString {
7282 static const bool kHasAsciiEncoding = false;
7284 // Dispatched behavior.
7285 inline uint16_t SeqTwoByteStringGet(int index);
7286 inline void SeqTwoByteStringSet(int index, uint16_t value);
7288 // Get the address of the characters in this string.
7289 inline Address GetCharsAddress();
7291 inline uc16* GetChars();
7294 const uint16_t* SeqTwoByteStringGetData(unsigned start);
7297 static inline SeqTwoByteString* cast(Object* obj);
7299 // Garbage collection support. This method is called by the
7300 // garbage collector to compute the actual size of a TwoByteString
7302 inline int SeqTwoByteStringSize(InstanceType instance_type);
7304 // Computes the size for a TwoByteString instance of a given length.
7305 static int SizeFor(int length) {
7306 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
7309 // Maximal memory usage for a single sequential two-byte string.
7310 static const int kMaxSize = 512 * MB - 1;
7311 // Maximal length of a single sequential two-byte string.
7312 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7313 static const int kMaxLength = (kMaxSize - kHeaderSize) / sizeof(uint16_t);
7315 // Support for StringInputBuffer.
7316 inline void SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7317 unsigned* offset_ptr,
7321 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
7325 // The ConsString class describes string values built by using the
7326 // addition operator on strings. A ConsString is a pair where the
7327 // first and second components are pointers to other string values.
7328 // One or both components of a ConsString can be pointers to other
7329 // ConsStrings, creating a binary tree of ConsStrings where the leaves
7330 // are non-ConsString string values. The string value represented by
7331 // a ConsString can be obtained by concatenating the leaf string
7332 // values in a left-to-right depth-first traversal of the tree.
7333 class ConsString: public String {
7335 // First string of the cons cell.
7336 inline String* first();
7337 // Doesn't check that the result is a string, even in debug mode. This is
7338 // useful during GC where the mark bits confuse the checks.
7339 inline Object* unchecked_first();
7340 inline void set_first(String* first,
7341 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7343 // Second string of the cons cell.
7344 inline String* second();
7345 // Doesn't check that the result is a string, even in debug mode. This is
7346 // useful during GC where the mark bits confuse the checks.
7347 inline Object* unchecked_second();
7348 inline void set_second(String* second,
7349 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7351 // Dispatched behavior.
7352 uint16_t ConsStringGet(int index);
7355 static inline ConsString* cast(Object* obj);
7357 // Layout description.
7358 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
7359 static const int kSecondOffset = kFirstOffset + kPointerSize;
7360 static const int kSize = kSecondOffset + kPointerSize;
7362 // Support for StringInputBuffer.
7363 inline const unibrow::byte* ConsStringReadBlock(ReadBlockBuffer* buffer,
7364 unsigned* offset_ptr,
7366 inline void ConsStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7367 unsigned* offset_ptr,
7370 // Minimum length for a cons string.
7371 static const int kMinLength = 13;
7373 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
7377 void ConsStringVerify();
7381 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
7385 // The Sliced String class describes strings that are substrings of another
7386 // sequential string. The motivation is to save time and memory when creating
7387 // a substring. A Sliced String is described as a pointer to the parent,
7388 // the offset from the start of the parent string and the length. Using
7389 // a Sliced String therefore requires unpacking of the parent string and
7390 // adding the offset to the start address. A substring of a Sliced String
7391 // are not nested since the double indirection is simplified when creating
7392 // such a substring.
7393 // Currently missing features are:
7394 // - handling externalized parent strings
7395 // - external strings as parent
7396 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
7397 class SlicedString: public String {
7399 inline String* parent();
7400 inline void set_parent(String* parent);
7401 inline int offset();
7402 inline void set_offset(int offset);
7404 // Dispatched behavior.
7405 uint16_t SlicedStringGet(int index);
7408 static inline SlicedString* cast(Object* obj);
7410 // Layout description.
7411 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
7412 static const int kOffsetOffset = kParentOffset + kPointerSize;
7413 static const int kSize = kOffsetOffset + kPointerSize;
7415 // Support for StringInputBuffer
7416 inline const unibrow::byte* SlicedStringReadBlock(ReadBlockBuffer* buffer,
7417 unsigned* offset_ptr,
7419 inline void SlicedStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7420 unsigned* offset_ptr,
7422 // Minimum length for a sliced string.
7423 static const int kMinLength = 13;
7425 typedef FixedBodyDescriptor<kParentOffset,
7426 kOffsetOffset + kPointerSize, kSize>
7430 void SlicedStringVerify();
7434 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
7438 // The ExternalString class describes string values that are backed by
7439 // a string resource that lies outside the V8 heap. ExternalStrings
7440 // consist of the length field common to all strings, a pointer to the
7441 // external resource. It is important to ensure (externally) that the
7442 // resource is not deallocated while the ExternalString is live in the
7445 // The API expects that all ExternalStrings are created through the
7446 // API. Therefore, ExternalStrings should not be used internally.
7447 class ExternalString: public String {
7450 static inline ExternalString* cast(Object* obj);
7452 // Layout description.
7453 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
7454 static const int kShortSize = kResourceOffset + kPointerSize;
7455 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
7456 static const int kSize = kResourceDataOffset + kPointerSize;
7458 // Return whether external string is short (data pointer is not cached).
7459 inline bool is_short();
7461 STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
7464 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
7468 // The ExternalAsciiString class is an external string backed by an
7470 class ExternalAsciiString: public ExternalString {
7472 static const bool kHasAsciiEncoding = true;
7474 typedef v8::String::ExternalAsciiStringResource Resource;
7476 // The underlying resource.
7477 inline const Resource* resource();
7478 inline void set_resource(const Resource* buffer);
7480 // Update the pointer cache to the external character array.
7481 // The cached pointer is always valid, as the external character array does =
7482 // not move during lifetime. Deserialization is the only exception, after
7483 // which the pointer cache has to be refreshed.
7484 inline void update_data_cache();
7486 inline const char* GetChars();
7488 // Dispatched behavior.
7489 inline uint16_t ExternalAsciiStringGet(int index);
7492 static inline ExternalAsciiString* cast(Object* obj);
7494 // Garbage collection support.
7495 inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
7497 template<typename StaticVisitor>
7498 inline void ExternalAsciiStringIterateBody();
7500 // Support for StringInputBuffer.
7501 const unibrow::byte* ExternalAsciiStringReadBlock(unsigned* remaining,
7504 inline void ExternalAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7509 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
7513 // The ExternalTwoByteString class is an external string backed by a UTF-16
7515 class ExternalTwoByteString: public ExternalString {
7517 static const bool kHasAsciiEncoding = false;
7519 typedef v8::String::ExternalStringResource Resource;
7521 // The underlying string resource.
7522 inline const Resource* resource();
7523 inline void set_resource(const Resource* buffer);
7525 // Update the pointer cache to the external character array.
7526 // The cached pointer is always valid, as the external character array does =
7527 // not move during lifetime. Deserialization is the only exception, after
7528 // which the pointer cache has to be refreshed.
7529 inline void update_data_cache();
7531 inline const uint16_t* GetChars();
7533 // Dispatched behavior.
7534 inline uint16_t ExternalTwoByteStringGet(int index);
7537 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
7540 static inline ExternalTwoByteString* cast(Object* obj);
7542 // Garbage collection support.
7543 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
7545 template<typename StaticVisitor>
7546 inline void ExternalTwoByteStringIterateBody();
7549 // Support for StringInputBuffer.
7550 void ExternalTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7551 unsigned* offset_ptr,
7555 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
7559 // Utility superclass for stack-allocated objects that must be updated
7560 // on gc. It provides two ways for the gc to update instances, either
7561 // iterating or updating after gc.
7562 class Relocatable BASE_EMBEDDED {
7564 explicit inline Relocatable(Isolate* isolate);
7565 inline virtual ~Relocatable();
7566 virtual void IterateInstance(ObjectVisitor* v) { }
7567 virtual void PostGarbageCollection() { }
7569 static void PostGarbageCollectionProcessing();
7570 static int ArchiveSpacePerThread();
7571 static char* ArchiveState(Isolate* isolate, char* to);
7572 static char* RestoreState(Isolate* isolate, char* from);
7573 static void Iterate(ObjectVisitor* v);
7574 static void Iterate(ObjectVisitor* v, Relocatable* top);
7575 static char* Iterate(ObjectVisitor* v, char* t);
7582 // A flat string reader provides random access to the contents of a
7583 // string independent of the character width of the string. The handle
7584 // must be valid as long as the reader is being used.
7585 class FlatStringReader : public Relocatable {
7587 FlatStringReader(Isolate* isolate, Handle<String> str);
7588 FlatStringReader(Isolate* isolate, Vector<const char> input);
7589 void PostGarbageCollection();
7590 inline uc32 Get(int index);
7591 int length() { return length_; }
7600 // Note that StringInputBuffers are not valid across a GC! To fix this
7601 // it would have to store a String Handle instead of a String* and
7602 // AsciiStringReadBlock would have to be modified to use memcpy.
7604 // StringInputBuffer is able to traverse any string regardless of how
7605 // deeply nested a sequence of ConsStrings it is made of. However,
7606 // performance will be better if deep strings are flattened before they
7607 // are traversed. Since flattening requires memory allocation this is
7608 // not always desirable, however (esp. in debugging situations).
7609 class StringInputBuffer: public unibrow::InputBuffer<String, String*, 1024> {
7611 virtual void Seek(unsigned pos);
7612 inline StringInputBuffer(): unibrow::InputBuffer<String, String*, 1024>() {}
7613 explicit inline StringInputBuffer(String* backing):
7614 unibrow::InputBuffer<String, String*, 1024>(backing) {}
7618 class SafeStringInputBuffer
7619 : public unibrow::InputBuffer<String, String**, 256> {
7621 virtual void Seek(unsigned pos);
7622 inline SafeStringInputBuffer()
7623 : unibrow::InputBuffer<String, String**, 256>() {}
7624 explicit inline SafeStringInputBuffer(String** backing)
7625 : unibrow::InputBuffer<String, String**, 256>(backing) {}
7629 template <typename T>
7630 class VectorIterator {
7632 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
7633 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
7634 T GetNext() { return data_[index_++]; }
7635 bool has_more() { return index_ < data_.length(); }
7637 Vector<const T> data_;
7642 // The Oddball describes objects null, undefined, true, and false.
7643 class Oddball: public HeapObject {
7645 // [to_string]: Cached to_string computed at startup.
7646 DECL_ACCESSORS(to_string, String)
7648 // [to_number]: Cached to_number computed at startup.
7649 DECL_ACCESSORS(to_number, Object)
7652 inline void set_kind(byte kind);
7655 static inline Oddball* cast(Object* obj);
7657 // Dispatched behavior.
7659 void OddballVerify();
7662 // Initialize the fields.
7663 MUST_USE_RESULT MaybeObject* Initialize(const char* to_string,
7667 // Layout description.
7668 static const int kToStringOffset = HeapObject::kHeaderSize;
7669 static const int kToNumberOffset = kToStringOffset + kPointerSize;
7670 static const int kKindOffset = kToNumberOffset + kPointerSize;
7671 static const int kSize = kKindOffset + kPointerSize;
7673 static const byte kFalse = 0;
7674 static const byte kTrue = 1;
7675 static const byte kNotBooleanMask = ~1;
7676 static const byte kTheHole = 2;
7677 static const byte kNull = 3;
7678 static const byte kArgumentMarker = 4;
7679 static const byte kUndefined = 5;
7680 static const byte kOther = 6;
7682 typedef FixedBodyDescriptor<kToStringOffset,
7683 kToNumberOffset + kPointerSize,
7684 kSize> BodyDescriptor;
7686 STATIC_CHECK(kKindOffset == Internals::kOddballKindOffset);
7687 STATIC_CHECK(kNull == Internals::kNullOddballKind);
7688 STATIC_CHECK(kUndefined == Internals::kUndefinedOddballKind);
7691 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
7695 class JSGlobalPropertyCell: public HeapObject {
7697 // [value]: value of the global property.
7698 DECL_ACCESSORS(value, Object)
7701 static inline JSGlobalPropertyCell* cast(Object* obj);
7704 void JSGlobalPropertyCellVerify();
7707 inline void JSGlobalPropertyCellPrint() {
7708 JSGlobalPropertyCellPrint(stdout);
7710 void JSGlobalPropertyCellPrint(FILE* out);
7713 // Layout description.
7714 static const int kValueOffset = HeapObject::kHeaderSize;
7715 static const int kSize = kValueOffset + kPointerSize;
7717 typedef FixedBodyDescriptor<kValueOffset,
7718 kValueOffset + kPointerSize,
7719 kSize> BodyDescriptor;
7722 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalPropertyCell);
7726 // The JSProxy describes EcmaScript Harmony proxies
7727 class JSProxy: public JSReceiver {
7729 // [handler]: The handler property.
7730 DECL_ACCESSORS(handler, Object)
7732 // [hash]: The hash code property (undefined if not initialized yet).
7733 DECL_ACCESSORS(hash, Object)
7736 static inline JSProxy* cast(Object* obj);
7738 bool HasPropertyWithHandler(String* name);
7739 bool HasElementWithHandler(uint32_t index);
7741 MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
7744 MUST_USE_RESULT MaybeObject* GetElementWithHandler(
7748 MUST_USE_RESULT MaybeObject* SetPropertyWithHandler(
7751 PropertyAttributes attributes,
7752 StrictModeFlag strict_mode);
7753 MUST_USE_RESULT MaybeObject* SetElementWithHandler(
7756 StrictModeFlag strict_mode);
7758 // If the handler defines an accessor property, invoke its setter
7759 // (or throw if only a getter exists) and set *found to true. Otherwise false.
7760 MUST_USE_RESULT MaybeObject* SetPropertyWithHandlerIfDefiningSetter(
7763 PropertyAttributes attributes,
7764 StrictModeFlag strict_mode,
7767 MUST_USE_RESULT MaybeObject* DeletePropertyWithHandler(
7770 MUST_USE_RESULT MaybeObject* DeleteElementWithHandler(
7774 MUST_USE_RESULT PropertyAttributes GetPropertyAttributeWithHandler(
7775 JSReceiver* receiver,
7777 MUST_USE_RESULT PropertyAttributes GetElementAttributeWithHandler(
7778 JSReceiver* receiver,
7781 MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
7783 // Turn this into an (empty) JSObject.
7786 // Initializes the body after the handler slot.
7787 inline void InitializeBody(int object_size, Object* value);
7789 // Invoke a trap by name. If the trap does not exist on this's handler,
7790 // but derived_trap is non-NULL, invoke that instead. May cause GC.
7791 Handle<Object> CallTrap(const char* name,
7792 Handle<Object> derived_trap,
7794 Handle<Object> args[]);
7796 // Dispatched behavior.
7798 inline void JSProxyPrint() {
7799 JSProxyPrint(stdout);
7801 void JSProxyPrint(FILE* out);
7804 void JSProxyVerify();
7807 // Layout description. We add padding so that a proxy has the same
7808 // size as a virgin JSObject. This is essential for becoming a JSObject
7810 static const int kHandlerOffset = HeapObject::kHeaderSize;
7811 static const int kHashOffset = kHandlerOffset + kPointerSize;
7812 static const int kPaddingOffset = kHashOffset + kPointerSize;
7813 static const int kSize = JSObject::kHeaderSize;
7814 static const int kHeaderSize = kPaddingOffset;
7815 static const int kPaddingSize = kSize - kPaddingOffset;
7817 STATIC_CHECK(kPaddingSize >= 0);
7819 typedef FixedBodyDescriptor<kHandlerOffset,
7821 kSize> BodyDescriptor;
7824 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
7828 class JSFunctionProxy: public JSProxy {
7830 // [call_trap]: The call trap.
7831 DECL_ACCESSORS(call_trap, Object)
7833 // [construct_trap]: The construct trap.
7834 DECL_ACCESSORS(construct_trap, Object)
7837 static inline JSFunctionProxy* cast(Object* obj);
7839 // Dispatched behavior.
7841 inline void JSFunctionProxyPrint() {
7842 JSFunctionProxyPrint(stdout);
7844 void JSFunctionProxyPrint(FILE* out);
7847 void JSFunctionProxyVerify();
7850 // Layout description.
7851 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
7852 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
7853 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
7854 static const int kSize = JSFunction::kSize;
7855 static const int kPaddingSize = kSize - kPaddingOffset;
7857 STATIC_CHECK(kPaddingSize >= 0);
7859 typedef FixedBodyDescriptor<kHandlerOffset,
7860 kConstructTrapOffset + kPointerSize,
7861 kSize> BodyDescriptor;
7864 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
7868 // The JSSet describes EcmaScript Harmony sets
7869 class JSSet: public JSObject {
7871 // [set]: the backing hash set containing keys.
7872 DECL_ACCESSORS(table, Object)
7875 static inline JSSet* cast(Object* obj);
7878 inline void JSSetPrint() {
7881 void JSSetPrint(FILE* out);
7887 static const int kTableOffset = JSObject::kHeaderSize;
7888 static const int kSize = kTableOffset + kPointerSize;
7891 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
7895 // The JSMap describes EcmaScript Harmony maps
7896 class JSMap: public JSObject {
7898 // [table]: the backing hash table mapping keys to values.
7899 DECL_ACCESSORS(table, Object)
7902 static inline JSMap* cast(Object* obj);
7905 inline void JSMapPrint() {
7908 void JSMapPrint(FILE* out);
7914 static const int kTableOffset = JSObject::kHeaderSize;
7915 static const int kSize = kTableOffset + kPointerSize;
7918 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
7922 // The JSWeakMap describes EcmaScript Harmony weak maps
7923 class JSWeakMap: public JSObject {
7925 // [table]: the backing hash table mapping keys to values.
7926 DECL_ACCESSORS(table, Object)
7928 // [next]: linked list of encountered weak maps during GC.
7929 DECL_ACCESSORS(next, Object)
7932 static inline JSWeakMap* cast(Object* obj);
7935 inline void JSWeakMapPrint() {
7936 JSWeakMapPrint(stdout);
7938 void JSWeakMapPrint(FILE* out);
7941 void JSWeakMapVerify();
7944 static const int kTableOffset = JSObject::kHeaderSize;
7945 static const int kNextOffset = kTableOffset + kPointerSize;
7946 static const int kSize = kNextOffset + kPointerSize;
7949 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
7953 // Foreign describes objects pointing from JavaScript to C structures.
7954 // Since they cannot contain references to JS HeapObjects they can be
7955 // placed in old_data_space.
7956 class Foreign: public HeapObject {
7958 // [address]: field containing the address.
7959 inline Address foreign_address();
7960 inline void set_foreign_address(Address value);
7963 static inline Foreign* cast(Object* obj);
7965 // Dispatched behavior.
7966 inline void ForeignIterateBody(ObjectVisitor* v);
7968 template<typename StaticVisitor>
7969 inline void ForeignIterateBody();
7972 inline void ForeignPrint() {
7973 ForeignPrint(stdout);
7975 void ForeignPrint(FILE* out);
7978 void ForeignVerify();
7981 // Layout description.
7983 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
7984 static const int kSize = kForeignAddressOffset + kPointerSize;
7986 STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
7989 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
7993 // The JSArray describes JavaScript Arrays
7994 // Such an array can be in one of two modes:
7995 // - fast, backing storage is a FixedArray and length <= elements.length();
7996 // Please note: push and pop can be used to grow and shrink the array.
7997 // - slow, backing storage is a HashTable with numbers as keys.
7998 class JSArray: public JSObject {
8000 // [length]: The length property.
8001 DECL_ACCESSORS(length, Object)
8003 // Overload the length setter to skip write barrier when the length
8004 // is set to a smi. This matches the set function on FixedArray.
8005 inline void set_length(Smi* length);
8007 MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
8010 // Initialize the array with the given capacity. The function may
8011 // fail due to out-of-memory situations, but only if the requested
8012 // capacity is non-zero.
8013 MUST_USE_RESULT MaybeObject* Initialize(int capacity);
8015 // Initializes the array to a certain length.
8016 inline bool AllowsSetElementsLength();
8017 MUST_USE_RESULT MaybeObject* SetElementsLength(Object* length);
8019 // Set the content of the array to the content of storage.
8020 MUST_USE_RESULT inline MaybeObject* SetContent(FixedArrayBase* storage);
8023 static inline JSArray* cast(Object* obj);
8025 // Uses handles. Ensures that the fixed array backing the JSArray has at
8026 // least the stated size.
8027 inline void EnsureSize(int minimum_size_of_backing_fixed_array);
8029 // Dispatched behavior.
8031 inline void JSArrayPrint() {
8032 JSArrayPrint(stdout);
8034 void JSArrayPrint(FILE* out);
8037 void JSArrayVerify();
8040 // Number of element slots to pre-allocate for an empty array.
8041 static const int kPreallocatedArrayElements = 4;
8043 // Layout description.
8044 static const int kLengthOffset = JSObject::kHeaderSize;
8045 static const int kSize = kLengthOffset + kPointerSize;
8048 // Expand the fixed array backing of a fast-case JSArray to at least
8049 // the requested size.
8050 void Expand(int minimum_size_of_backing_fixed_array);
8052 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
8056 // JSRegExpResult is just a JSArray with a specific initial map.
8057 // This initial map adds in-object properties for "index" and "input"
8058 // properties, as assigned by RegExp.prototype.exec, which allows
8059 // faster creation of RegExp exec results.
8060 // This class just holds constants used when creating the result.
8061 // After creation the result must be treated as a JSArray in all regards.
8062 class JSRegExpResult: public JSArray {
8064 // Offsets of object fields.
8065 static const int kIndexOffset = JSArray::kSize;
8066 static const int kInputOffset = kIndexOffset + kPointerSize;
8067 static const int kSize = kInputOffset + kPointerSize;
8068 // Indices of in-object properties.
8069 static const int kIndexIndex = 0;
8070 static const int kInputIndex = 1;
8072 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
8076 // An accessor must have a getter, but can have no setter.
8078 // When setting a property, V8 searches accessors in prototypes.
8079 // If an accessor was found and it does not have a setter,
8080 // the request is ignored.
8082 // If the accessor in the prototype has the READ_ONLY property attribute, then
8083 // a new value is added to the local object when the property is set.
8084 // This shadows the accessor in the prototype.
8085 class AccessorInfo: public Struct {
8087 DECL_ACCESSORS(getter, Object)
8088 DECL_ACCESSORS(setter, Object)
8089 DECL_ACCESSORS(data, Object)
8090 DECL_ACCESSORS(name, Object)
8091 DECL_ACCESSORS(flag, Smi)
8093 inline bool all_can_read();
8094 inline void set_all_can_read(bool value);
8096 inline bool all_can_write();
8097 inline void set_all_can_write(bool value);
8099 inline bool prohibits_overwriting();
8100 inline void set_prohibits_overwriting(bool value);
8102 inline PropertyAttributes property_attributes();
8103 inline void set_property_attributes(PropertyAttributes attributes);
8105 static inline AccessorInfo* cast(Object* obj);
8108 inline void AccessorInfoPrint() {
8109 AccessorInfoPrint(stdout);
8111 void AccessorInfoPrint(FILE* out);
8114 void AccessorInfoVerify();
8117 static const int kGetterOffset = HeapObject::kHeaderSize;
8118 static const int kSetterOffset = kGetterOffset + kPointerSize;
8119 static const int kDataOffset = kSetterOffset + kPointerSize;
8120 static const int kNameOffset = kDataOffset + kPointerSize;
8121 static const int kFlagOffset = kNameOffset + kPointerSize;
8122 static const int kSize = kFlagOffset + kPointerSize;
8125 // Bit positions in flag.
8126 static const int kAllCanReadBit = 0;
8127 static const int kAllCanWriteBit = 1;
8128 static const int kProhibitsOverwritingBit = 2;
8129 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
8131 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
8135 // Support for JavaScript accessors: A pair of a getter and a setter. Each
8136 // accessor can either be
8137 // * a pointer to a JavaScript function or proxy: a real accessor
8138 // * undefined: considered an accessor by the spec, too, strangely enough
8139 // * the hole: an accessor which has not been set
8140 // * a pointer to a map: a transition used to ensure map sharing
8141 class AccessorPair: public Struct {
8143 DECL_ACCESSORS(getter, Object)
8144 DECL_ACCESSORS(setter, Object)
8146 static inline AccessorPair* cast(Object* obj);
8148 MUST_USE_RESULT MaybeObject* CopyWithoutTransitions();
8150 // Note: Returns undefined instead in case of a hole.
8151 Object* GetComponent(AccessorComponent component);
8153 // Set both components, skipping arguments which are a JavaScript null.
8154 void SetComponents(Object* getter, Object* setter) {
8155 if (!getter->IsNull()) set_getter(getter);
8156 if (!setter->IsNull()) set_setter(setter);
8159 bool ContainsAccessor() {
8160 return IsJSAccessor(getter()) || IsJSAccessor(setter());
8164 void AccessorPairPrint(FILE* out = stdout);
8167 void AccessorPairVerify();
8170 static const int kGetterOffset = HeapObject::kHeaderSize;
8171 static const int kSetterOffset = kGetterOffset + kPointerSize;
8172 static const int kSize = kSetterOffset + kPointerSize;
8175 // Strangely enough, in addition to functions and harmony proxies, the spec
8176 // requires us to consider undefined as a kind of accessor, too:
8178 // Object.defineProperty(obj, "foo", {get: undefined});
8179 // assertTrue("foo" in obj);
8180 bool IsJSAccessor(Object* obj) {
8181 return obj->IsSpecFunction() || obj->IsUndefined();
8184 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
8188 class AccessCheckInfo: public Struct {
8190 DECL_ACCESSORS(named_callback, Object)
8191 DECL_ACCESSORS(indexed_callback, Object)
8192 DECL_ACCESSORS(data, Object)
8194 static inline AccessCheckInfo* cast(Object* obj);
8197 inline void AccessCheckInfoPrint() {
8198 AccessCheckInfoPrint(stdout);
8200 void AccessCheckInfoPrint(FILE* out);
8203 void AccessCheckInfoVerify();
8206 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
8207 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
8208 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
8209 static const int kSize = kDataOffset + kPointerSize;
8212 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
8216 class InterceptorInfo: public Struct {
8218 DECL_ACCESSORS(getter, Object)
8219 DECL_ACCESSORS(setter, Object)
8220 DECL_ACCESSORS(query, Object)
8221 DECL_ACCESSORS(deleter, Object)
8222 DECL_ACCESSORS(enumerator, Object)
8223 DECL_ACCESSORS(data, Object)
8224 DECL_ACCESSORS(is_fallback, Smi)
8226 static inline InterceptorInfo* cast(Object* obj);
8229 inline void InterceptorInfoPrint() {
8230 InterceptorInfoPrint(stdout);
8232 void InterceptorInfoPrint(FILE* out);
8235 void InterceptorInfoVerify();
8238 static const int kGetterOffset = HeapObject::kHeaderSize;
8239 static const int kSetterOffset = kGetterOffset + kPointerSize;
8240 static const int kQueryOffset = kSetterOffset + kPointerSize;
8241 static const int kDeleterOffset = kQueryOffset + kPointerSize;
8242 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
8243 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
8244 static const int kFallbackOffset = kDataOffset + kPointerSize;
8245 static const int kSize = kFallbackOffset + kPointerSize;
8248 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
8252 class CallHandlerInfo: public Struct {
8254 DECL_ACCESSORS(callback, Object)
8255 DECL_ACCESSORS(data, Object)
8257 static inline CallHandlerInfo* cast(Object* obj);
8260 inline void CallHandlerInfoPrint() {
8261 CallHandlerInfoPrint(stdout);
8263 void CallHandlerInfoPrint(FILE* out);
8266 void CallHandlerInfoVerify();
8269 static const int kCallbackOffset = HeapObject::kHeaderSize;
8270 static const int kDataOffset = kCallbackOffset + kPointerSize;
8271 static const int kSize = kDataOffset + kPointerSize;
8274 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
8278 class TemplateInfo: public Struct {
8280 DECL_ACCESSORS(tag, Object)
8281 DECL_ACCESSORS(property_list, Object)
8284 void TemplateInfoVerify();
8287 static const int kTagOffset = HeapObject::kHeaderSize;
8288 static const int kPropertyListOffset = kTagOffset + kPointerSize;
8289 static const int kHeaderSize = kPropertyListOffset + kPointerSize;
8292 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
8296 class FunctionTemplateInfo: public TemplateInfo {
8298 DECL_ACCESSORS(serial_number, Object)
8299 DECL_ACCESSORS(call_code, Object)
8300 DECL_ACCESSORS(property_accessors, Object)
8301 DECL_ACCESSORS(prototype_template, Object)
8302 DECL_ACCESSORS(parent_template, Object)
8303 DECL_ACCESSORS(named_property_handler, Object)
8304 DECL_ACCESSORS(indexed_property_handler, Object)
8305 DECL_ACCESSORS(instance_template, Object)
8306 DECL_ACCESSORS(class_name, Object)
8307 DECL_ACCESSORS(signature, Object)
8308 DECL_ACCESSORS(instance_call_handler, Object)
8309 DECL_ACCESSORS(access_check_info, Object)
8310 DECL_ACCESSORS(flag, Smi)
8312 // Following properties use flag bits.
8313 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
8314 DECL_BOOLEAN_ACCESSORS(undetectable)
8315 // If the bit is set, object instances created by this function
8316 // requires access check.
8317 DECL_BOOLEAN_ACCESSORS(needs_access_check)
8318 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
8320 static inline FunctionTemplateInfo* cast(Object* obj);
8323 inline void FunctionTemplateInfoPrint() {
8324 FunctionTemplateInfoPrint(stdout);
8326 void FunctionTemplateInfoPrint(FILE* out);
8329 void FunctionTemplateInfoVerify();
8332 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
8333 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
8334 static const int kPropertyAccessorsOffset = kCallCodeOffset + kPointerSize;
8335 static const int kPrototypeTemplateOffset =
8336 kPropertyAccessorsOffset + kPointerSize;
8337 static const int kParentTemplateOffset =
8338 kPrototypeTemplateOffset + kPointerSize;
8339 static const int kNamedPropertyHandlerOffset =
8340 kParentTemplateOffset + kPointerSize;
8341 static const int kIndexedPropertyHandlerOffset =
8342 kNamedPropertyHandlerOffset + kPointerSize;
8343 static const int kInstanceTemplateOffset =
8344 kIndexedPropertyHandlerOffset + kPointerSize;
8345 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
8346 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
8347 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
8348 static const int kAccessCheckInfoOffset =
8349 kInstanceCallHandlerOffset + kPointerSize;
8350 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
8351 static const int kSize = kFlagOffset + kPointerSize;
8354 // Bit position in the flag, from least significant bit position.
8355 static const int kHiddenPrototypeBit = 0;
8356 static const int kUndetectableBit = 1;
8357 static const int kNeedsAccessCheckBit = 2;
8358 static const int kReadOnlyPrototypeBit = 3;
8360 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
8364 class ObjectTemplateInfo: public TemplateInfo {
8366 DECL_ACCESSORS(constructor, Object)
8367 DECL_ACCESSORS(internal_field_count, Object)
8368 DECL_ACCESSORS(has_external_resource, Object)
8370 static inline ObjectTemplateInfo* cast(Object* obj);
8373 inline void ObjectTemplateInfoPrint() {
8374 ObjectTemplateInfoPrint(stdout);
8376 void ObjectTemplateInfoPrint(FILE* out);
8379 void ObjectTemplateInfoVerify();
8382 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
8383 static const int kInternalFieldCountOffset =
8384 kConstructorOffset + kPointerSize;
8385 static const int kHasExternalResourceOffset = kInternalFieldCountOffset + kPointerSize;
8386 static const int kSize = kHasExternalResourceOffset + kPointerSize;
8390 class SignatureInfo: public Struct {
8392 DECL_ACCESSORS(receiver, Object)
8393 DECL_ACCESSORS(args, Object)
8395 static inline SignatureInfo* cast(Object* obj);
8398 inline void SignatureInfoPrint() {
8399 SignatureInfoPrint(stdout);
8401 void SignatureInfoPrint(FILE* out);
8404 void SignatureInfoVerify();
8407 static const int kReceiverOffset = Struct::kHeaderSize;
8408 static const int kArgsOffset = kReceiverOffset + kPointerSize;
8409 static const int kSize = kArgsOffset + kPointerSize;
8412 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
8416 class TypeSwitchInfo: public Struct {
8418 DECL_ACCESSORS(types, Object)
8420 static inline TypeSwitchInfo* cast(Object* obj);
8423 inline void TypeSwitchInfoPrint() {
8424 TypeSwitchInfoPrint(stdout);
8426 void TypeSwitchInfoPrint(FILE* out);
8429 void TypeSwitchInfoVerify();
8432 static const int kTypesOffset = Struct::kHeaderSize;
8433 static const int kSize = kTypesOffset + kPointerSize;
8437 #ifdef ENABLE_DEBUGGER_SUPPORT
8438 // The DebugInfo class holds additional information for a function being
8440 class DebugInfo: public Struct {
8442 // The shared function info for the source being debugged.
8443 DECL_ACCESSORS(shared, SharedFunctionInfo)
8444 // Code object for the original code.
8445 DECL_ACCESSORS(original_code, Code)
8446 // Code object for the patched code. This code object is the code object
8447 // currently active for the function.
8448 DECL_ACCESSORS(code, Code)
8449 // Fixed array holding status information for each active break point.
8450 DECL_ACCESSORS(break_points, FixedArray)
8452 // Check if there is a break point at a code position.
8453 bool HasBreakPoint(int code_position);
8454 // Get the break point info object for a code position.
8455 Object* GetBreakPointInfo(int code_position);
8456 // Clear a break point.
8457 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
8459 Handle<Object> break_point_object);
8460 // Set a break point.
8461 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
8462 int source_position, int statement_position,
8463 Handle<Object> break_point_object);
8464 // Get the break point objects for a code position.
8465 Object* GetBreakPointObjects(int code_position);
8466 // Find the break point info holding this break point object.
8467 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
8468 Handle<Object> break_point_object);
8469 // Get the number of break points for this function.
8470 int GetBreakPointCount();
8472 static inline DebugInfo* cast(Object* obj);
8475 inline void DebugInfoPrint() {
8476 DebugInfoPrint(stdout);
8478 void DebugInfoPrint(FILE* out);
8481 void DebugInfoVerify();
8484 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
8485 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
8486 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
8487 static const int kActiveBreakPointsCountIndex =
8488 kPatchedCodeIndex + kPointerSize;
8489 static const int kBreakPointsStateIndex =
8490 kActiveBreakPointsCountIndex + kPointerSize;
8491 static const int kSize = kBreakPointsStateIndex + kPointerSize;
8494 static const int kNoBreakPointInfo = -1;
8496 // Lookup the index in the break_points array for a code position.
8497 int GetBreakPointInfoIndex(int code_position);
8499 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
8503 // The BreakPointInfo class holds information for break points set in a
8504 // function. The DebugInfo object holds a BreakPointInfo object for each code
8505 // position with one or more break points.
8506 class BreakPointInfo: public Struct {
8508 // The position in the code for the break point.
8509 DECL_ACCESSORS(code_position, Smi)
8510 // The position in the source for the break position.
8511 DECL_ACCESSORS(source_position, Smi)
8512 // The position in the source for the last statement before this break
8514 DECL_ACCESSORS(statement_position, Smi)
8515 // List of related JavaScript break points.
8516 DECL_ACCESSORS(break_point_objects, Object)
8518 // Removes a break point.
8519 static void ClearBreakPoint(Handle<BreakPointInfo> info,
8520 Handle<Object> break_point_object);
8521 // Set a break point.
8522 static void SetBreakPoint(Handle<BreakPointInfo> info,
8523 Handle<Object> break_point_object);
8524 // Check if break point info has this break point object.
8525 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
8526 Handle<Object> break_point_object);
8527 // Get the number of break points for this code position.
8528 int GetBreakPointCount();
8530 static inline BreakPointInfo* cast(Object* obj);
8533 inline void BreakPointInfoPrint() {
8534 BreakPointInfoPrint(stdout);
8536 void BreakPointInfoPrint(FILE* out);
8539 void BreakPointInfoVerify();
8542 static const int kCodePositionIndex = Struct::kHeaderSize;
8543 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
8544 static const int kStatementPositionIndex =
8545 kSourcePositionIndex + kPointerSize;
8546 static const int kBreakPointObjectsIndex =
8547 kStatementPositionIndex + kPointerSize;
8548 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
8551 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
8553 #endif // ENABLE_DEBUGGER_SUPPORT
8556 #undef DECL_BOOLEAN_ACCESSORS
8557 #undef DECL_ACCESSORS
8559 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
8560 V(kSymbolTable, "symbol_table", "(Symbols)") \
8561 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
8562 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
8563 V(kSymbol, "symbol", "(Symbol)") \
8564 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
8565 V(kTop, "top", "(Isolate)") \
8566 V(kRelocatable, "relocatable", "(Relocatable)") \
8567 V(kDebug, "debug", "(Debugger)") \
8568 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
8569 V(kHandleScope, "handlescope", "(Handle scope)") \
8570 V(kBuiltins, "builtins", "(Builtins)") \
8571 V(kGlobalHandles, "globalhandles", "(Global handles)") \
8572 V(kThreadManager, "threadmanager", "(Thread manager)") \
8573 V(kExtensions, "Extensions", "(Extensions)")
8575 class VisitorSynchronization : public AllStatic {
8577 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
8579 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
8584 static const char* const kTags[kNumberOfSyncTags];
8585 static const char* const kTagNames[kNumberOfSyncTags];
8588 // Abstract base class for visiting, and optionally modifying, the
8589 // pointers contained in Objects. Used in GC and serialization/deserialization.
8590 class ObjectVisitor BASE_EMBEDDED {
8592 virtual ~ObjectVisitor() {}
8594 // Visits a contiguous arrays of pointers in the half-open range
8595 // [start, end). Any or all of the values may be modified on return.
8596 virtual void VisitPointers(Object** start, Object** end) = 0;
8598 // To allow lazy clearing of inline caches the visitor has
8599 // a rich interface for iterating over Code objects..
8601 // Visits a code target in the instruction stream.
8602 virtual void VisitCodeTarget(RelocInfo* rinfo);
8604 // Visits a code entry in a JS function.
8605 virtual void VisitCodeEntry(Address entry_address);
8607 // Visits a global property cell reference in the instruction stream.
8608 virtual void VisitGlobalPropertyCell(RelocInfo* rinfo);
8610 // Visits a runtime entry in the instruction stream.
8611 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
8613 // Visits the resource of an ASCII or two-byte string.
8614 virtual void VisitExternalAsciiString(
8615 v8::String::ExternalAsciiStringResource** resource) {}
8616 virtual void VisitExternalTwoByteString(
8617 v8::String::ExternalStringResource** resource) {}
8619 // Visits a debug call target in the instruction stream.
8620 virtual void VisitDebugTarget(RelocInfo* rinfo);
8622 // Handy shorthand for visiting a single pointer.
8623 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
8625 // Visit pointer embedded into a code object.
8626 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
8628 virtual void VisitSharedFunctionInfo(SharedFunctionInfo* shared) {}
8630 // Visits a contiguous arrays of external references (references to the C++
8631 // heap) in the half-open range [start, end). Any or all of the values
8632 // may be modified on return.
8633 virtual void VisitExternalReferences(Address* start, Address* end) {}
8635 virtual void VisitExternalReference(RelocInfo* rinfo);
8637 inline void VisitExternalReference(Address* p) {
8638 VisitExternalReferences(p, p + 1);
8641 // Visits a handle that has an embedder-assigned class ID.
8642 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
8644 // Intended for serialization/deserialization checking: insert, or
8645 // check for the presence of, a tag at this position in the stream.
8646 // Also used for marking up GC roots in heap snapshots.
8647 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
8651 class StructBodyDescriptor : public
8652 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
8654 static inline int SizeOf(Map* map, HeapObject* object) {
8655 return map->instance_size();
8660 // BooleanBit is a helper class for setting and getting a bit in an
8662 class BooleanBit : public AllStatic {
8664 static inline bool get(Smi* smi, int bit_position) {
8665 return get(smi->value(), bit_position);
8668 static inline bool get(int value, int bit_position) {
8669 return (value & (1 << bit_position)) != 0;
8672 static inline Smi* set(Smi* smi, int bit_position, bool v) {
8673 return Smi::FromInt(set(smi->value(), bit_position, v));
8676 static inline int set(int value, int bit_position, bool v) {
8678 value |= (1 << bit_position);
8680 value &= ~(1 << bit_position);
8686 } } // namespace v8::internal
8688 #endif // V8_OBJECTS_H_