1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_TO_OBJECT,
162 STORE_TRANSITION_TO_DOUBLE,
163 STORE_AND_GROW_NO_TRANSITION,
164 STORE_AND_GROW_TRANSITION_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
166 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
167 STORE_NO_TRANSITION_HANDLE_COW
171 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
180 enum ExternalArrayType {
181 kExternalInt8Array = 1,
184 kExternalUint16Array,
186 kExternalUint32Array,
187 kExternalFloat32Array,
188 kExternalFloat64Array,
189 kExternalUint8ClampedArray,
193 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
194 return store_mode == STORE_TRANSITION_TO_OBJECT ||
195 store_mode == STORE_TRANSITION_TO_DOUBLE ||
196 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
197 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
201 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
202 KeyedAccessStoreMode store_mode) {
203 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
206 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
207 return STORE_AND_GROW_NO_TRANSITION;
209 return STANDARD_STORE;
213 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
214 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
215 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
219 enum IcCheckType { ELEMENT, PROPERTY };
222 // SKIP_WRITE_BARRIER skips the write barrier.
223 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
224 // only performs the generational part.
225 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
226 enum WriteBarrierMode {
228 UPDATE_WEAK_WRITE_BARRIER,
233 // Indicates whether a value can be loaded as a constant.
234 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
237 // PropertyNormalizationMode is used to specify whether to keep
238 // inobject properties when normalizing properties of a JSObject.
239 enum PropertyNormalizationMode {
240 CLEAR_INOBJECT_PROPERTIES,
241 KEEP_INOBJECT_PROPERTIES
245 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
246 // will give the fastest result by tailoring the map to the prototype, but that
247 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
248 // (at least for now) when dynamically modifying the prototype chain of an
249 // object using __proto__ or Object.setPrototypeOf.
250 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
253 // Indicates whether transitions can be added to a source map or not.
254 enum TransitionFlag {
260 // Indicates whether the transition is simple: the target map of the transition
261 // either extends the current map with a new property, or it modifies the
262 // property that was added last to the current map.
263 enum SimpleTransitionFlag {
264 SIMPLE_PROPERTY_TRANSITION,
270 // Indicates whether we are only interested in the descriptors of a particular
271 // map, or in all descriptors in the descriptor array.
272 enum DescriptorFlag {
277 // The GC maintains a bit of information, the MarkingParity, which toggles
278 // from odd to even and back every time marking is completed. Incremental
279 // marking can visit an object twice during a marking phase, so algorithms that
280 // that piggy-back on marking can use the parity to ensure that they only
281 // perform an operation on an object once per marking phase: they record the
282 // MarkingParity when they visit an object, and only re-visit the object when it
283 // is marked again and the MarkingParity changes.
290 // ICs store extra state in a Code object. The default extra state is
292 typedef int ExtraICState;
293 static const ExtraICState kNoExtraICState = 0;
295 // Instance size sentinel for objects of variable size.
296 const int kVariableSizeSentinel = 0;
298 // We may store the unsigned bit field as signed Smi value and do not
300 const int kStubMajorKeyBits = 7;
301 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
303 // All Maps have a field instance_type containing a InstanceType.
304 // It describes the type of the instances.
306 // As an example, a JavaScript object is a heap object and its map
307 // instance_type is JS_OBJECT_TYPE.
309 // The names of the string instance types are intended to systematically
310 // mirror their encoding in the instance_type field of the map. The default
311 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
312 // encoding is mentioned explicitly in the name. Likewise, the default
313 // representation is considered sequential. It is not mentioned in the
314 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
315 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
316 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
318 // NOTE: The following things are some that depend on the string types having
319 // instance_types that are less than those of all other types:
320 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
323 // NOTE: Everything following JS_VALUE_TYPE is considered a
324 // JSObject for GC purposes. The first four entries here have typeof
325 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
326 #define INSTANCE_TYPE_LIST(V) \
328 V(ONE_BYTE_STRING_TYPE) \
329 V(CONS_STRING_TYPE) \
330 V(CONS_ONE_BYTE_STRING_TYPE) \
331 V(SLICED_STRING_TYPE) \
332 V(SLICED_ONE_BYTE_STRING_TYPE) \
333 V(EXTERNAL_STRING_TYPE) \
334 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
335 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
336 V(SHORT_EXTERNAL_STRING_TYPE) \
337 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
338 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
340 V(INTERNALIZED_STRING_TYPE) \
341 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
342 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
343 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
344 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
345 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
346 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
347 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(SIMD128_VALUE_TYPE) \
356 V(PROPERTY_CELL_TYPE) \
358 V(HEAP_NUMBER_TYPE) \
359 V(MUTABLE_HEAP_NUMBER_TYPE) \
362 V(BYTECODE_ARRAY_TYPE) \
365 V(FIXED_INT8_ARRAY_TYPE) \
366 V(FIXED_UINT8_ARRAY_TYPE) \
367 V(FIXED_INT16_ARRAY_TYPE) \
368 V(FIXED_UINT16_ARRAY_TYPE) \
369 V(FIXED_INT32_ARRAY_TYPE) \
370 V(FIXED_UINT32_ARRAY_TYPE) \
371 V(FIXED_FLOAT32_ARRAY_TYPE) \
372 V(FIXED_FLOAT64_ARRAY_TYPE) \
373 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
377 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
378 V(DECLARED_ACCESSOR_INFO_TYPE) \
379 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
380 V(ACCESSOR_PAIR_TYPE) \
381 V(ACCESS_CHECK_INFO_TYPE) \
382 V(INTERCEPTOR_INFO_TYPE) \
383 V(CALL_HANDLER_INFO_TYPE) \
384 V(FUNCTION_TEMPLATE_INFO_TYPE) \
385 V(OBJECT_TEMPLATE_INFO_TYPE) \
386 V(SIGNATURE_INFO_TYPE) \
387 V(TYPE_SWITCH_INFO_TYPE) \
388 V(ALLOCATION_MEMENTO_TYPE) \
389 V(ALLOCATION_SITE_TYPE) \
392 V(POLYMORPHIC_CODE_CACHE_TYPE) \
393 V(TYPE_FEEDBACK_INFO_TYPE) \
394 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
396 V(PROTOTYPE_INFO_TYPE) \
397 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
399 V(FIXED_ARRAY_TYPE) \
400 V(FIXED_DOUBLE_ARRAY_TYPE) \
401 V(SHARED_FUNCTION_INFO_TYPE) \
404 V(JS_MESSAGE_OBJECT_TYPE) \
409 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
410 V(JS_GENERATOR_OBJECT_TYPE) \
412 V(JS_GLOBAL_OBJECT_TYPE) \
413 V(JS_BUILTINS_OBJECT_TYPE) \
414 V(JS_GLOBAL_PROXY_TYPE) \
416 V(JS_ARRAY_BUFFER_TYPE) \
417 V(JS_TYPED_ARRAY_TYPE) \
418 V(JS_DATA_VIEW_TYPE) \
422 V(JS_SET_ITERATOR_TYPE) \
423 V(JS_MAP_ITERATOR_TYPE) \
424 V(JS_WEAK_MAP_TYPE) \
425 V(JS_WEAK_SET_TYPE) \
428 V(JS_FUNCTION_TYPE) \
429 V(JS_FUNCTION_PROXY_TYPE) \
431 V(BREAK_POINT_INFO_TYPE)
434 // Since string types are not consecutive, this macro is used to
435 // iterate over them.
436 #define STRING_TYPE_LIST(V) \
437 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
438 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
440 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
441 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
443 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
444 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
445 SlicedOneByteString) \
446 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
448 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
449 external_one_byte_string, ExternalOneByteString) \
450 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
451 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
452 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
453 short_external_string, ShortExternalString) \
454 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
455 short_external_one_byte_string, ShortExternalOneByteString) \
456 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
457 ExternalTwoByteString::kShortSize, \
458 short_external_string_with_one_byte_data, \
459 ShortExternalStringWithOneByteData) \
461 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
462 InternalizedString) \
463 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
464 one_byte_internalized_string, OneByteInternalizedString) \
465 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
466 external_internalized_string, ExternalInternalizedString) \
467 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
468 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
469 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
470 ExternalTwoByteString::kSize, \
471 external_internalized_string_with_one_byte_data, \
472 ExternalInternalizedStringWithOneByteData) \
473 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
474 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
475 ShortExternalInternalizedString) \
476 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
477 ExternalOneByteString::kShortSize, \
478 short_external_one_byte_internalized_string, \
479 ShortExternalOneByteInternalizedString) \
480 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
481 ExternalTwoByteString::kShortSize, \
482 short_external_internalized_string_with_one_byte_data, \
483 ShortExternalInternalizedStringWithOneByteData)
485 // A struct is a simple object a set of object-valued fields. Including an
486 // object type in this causes the compiler to generate most of the boilerplate
487 // code for the class including allocation and garbage collection routines,
488 // casts and predicates. All you need to define is the class, methods and
489 // object verification routines. Easy, no?
491 // Note that for subtle reasons related to the ordering or numerical values of
492 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
494 #define STRUCT_LIST(V) \
496 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
497 executable_accessor_info) \
498 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
499 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
500 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
501 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
502 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
503 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
504 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
505 V(SCRIPT, Script, script) \
506 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
507 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
508 V(CODE_CACHE, CodeCache, code_cache) \
509 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
510 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
511 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
512 V(DEBUG_INFO, DebugInfo, debug_info) \
513 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
514 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
515 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
516 SloppyBlockWithEvalContextExtension, \
517 sloppy_block_with_eval_context_extension)
519 // We use the full 8 bits of the instance_type field to encode heap object
520 // instance types. The high-order bit (bit 7) is set if the object is not a
521 // string, and cleared if it is a string.
522 const uint32_t kIsNotStringMask = 0x80;
523 const uint32_t kStringTag = 0x0;
524 const uint32_t kNotStringTag = 0x80;
526 // Bit 6 indicates that the object is an internalized string (if set) or not.
527 // Bit 7 has to be clear as well.
528 const uint32_t kIsNotInternalizedMask = 0x40;
529 const uint32_t kNotInternalizedTag = 0x40;
530 const uint32_t kInternalizedTag = 0x0;
532 // If bit 7 is clear then bit 2 indicates whether the string consists of
533 // two-byte characters or one-byte characters.
534 const uint32_t kStringEncodingMask = 0x4;
535 const uint32_t kTwoByteStringTag = 0x0;
536 const uint32_t kOneByteStringTag = 0x4;
538 // If bit 7 is clear, the low-order 2 bits indicate the representation
540 const uint32_t kStringRepresentationMask = 0x03;
541 enum StringRepresentationTag {
543 kConsStringTag = 0x1,
544 kExternalStringTag = 0x2,
545 kSlicedStringTag = 0x3
547 const uint32_t kIsIndirectStringMask = 0x1;
548 const uint32_t kIsIndirectStringTag = 0x1;
549 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
550 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
551 STATIC_ASSERT((kConsStringTag &
552 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
553 STATIC_ASSERT((kSlicedStringTag &
554 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
556 // Use this mask to distinguish between cons and slice only after making
557 // sure that the string is one of the two (an indirect string).
558 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
559 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
561 // If bit 7 is clear, then bit 3 indicates whether this two-byte
562 // string actually contains one byte data.
563 const uint32_t kOneByteDataHintMask = 0x08;
564 const uint32_t kOneByteDataHintTag = 0x08;
566 // If bit 7 is clear and string representation indicates an external string,
567 // then bit 4 indicates whether the data pointer is cached.
568 const uint32_t kShortExternalStringMask = 0x10;
569 const uint32_t kShortExternalStringTag = 0x10;
572 // A ConsString with an empty string as the right side is a candidate
573 // for being shortcut by the garbage collector. We don't allocate any
574 // non-flat internalized strings, so we do not shortcut them thereby
575 // avoiding turning internalized strings into strings. The bit-masks
576 // below contain the internalized bit as additional safety.
577 // See heap.cc, mark-compact.cc and objects-visiting.cc.
578 const uint32_t kShortcutTypeMask =
580 kIsNotInternalizedMask |
581 kStringRepresentationMask;
582 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
584 static inline bool IsShortcutCandidate(int type) {
585 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
591 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
592 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
593 ONE_BYTE_INTERNALIZED_STRING_TYPE =
594 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
595 EXTERNAL_INTERNALIZED_STRING_TYPE =
596 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
597 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
598 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
599 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
600 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
602 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
603 kShortExternalStringTag |
605 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
606 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
608 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
609 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
610 kShortExternalStringTag | kInternalizedTag,
611 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
612 ONE_BYTE_STRING_TYPE =
613 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
614 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
615 CONS_ONE_BYTE_STRING_TYPE =
616 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
618 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
619 SLICED_ONE_BYTE_STRING_TYPE =
620 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
621 EXTERNAL_STRING_TYPE =
622 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 EXTERNAL_ONE_BYTE_STRING_TYPE =
624 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
626 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
628 SHORT_EXTERNAL_STRING_TYPE =
629 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
630 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
631 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
632 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
633 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
637 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
639 // Other primitives (cannot contain non-map-word pointers to heap objects).
642 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
644 // Objects allocated in their own spaces (never in new space).
648 // "Data", objects that cannot contain non-map-word pointers to heap
650 MUTABLE_HEAP_NUMBER_TYPE,
655 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
656 FIXED_UINT8_ARRAY_TYPE,
657 FIXED_INT16_ARRAY_TYPE,
658 FIXED_UINT16_ARRAY_TYPE,
659 FIXED_INT32_ARRAY_TYPE,
660 FIXED_UINT32_ARRAY_TYPE,
661 FIXED_FLOAT32_ARRAY_TYPE,
662 FIXED_FLOAT64_ARRAY_TYPE,
663 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
664 FIXED_DOUBLE_ARRAY_TYPE,
665 FILLER_TYPE, // LAST_DATA_TYPE
668 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
669 DECLARED_ACCESSOR_INFO_TYPE,
670 EXECUTABLE_ACCESSOR_INFO_TYPE,
672 ACCESS_CHECK_INFO_TYPE,
673 INTERCEPTOR_INFO_TYPE,
674 CALL_HANDLER_INFO_TYPE,
675 FUNCTION_TEMPLATE_INFO_TYPE,
676 OBJECT_TEMPLATE_INFO_TYPE,
678 TYPE_SWITCH_INFO_TYPE,
679 ALLOCATION_SITE_TYPE,
680 ALLOCATION_MEMENTO_TYPE,
683 POLYMORPHIC_CODE_CACHE_TYPE,
684 TYPE_FEEDBACK_INFO_TYPE,
685 ALIASED_ARGUMENTS_ENTRY_TYPE,
688 BREAK_POINT_INFO_TYPE,
690 SHARED_FUNCTION_INFO_TYPE,
695 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
697 // All the following types are subtypes of JSReceiver, which corresponds to
698 // objects in the JS sense. The first and the last type in this range are
699 // the two forms of function. This organization enables using the same
700 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
701 // NONCALLABLE_JS_OBJECT range.
702 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
703 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
704 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
705 JS_MESSAGE_OBJECT_TYPE,
708 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
709 JS_GENERATOR_OBJECT_TYPE,
711 JS_GLOBAL_OBJECT_TYPE,
712 JS_BUILTINS_OBJECT_TYPE,
713 JS_GLOBAL_PROXY_TYPE,
715 JS_ARRAY_BUFFER_TYPE,
720 JS_SET_ITERATOR_TYPE,
721 JS_MAP_ITERATOR_TYPE,
725 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
729 LAST_TYPE = JS_FUNCTION_TYPE,
730 FIRST_NAME_TYPE = FIRST_TYPE,
731 LAST_NAME_TYPE = SYMBOL_TYPE,
732 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
733 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
734 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
735 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
736 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
737 // Boundaries for testing for a fixed typed array.
738 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
739 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
740 // Boundary for promotion to old space.
741 LAST_DATA_TYPE = FILLER_TYPE,
742 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
743 // Note that there is no range for JSObject or JSProxy, since their subtypes
744 // are not continuous in this enum! The enum ranges instead reflect the
745 // external class names, where proxies are treated as either ordinary objects,
747 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
748 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
749 // Boundaries for testing the types represented as JSObject
750 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
751 LAST_JS_OBJECT_TYPE = LAST_TYPE,
752 // Boundaries for testing the types represented as JSProxy
753 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
754 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
755 // Boundaries for testing whether the type is a JavaScript object.
756 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
757 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
758 // Boundaries for testing the types for which typeof is "object".
759 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
760 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
761 // Note that the types for which typeof is "function" are not continuous.
762 // Define this so that we can put assertions on discrete checks.
763 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
766 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
767 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
768 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
769 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
772 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
773 V(FAST_ELEMENTS_SUB_TYPE) \
774 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
775 V(FAST_PROPERTIES_SUB_TYPE) \
776 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
777 V(MAP_CODE_CACHE_SUB_TYPE) \
778 V(SCOPE_INFO_SUB_TYPE) \
779 V(STRING_TABLE_SUB_TYPE) \
780 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
781 V(TRANSITION_ARRAY_SUB_TYPE)
783 enum FixedArraySubInstanceType {
784 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
785 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
786 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
787 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
800 #define DECL_BOOLEAN_ACCESSORS(name) \
801 inline bool name() const; \
802 inline void set_##name(bool value); \
805 #define DECL_ACCESSORS(name, type) \
806 inline type* name() const; \
807 inline void set_##name(type* value, \
808 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
811 #define DECLARE_CAST(type) \
812 INLINE(static type* cast(Object* object)); \
813 INLINE(static const type* cast(const Object* object));
817 class AllocationSite;
818 class AllocationSiteCreationContext;
819 class AllocationSiteUsageContext;
822 class ElementsAccessor;
823 class FixedArrayBase;
824 class FunctionLiteral;
826 class JSBuiltinsObject;
827 class LayoutDescriptor;
828 class LookupIterator;
829 class ObjectHashTable;
832 class SafepointEntry;
833 class SharedFunctionInfo;
835 class TypeFeedbackInfo;
836 class TypeFeedbackVector;
839 // We cannot just say "class HeapType;" if it is created from a template... =8-?
840 template<class> class TypeImpl;
841 struct HeapTypeConfig;
842 typedef TypeImpl<HeapTypeConfig> HeapType;
845 // A template-ized version of the IsXXX functions.
846 template <class C> inline bool Is(Object* obj);
849 #define DECLARE_VERIFIER(Name) void Name##Verify();
851 #define DECLARE_VERIFIER(Name)
855 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
857 #define DECLARE_PRINTER(Name)
861 #define OBJECT_TYPE_LIST(V) \
866 #define HEAP_OBJECT_TYPE_LIST(V) \
868 V(MutableHeapNumber) \
887 V(ExternalTwoByteString) \
888 V(ExternalOneByteString) \
889 V(SeqTwoByteString) \
890 V(SeqOneByteString) \
891 V(InternalizedString) \
894 V(FixedTypedArrayBase) \
897 V(FixedUint16Array) \
899 V(FixedUint32Array) \
901 V(FixedFloat32Array) \
902 V(FixedFloat64Array) \
903 V(FixedUint8ClampedArray) \
909 V(JSContextExtensionObject) \
910 V(JSGeneratorObject) \
912 V(LayoutDescriptor) \
916 V(TypeFeedbackVector) \
917 V(DeoptimizationInputData) \
918 V(DeoptimizationOutputData) \
922 V(FixedDoubleArray) \
926 V(ScriptContextTable) \
932 V(SharedFunctionInfo) \
941 V(JSArrayBufferView) \
950 V(JSWeakCollection) \
957 V(NormalizedMapCache) \
958 V(CompilationCacheTable) \
959 V(CodeCacheHashTable) \
960 V(PolymorphicCodeCacheHashTable) \
965 V(JSBuiltinsObject) \
967 V(UndetectableObject) \
968 V(AccessCheckNeeded) \
976 // Object is the abstract superclass for all classes in the
978 // Object does not use any virtual functions to avoid the
979 // allocation of the C++ vtable.
980 // Since both Smi and HeapObject are subclasses of Object no
981 // data members can be present in Object.
985 bool IsObject() const { return true; }
987 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
988 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
989 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
990 #undef IS_TYPE_FUNCTION_DECL
992 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
993 // a keyed store is of the form a[expression] = foo.
994 enum StoreFromKeyed {
995 MAY_BE_STORE_FROM_KEYED,
996 CERTAINLY_NOT_STORE_FROM_KEYED
999 INLINE(bool IsFixedArrayBase() const);
1000 INLINE(bool IsExternal() const);
1001 INLINE(bool IsAccessorInfo() const);
1003 INLINE(bool IsStruct() const);
1004 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1005 INLINE(bool Is##Name() const);
1006 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1007 #undef DECLARE_STRUCT_PREDICATE
1009 INLINE(bool IsSpecObject()) const;
1010 INLINE(bool IsSpecFunction()) const;
1011 INLINE(bool IsTemplateInfo()) const;
1012 INLINE(bool IsNameDictionary() const);
1013 INLINE(bool IsGlobalDictionary() const);
1014 INLINE(bool IsSeededNumberDictionary() const);
1015 INLINE(bool IsUnseededNumberDictionary() const);
1016 INLINE(bool IsOrderedHashSet() const);
1017 INLINE(bool IsOrderedHashMap() const);
1018 bool IsCallable() const;
1019 static bool IsPromise(Handle<Object> object);
1022 INLINE(bool IsUndefined() const);
1023 INLINE(bool IsNull() const);
1024 INLINE(bool IsTheHole() const);
1025 INLINE(bool IsException() const);
1026 INLINE(bool IsUninitialized() const);
1027 INLINE(bool IsTrue() const);
1028 INLINE(bool IsFalse() const);
1029 INLINE(bool IsArgumentsMarker() const);
1031 // Filler objects (fillers and free space objects).
1032 INLINE(bool IsFiller() const);
1034 // Extract the number.
1035 inline double Number();
1036 INLINE(bool IsNaN() const);
1037 INLINE(bool IsMinusZero() const);
1038 bool ToInt32(int32_t* value);
1039 bool ToUint32(uint32_t* value);
1041 inline Representation OptimalRepresentation();
1043 inline ElementsKind OptimalElementsKind();
1045 inline bool FitsRepresentation(Representation representation);
1047 // Checks whether two valid primitive encodings of a property name resolve to
1048 // the same logical property. E.g., the smi 1, the string "1" and the double
1049 // 1 all refer to the same property, so this helper will return true.
1050 inline bool KeyEquals(Object* other);
1052 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1054 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1055 Handle<Object> object,
1056 Representation representation);
1058 inline static Handle<Object> WrapForRead(Isolate* isolate,
1059 Handle<Object> object,
1060 Representation representation);
1062 // Returns true if the object is of the correct type to be used as a
1063 // implementation of a JSObject's elements.
1064 inline bool HasValidElements();
1066 inline bool HasSpecificClassOf(String* name);
1068 bool BooleanValue(); // ECMA-262 9.2.
1070 // ES6 section 7.2.13 Strict Equality Comparison
1071 bool StrictEquals(Object* that);
1073 // Convert to a JSObject if needed.
1074 // native_context is used when creating wrapper object.
1075 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1076 Handle<Object> object);
1077 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1078 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1080 // Convert to a Name if needed.
1081 MUST_USE_RESULT static MaybeHandle<Name> ToName(Isolate* isolate,
1082 Handle<Object> object);
1084 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1085 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1087 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1088 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1089 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1090 LanguageMode language_mode,
1091 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1093 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1094 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1095 StoreFromKeyed store_mode);
1097 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1098 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1099 StoreFromKeyed store_mode);
1101 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1102 LookupIterator* it, LanguageMode language_mode);
1103 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1104 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1105 LanguageMode language_mode);
1106 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1107 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1108 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1109 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1110 Handle<Object> value, LanguageMode language_mode);
1111 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1112 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1113 LanguageMode language_mode);
1114 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1115 LookupIterator* it, Handle<Object> value);
1116 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1117 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1118 LanguageMode language_mode, StoreFromKeyed store_mode);
1119 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1120 Handle<Object> object, Handle<Name> name,
1121 LanguageMode language_mode = SLOPPY);
1122 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1123 Isolate* isolate, Handle<Object> object, const char* key,
1124 LanguageMode language_mode = SLOPPY);
1125 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1126 Handle<Object> object, Handle<Name> name,
1127 LanguageMode language_mode = SLOPPY);
1129 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1130 LookupIterator* it, LanguageMode language_mode);
1131 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1132 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1135 Handle<Object> receiver,
1136 Handle<JSReceiver> getter);
1137 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1138 Handle<Object> receiver,
1139 Handle<JSReceiver> setter,
1140 Handle<Object> value);
1142 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1143 Isolate* isolate, Handle<Object> object, uint32_t index,
1144 LanguageMode language_mode = SLOPPY);
1146 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1147 Isolate* isolate, Handle<Object> object, uint32_t index,
1148 Handle<Object> value, LanguageMode language_mode);
1150 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1151 Isolate* isolate, Handle<Object> receiver);
1153 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1155 // Returns the permanent hash code associated with this object. May return
1156 // undefined if not yet created.
1159 // Returns undefined for JSObjects, but returns the hash code for simple
1160 // objects. This avoids a double lookup in the cases where we know we will
1161 // add the hash to the JSObject if it does not already exist.
1162 Object* GetSimpleHash();
1164 // Returns the permanent hash code associated with this object depending on
1165 // the actual object type. May create and store a hash code if needed and none
1167 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1169 // Checks whether this object has the same value as the given one. This
1170 // function is implemented according to ES5, section 9.12 and can be used
1171 // to implement the Harmony "egal" function.
1172 bool SameValue(Object* other);
1174 // Checks whether this object has the same value as the given one.
1175 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1176 // This function is implemented according to ES6, section 7.2.4 and is used
1177 // by ES6 Map and Set.
1178 bool SameValueZero(Object* other);
1180 // Tries to convert an object to an array length. Returns true and sets the
1181 // output parameter if it succeeds.
1182 inline bool ToArrayLength(uint32_t* index);
1184 // Tries to convert an object to an array index. Returns true and sets the
1185 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1186 // allow kMaxUInt32.
1187 inline bool ToArrayIndex(uint32_t* index);
1189 // Returns true if this is a JSValue containing a string and the index is
1190 // < the length of the string. Used to implement [] on strings.
1191 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1193 DECLARE_VERIFIER(Object)
1195 // Verify a pointer is a valid object pointer.
1196 static void VerifyPointer(Object* p);
1199 inline void VerifyApiCallResultType();
1201 // Prints this object without details.
1202 void ShortPrint(FILE* out = stdout);
1204 // Prints this object without details to a message accumulator.
1205 void ShortPrint(StringStream* accumulator);
1207 void ShortPrint(std::ostream& os); // NOLINT
1209 DECLARE_CAST(Object)
1211 // Layout description.
1212 static const int kHeaderSize = 0; // Object does not take up any space.
1215 // For our gdb macros, we should perhaps change these in the future.
1218 // Prints this object with details.
1219 void Print(std::ostream& os); // NOLINT
1221 void Print() { ShortPrint(); }
1222 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1226 friend class LookupIterator;
1227 friend class PrototypeIterator;
1229 // Return the map of the root of object's prototype chain.
1230 Map* GetRootMap(Isolate* isolate);
1232 // Helper for SetProperty and SetSuperProperty.
1233 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1234 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1235 StoreFromKeyed store_mode, bool* found);
1237 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1241 // In objects.h to be usable without objects-inl.h inclusion.
1242 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1243 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1247 explicit Brief(const Object* const v) : value(v) {}
1248 const Object* value;
1252 std::ostream& operator<<(std::ostream& os, const Brief& v);
1255 // Smi represents integer Numbers that can be stored in 31 bits.
1256 // Smis are immediate which means they are NOT allocated in the heap.
1257 // The this pointer has the following format: [31 bit signed int] 0
1258 // For long smis it has the following format:
1259 // [32 bit signed int] [31 bits zero padding] 0
1260 // Smi stands for small integer.
1261 class Smi: public Object {
1263 // Returns the integer value.
1264 inline int value() const { return Internals::SmiValue(this); }
1266 // Convert a value to a Smi object.
1267 static inline Smi* FromInt(int value) {
1268 DCHECK(Smi::IsValid(value));
1269 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1272 static inline Smi* FromIntptr(intptr_t value) {
1273 DCHECK(Smi::IsValid(value));
1274 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1275 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1278 // Returns whether value can be represented in a Smi.
1279 static inline bool IsValid(intptr_t value) {
1280 bool result = Internals::IsValidSmi(value);
1281 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1287 // Dispatched behavior.
1288 void SmiPrint(std::ostream& os) const; // NOLINT
1289 DECLARE_VERIFIER(Smi)
1291 static const int kMinValue =
1292 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1293 static const int kMaxValue = -(kMinValue + 1);
1296 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1300 // Heap objects typically have a map pointer in their first word. However,
1301 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1302 // encoded in the first word. The class MapWord is an abstraction of the
1303 // value in a heap object's first word.
1304 class MapWord BASE_EMBEDDED {
1306 // Normal state: the map word contains a map pointer.
1308 // Create a map word from a map pointer.
1309 static inline MapWord FromMap(const Map* map);
1311 // View this map word as a map pointer.
1312 inline Map* ToMap();
1315 // Scavenge collection: the map word of live objects in the from space
1316 // contains a forwarding address (a heap object pointer in the to space).
1318 // True if this map word is a forwarding address for a scavenge
1319 // collection. Only valid during a scavenge collection (specifically,
1320 // when all map words are heap object pointers, i.e. not during a full GC).
1321 inline bool IsForwardingAddress();
1323 // Create a map word from a forwarding address.
1324 static inline MapWord FromForwardingAddress(HeapObject* object);
1326 // View this map word as a forwarding address.
1327 inline HeapObject* ToForwardingAddress();
1329 static inline MapWord FromRawValue(uintptr_t value) {
1330 return MapWord(value);
1333 inline uintptr_t ToRawValue() {
1338 // HeapObject calls the private constructor and directly reads the value.
1339 friend class HeapObject;
1341 explicit MapWord(uintptr_t value) : value_(value) {}
1347 // The content of an heap object (except for the map pointer). kTaggedValues
1348 // objects can contain both heap pointers and Smis, kMixedValues can contain
1349 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1350 // objects can contain raw values and Smis.
1351 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1354 // HeapObject is the superclass for all classes describing heap allocated
1356 class HeapObject: public Object {
1358 // [map]: Contains a map which contains the object's reflective
1360 inline Map* map() const;
1361 inline void set_map(Map* value);
1362 // The no-write-barrier version. This is OK if the object is white and in
1363 // new space, or if the value is an immortal immutable object, like the maps
1364 // of primitive (non-JS) objects like strings, heap numbers etc.
1365 inline void set_map_no_write_barrier(Map* value);
1367 // Get the map using acquire load.
1368 inline Map* synchronized_map();
1369 inline MapWord synchronized_map_word() const;
1371 // Set the map using release store
1372 inline void synchronized_set_map(Map* value);
1373 inline void synchronized_set_map_no_write_barrier(Map* value);
1374 inline void synchronized_set_map_word(MapWord map_word);
1376 // During garbage collection, the map word of a heap object does not
1377 // necessarily contain a map pointer.
1378 inline MapWord map_word() const;
1379 inline void set_map_word(MapWord map_word);
1381 // The Heap the object was allocated in. Used also to access Isolate.
1382 inline Heap* GetHeap() const;
1384 // Convenience method to get current isolate.
1385 inline Isolate* GetIsolate() const;
1387 // Converts an address to a HeapObject pointer.
1388 static inline HeapObject* FromAddress(Address address) {
1389 DCHECK_TAG_ALIGNED(address);
1390 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1393 // Returns the address of this HeapObject.
1394 inline Address address() {
1395 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1398 // Iterates over pointers contained in the object (including the Map)
1399 void Iterate(ObjectVisitor* v);
1401 // Iterates over all pointers contained in the object except the
1402 // first map pointer. The object type is given in the first
1403 // parameter. This function does not access the map pointer in the
1404 // object, and so is safe to call while the map pointer is modified.
1405 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1407 // Returns the heap object's size in bytes
1410 // Indicates what type of values this heap object may contain.
1411 inline HeapObjectContents ContentType();
1413 // Given a heap object's map pointer, returns the heap size in bytes
1414 // Useful when the map pointer field is used for other purposes.
1416 inline int SizeFromMap(Map* map);
1418 // Returns the field at offset in obj, as a read/write Object* reference.
1419 // Does no checking, and is safe to use during GC, while maps are invalid.
1420 // Does not invoke write barrier, so should only be assigned to
1421 // during marking GC.
1422 static inline Object** RawField(HeapObject* obj, int offset);
1424 // Adds the |code| object related to |name| to the code cache of this map. If
1425 // this map is a dictionary map that is shared, the map copied and installed
1427 static void UpdateMapCodeCache(Handle<HeapObject> object,
1431 DECLARE_CAST(HeapObject)
1433 // Return the write barrier mode for this. Callers of this function
1434 // must be able to present a reference to an DisallowHeapAllocation
1435 // object as a sign that they are not going to use this function
1436 // from code that allocates and thus invalidates the returned write
1438 inline WriteBarrierMode GetWriteBarrierMode(
1439 const DisallowHeapAllocation& promise);
1441 // Dispatched behavior.
1442 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1444 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1446 DECLARE_PRINTER(HeapObject)
1447 DECLARE_VERIFIER(HeapObject)
1449 inline void VerifyObjectField(int offset);
1450 inline void VerifySmiField(int offset);
1452 // Verify a pointer is a valid HeapObject pointer that points to object
1453 // areas in the heap.
1454 static void VerifyHeapPointer(Object* p);
1457 inline AllocationAlignment RequiredAlignment();
1459 // Layout description.
1460 // First field in a heap object is map.
1461 static const int kMapOffset = Object::kHeaderSize;
1462 static const int kHeaderSize = kMapOffset + kPointerSize;
1464 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1467 // helpers for calling an ObjectVisitor to iterate over pointers in the
1468 // half-open range [start, end) specified as integer offsets
1469 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1470 // as above, for the single element at "offset"
1471 inline void IteratePointer(ObjectVisitor* v, int offset);
1472 // as above, for the next code link of a code object.
1473 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1476 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1480 // This class describes a body of an object of a fixed size
1481 // in which all pointer fields are located in the [start_offset, end_offset)
1483 template<int start_offset, int end_offset, int size>
1484 class FixedBodyDescriptor {
1486 static const int kStartOffset = start_offset;
1487 static const int kEndOffset = end_offset;
1488 static const int kSize = size;
1490 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1492 template<typename StaticVisitor>
1493 static inline void IterateBody(HeapObject* obj) {
1494 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1495 HeapObject::RawField(obj, end_offset));
1500 // This class describes a body of an object of a variable size
1501 // in which all pointer fields are located in the [start_offset, object_size)
1503 template<int start_offset>
1504 class FlexibleBodyDescriptor {
1506 static const int kStartOffset = start_offset;
1508 static inline void IterateBody(HeapObject* obj,
1512 template<typename StaticVisitor>
1513 static inline void IterateBody(HeapObject* obj, int object_size) {
1514 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1515 HeapObject::RawField(obj, object_size));
1520 // The HeapNumber class describes heap allocated numbers that cannot be
1521 // represented in a Smi (small integer)
1522 class HeapNumber: public HeapObject {
1524 // [value]: number value.
1525 inline double value() const;
1526 inline void set_value(double value);
1528 DECLARE_CAST(HeapNumber)
1530 // Dispatched behavior.
1531 bool HeapNumberBooleanValue();
1533 void HeapNumberPrint(std::ostream& os); // NOLINT
1534 DECLARE_VERIFIER(HeapNumber)
1536 inline int get_exponent();
1537 inline int get_sign();
1539 // Layout description.
1540 static const int kValueOffset = HeapObject::kHeaderSize;
1541 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1542 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1543 // words within double numbers are endian dependent and they are set
1545 #if defined(V8_TARGET_LITTLE_ENDIAN)
1546 static const int kMantissaOffset = kValueOffset;
1547 static const int kExponentOffset = kValueOffset + 4;
1548 #elif defined(V8_TARGET_BIG_ENDIAN)
1549 static const int kMantissaOffset = kValueOffset + 4;
1550 static const int kExponentOffset = kValueOffset;
1552 #error Unknown byte ordering
1555 static const int kSize = kValueOffset + kDoubleSize;
1556 static const uint32_t kSignMask = 0x80000000u;
1557 static const uint32_t kExponentMask = 0x7ff00000u;
1558 static const uint32_t kMantissaMask = 0xfffffu;
1559 static const int kMantissaBits = 52;
1560 static const int kExponentBits = 11;
1561 static const int kExponentBias = 1023;
1562 static const int kExponentShift = 20;
1563 static const int kInfinityOrNanExponent =
1564 (kExponentMask >> kExponentShift) - kExponentBias;
1565 static const int kMantissaBitsInTopWord = 20;
1566 static const int kNonMantissaBitsInTopWord = 12;
1569 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1573 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1574 class Simd128Value : public HeapObject {
1576 DECLARE_CAST(Simd128Value)
1578 DECLARE_PRINTER(Simd128Value)
1579 DECLARE_VERIFIER(Simd128Value)
1581 // Equality operations.
1582 inline bool Equals(Simd128Value* that);
1584 // Checks that another instance is bit-wise equal.
1585 bool BitwiseEquals(const Simd128Value* other) const;
1586 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1587 uint32_t Hash() const;
1588 // Copies the 16 bytes of SIMD data to the destination address.
1589 void CopyBits(void* destination) const;
1591 // Layout description.
1592 static const int kValueOffset = HeapObject::kHeaderSize;
1593 static const int kSize = kValueOffset + kSimd128Size;
1596 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1600 // V has parameters (TYPE, Type, type, lane count, lane type)
1601 #define SIMD128_TYPES(V) \
1602 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1603 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1604 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1605 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1606 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1607 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1608 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1609 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1610 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1611 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1613 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1614 class Type final : public Simd128Value { \
1616 inline lane_type get_lane(int lane) const; \
1617 inline void set_lane(int lane, lane_type value); \
1619 DECLARE_CAST(Type) \
1621 DECLARE_PRINTER(Type) \
1623 inline bool Equals(Type* that); \
1626 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1628 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1629 #undef SIMD128_VALUE_CLASS
1632 enum EnsureElementsMode {
1633 DONT_ALLOW_DOUBLE_ELEMENTS,
1634 ALLOW_COPIED_DOUBLE_ELEMENTS,
1635 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1639 // Indicator for one component of an AccessorPair.
1640 enum AccessorComponent {
1646 // JSReceiver includes types on which properties can be defined, i.e.,
1647 // JSObject and JSProxy.
1648 class JSReceiver: public HeapObject {
1650 DECLARE_CAST(JSReceiver)
1652 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1653 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1654 Handle<JSReceiver> object, Handle<Name> name);
1655 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1657 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1658 Handle<JSReceiver> object, uint32_t index);
1659 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1660 Handle<JSReceiver> object, uint32_t index);
1662 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1663 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1664 Handle<JSReceiver> object, Handle<Name> name,
1665 LanguageMode language_mode = SLOPPY);
1666 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1667 Handle<JSReceiver> object, Handle<Name> name,
1668 LanguageMode language_mode = SLOPPY);
1669 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1670 LookupIterator* it, LanguageMode language_mode);
1671 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1672 Handle<JSReceiver> object, uint32_t index,
1673 LanguageMode language_mode = SLOPPY);
1675 // Tests for the fast common case for property enumeration.
1676 bool IsSimpleEnum();
1678 // Returns the class name ([[Class]] property in the specification).
1679 String* class_name();
1681 // Returns the constructor name (the name (possibly, inferred name) of the
1682 // function that was used to instantiate the object).
1683 String* constructor_name();
1685 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1686 Handle<JSReceiver> object, Handle<Name> name);
1687 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1688 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1690 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1691 Handle<JSReceiver> object, uint32_t index);
1692 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1693 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1695 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1696 LookupIterator* it);
1699 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1701 static Handle<Object> GetDataProperty(LookupIterator* it);
1704 // Retrieves a permanent object identity hash code. The undefined value might
1705 // be returned in case no hash was created yet.
1706 inline Object* GetIdentityHash();
1708 // Retrieves a permanent object identity hash code. May create and store a
1709 // hash code if needed and none exists.
1710 inline static Handle<Smi> GetOrCreateIdentityHash(
1711 Handle<JSReceiver> object);
1713 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1715 // Computes the enumerable keys for a JSObject. Used for implementing
1716 // "for (n in object) { }".
1717 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1718 Handle<JSReceiver> object,
1719 KeyCollectionType type);
1722 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1726 // The JSObject describes real heap allocated JavaScript objects with
1728 // Note that the map of JSObject changes during execution to enable inline
1730 class JSObject: public JSReceiver {
1732 // [properties]: Backing storage for properties.
1733 // properties is a FixedArray in the fast case and a Dictionary in the
1735 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1736 inline void initialize_properties();
1737 inline bool HasFastProperties();
1738 // Gets slow properties for non-global objects.
1739 inline NameDictionary* property_dictionary();
1740 // Gets global object properties.
1741 inline GlobalDictionary* global_dictionary();
1743 // [elements]: The elements (properties with names that are integers).
1745 // Elements can be in two general modes: fast and slow. Each mode
1746 // corrensponds to a set of object representations of elements that
1747 // have something in common.
1749 // In the fast mode elements is a FixedArray and so each element can
1750 // be quickly accessed. This fact is used in the generated code. The
1751 // elements array can have one of three maps in this mode:
1752 // fixed_array_map, sloppy_arguments_elements_map or
1753 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1754 // the elements array may be shared by a few objects and so before
1755 // writing to any element the array must be copied. Use
1756 // EnsureWritableFastElements in this case.
1758 // In the slow mode the elements is either a NumberDictionary, a
1759 // FixedArray parameter map for a (sloppy) arguments object.
1760 DECL_ACCESSORS(elements, FixedArrayBase)
1761 inline void initialize_elements();
1762 static void ResetElements(Handle<JSObject> object);
1763 static inline void SetMapAndElements(Handle<JSObject> object,
1765 Handle<FixedArrayBase> elements);
1766 inline ElementsKind GetElementsKind();
1767 ElementsAccessor* GetElementsAccessor();
1768 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1769 inline bool HasFastSmiElements();
1770 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1771 inline bool HasFastObjectElements();
1772 // Returns true if an object has elements of FAST_ELEMENTS or
1773 // FAST_SMI_ONLY_ELEMENTS.
1774 inline bool HasFastSmiOrObjectElements();
1775 // Returns true if an object has any of the fast elements kinds.
1776 inline bool HasFastElements();
1777 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1779 inline bool HasFastDoubleElements();
1780 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1782 inline bool HasFastHoleyElements();
1783 inline bool HasSloppyArgumentsElements();
1784 inline bool HasDictionaryElements();
1786 inline bool HasFixedTypedArrayElements();
1788 inline bool HasFixedUint8ClampedElements();
1789 inline bool HasFixedArrayElements();
1790 inline bool HasFixedInt8Elements();
1791 inline bool HasFixedUint8Elements();
1792 inline bool HasFixedInt16Elements();
1793 inline bool HasFixedUint16Elements();
1794 inline bool HasFixedInt32Elements();
1795 inline bool HasFixedUint32Elements();
1796 inline bool HasFixedFloat32Elements();
1797 inline bool HasFixedFloat64Elements();
1799 inline bool HasFastArgumentsElements();
1800 inline bool HasSlowArgumentsElements();
1801 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1803 // Requires: HasFastElements().
1804 static Handle<FixedArray> EnsureWritableFastElements(
1805 Handle<JSObject> object);
1807 // Collects elements starting at index 0.
1808 // Undefined values are placed after non-undefined values.
1809 // Returns the number of non-undefined values.
1810 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1812 // As PrepareElementsForSort, but only on objects where elements is
1813 // a dictionary, and it will stay a dictionary. Collates undefined and
1814 // unexisting elements below limit from position zero of the elements.
1815 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1818 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1819 LookupIterator* it, Handle<Object> value);
1821 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1822 // grant an exemption to ExecutableAccessor callbacks in some cases.
1823 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1825 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1826 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1827 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1829 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1830 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1831 PropertyAttributes attributes,
1832 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1834 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1835 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1836 PropertyAttributes attributes,
1837 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1839 // Equivalent to one of the above depending on whether |name| can be converted
1840 // to an array index.
1841 MUST_USE_RESULT static MaybeHandle<Object>
1842 DefinePropertyOrElementIgnoreAttributes(
1843 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1844 PropertyAttributes attributes = NONE,
1845 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1847 // Adds or reconfigures a property to attributes NONE. It will fail when it
1849 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1850 Handle<Object> value);
1852 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1853 Handle<Object> value, PropertyAttributes attributes);
1855 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1856 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1857 PropertyAttributes attributes);
1859 // Extend the receiver with a single fast property appeared first in the
1860 // passed map. This also extends the property backing store if necessary.
1861 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1863 // Migrates the given object to a map whose field representations are the
1864 // lowest upper bound of all known representations for that field.
1865 static void MigrateInstance(Handle<JSObject> instance);
1867 // Migrates the given object only if the target map is already available,
1868 // or returns false if such a map is not yet available.
1869 static bool TryMigrateInstance(Handle<JSObject> instance);
1871 // Sets the property value in a normalized object given (key, value, details).
1872 // Handles the special representation of JS global objects.
1873 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1874 Handle<Object> value,
1875 PropertyDetails details);
1876 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1877 Handle<Object> value,
1878 PropertyAttributes attributes);
1879 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1881 Handle<Object> value,
1882 PropertyAttributes attributes);
1884 static void OptimizeAsPrototype(Handle<JSObject> object,
1885 PrototypeOptimizationMode mode);
1886 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1887 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1888 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1889 static void InvalidatePrototypeChains(Map* map);
1891 // Alternative implementation of WeakFixedArray::NullCallback.
1892 class PrototypeRegistryCompactionCallback {
1894 static void Callback(Object* value, int old_index, int new_index);
1897 // Retrieve interceptors.
1898 InterceptorInfo* GetNamedInterceptor();
1899 InterceptorInfo* GetIndexedInterceptor();
1901 // Used from JSReceiver.
1902 MUST_USE_RESULT static Maybe<PropertyAttributes>
1903 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1904 MUST_USE_RESULT static Maybe<PropertyAttributes>
1905 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1907 // Retrieves an AccessorPair property from the given object. Might return
1908 // undefined if the property doesn't exist or is of a different kind.
1909 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1910 Handle<JSObject> object,
1912 AccessorComponent component);
1914 // Defines an AccessorPair property on the given object.
1915 // TODO(mstarzinger): Rename to SetAccessor().
1916 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1918 Handle<Object> getter,
1919 Handle<Object> setter,
1920 PropertyAttributes attributes);
1922 // Defines an AccessorInfo property on the given object.
1923 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1924 Handle<JSObject> object,
1925 Handle<AccessorInfo> info);
1927 // The result must be checked first for exceptions. If there's no exception,
1928 // the output parameter |done| indicates whether the interceptor has a result
1930 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1931 LookupIterator* it, bool* done);
1933 // Accessors for hidden properties object.
1935 // Hidden properties are not own properties of the object itself.
1936 // Instead they are stored in an auxiliary structure kept as an own
1937 // property with a special name Heap::hidden_string(). But if the
1938 // receiver is a JSGlobalProxy then the auxiliary object is a property
1939 // of its prototype, and if it's a detached proxy, then you can't have
1940 // hidden properties.
1942 // Sets a hidden property on this object. Returns this object if successful,
1943 // undefined if called on a detached proxy.
1944 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1946 Handle<Object> value);
1947 // Gets the value of a hidden property with the given key. Returns the hole
1948 // if the property doesn't exist (or if called on a detached proxy),
1949 // otherwise returns the value set for the key.
1950 Object* GetHiddenProperty(Handle<Name> key);
1951 // Deletes a hidden property. Deleting a non-existing property is
1952 // considered successful.
1953 static void DeleteHiddenProperty(Handle<JSObject> object,
1955 // Returns true if the object has a property with the hidden string as name.
1956 static bool HasHiddenProperties(Handle<JSObject> object);
1958 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1960 static void ValidateElements(Handle<JSObject> object);
1962 // Makes sure that this object can contain HeapObject as elements.
1963 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1965 // Makes sure that this object can contain the specified elements.
1966 static inline void EnsureCanContainElements(
1967 Handle<JSObject> object,
1970 EnsureElementsMode mode);
1971 static inline void EnsureCanContainElements(
1972 Handle<JSObject> object,
1973 Handle<FixedArrayBase> elements,
1975 EnsureElementsMode mode);
1976 static void EnsureCanContainElements(
1977 Handle<JSObject> object,
1978 Arguments* arguments,
1981 EnsureElementsMode mode);
1983 // Would we convert a fast elements array to dictionary mode given
1984 // an access at key?
1985 bool WouldConvertToSlowElements(uint32_t index);
1987 // Computes the new capacity when expanding the elements of a JSObject.
1988 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1989 // (old_capacity + 50%) + 16
1990 return old_capacity + (old_capacity >> 1) + 16;
1993 // These methods do not perform access checks!
1994 static void UpdateAllocationSite(Handle<JSObject> object,
1995 ElementsKind to_kind);
1997 // Lookup interceptors are used for handling properties controlled by host
1999 inline bool HasNamedInterceptor();
2000 inline bool HasIndexedInterceptor();
2002 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2003 // by JSReceiver::GetKeys.
2004 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2005 Handle<JSObject> object,
2006 Handle<JSReceiver> receiver);
2007 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2008 Handle<JSObject> object,
2009 Handle<JSReceiver> receiver);
2011 // Support functions for v8 api (needed for correct interceptor behavior).
2012 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2013 Handle<JSObject> object, Handle<Name> name);
2014 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2015 Handle<JSObject> object, uint32_t index);
2016 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2017 Handle<JSObject> object, Handle<Name> name);
2019 // Get the header size for a JSObject. Used to compute the index of
2020 // internal fields as well as the number of internal fields.
2021 inline int GetHeaderSize();
2023 inline int GetInternalFieldCount();
2024 inline int GetInternalFieldOffset(int index);
2025 inline Object* GetInternalField(int index);
2026 inline void SetInternalField(int index, Object* value);
2027 inline void SetInternalField(int index, Smi* value);
2029 // Returns the number of properties on this object filtering out properties
2030 // with the specified attributes (ignoring interceptors).
2031 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2032 // Fill in details for properties into storage starting at the specified
2033 // index. Returns the number of properties added.
2034 int GetOwnPropertyNames(FixedArray* storage, int index,
2035 PropertyAttributes filter = NONE);
2037 // Returns the number of properties on this object filtering out properties
2038 // with the specified attributes (ignoring interceptors).
2039 int NumberOfOwnElements(PropertyAttributes filter);
2040 // Returns the number of enumerable elements (ignoring interceptors).
2041 int NumberOfEnumElements();
2042 // Returns the number of elements on this object filtering out elements
2043 // with the specified attributes (ignoring interceptors).
2044 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2045 // Count and fill in the enumerable elements into storage.
2046 // (storage->length() == NumberOfEnumElements()).
2047 // If storage is NULL, will count the elements without adding
2048 // them to any storage.
2049 // Returns the number of enumerable elements.
2050 int GetEnumElementKeys(FixedArray* storage);
2052 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2055 // Returns a new map with all transitions dropped from the object's current
2056 // map and the ElementsKind set.
2057 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2058 ElementsKind to_kind);
2059 static void TransitionElementsKind(Handle<JSObject> object,
2060 ElementsKind to_kind);
2062 // Always use this to migrate an object to a new map.
2063 // |expected_additional_properties| is only used for fast-to-slow transitions
2064 // and ignored otherwise.
2065 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2066 int expected_additional_properties = 0);
2068 // Convert the object to use the canonical dictionary
2069 // representation. If the object is expected to have additional properties
2070 // added this number can be indicated to have the backing store allocated to
2071 // an initial capacity for holding these properties.
2072 static void NormalizeProperties(Handle<JSObject> object,
2073 PropertyNormalizationMode mode,
2074 int expected_additional_properties,
2075 const char* reason);
2077 // Convert and update the elements backing store to be a
2078 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2079 static Handle<SeededNumberDictionary> NormalizeElements(
2080 Handle<JSObject> object);
2082 void RequireSlowElements(SeededNumberDictionary* dictionary);
2084 // Transform slow named properties to fast variants.
2085 static void MigrateSlowToFast(Handle<JSObject> object,
2086 int unused_property_fields, const char* reason);
2088 inline bool IsUnboxedDoubleField(FieldIndex index);
2090 // Access fast-case object properties at index.
2091 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2092 Representation representation,
2094 inline Object* RawFastPropertyAt(FieldIndex index);
2095 inline double RawFastDoublePropertyAt(FieldIndex index);
2097 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2098 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2099 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2100 inline void WriteToField(int descriptor, Object* value);
2102 // Access to in object properties.
2103 inline int GetInObjectPropertyOffset(int index);
2104 inline Object* InObjectPropertyAt(int index);
2105 inline Object* InObjectPropertyAtPut(int index,
2107 WriteBarrierMode mode
2108 = UPDATE_WRITE_BARRIER);
2110 // Set the object's prototype (only JSReceiver and null are allowed values).
2111 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2112 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2114 // Initializes the body after properties slot, properties slot is
2115 // initialized by set_properties. Fill the pre-allocated fields with
2116 // pre_allocated_value and the rest with filler_value.
2117 // Note: this call does not update write barrier, the caller is responsible
2118 // to ensure that |filler_value| can be collected without WB here.
2119 inline void InitializeBody(Map* map,
2120 Object* pre_allocated_value,
2121 Object* filler_value);
2123 // Check whether this object references another object
2124 bool ReferencesObject(Object* obj);
2126 // Disalow further properties to be added to the oject.
2127 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2128 Handle<JSObject> object);
2130 bool IsExtensible();
2133 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2135 // ES5 Object.freeze
2136 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2138 // Called the first time an object is observed with ES7 Object.observe.
2139 static void SetObserved(Handle<JSObject> object);
2142 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2144 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2145 Handle<JSObject> object,
2146 AllocationSiteUsageContext* site_context,
2147 DeepCopyHints hints = kNoHints);
2148 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2149 Handle<JSObject> object,
2150 AllocationSiteCreationContext* site_context);
2152 DECLARE_CAST(JSObject)
2154 // Dispatched behavior.
2155 void JSObjectShortPrint(StringStream* accumulator);
2156 DECLARE_PRINTER(JSObject)
2157 DECLARE_VERIFIER(JSObject)
2159 void PrintProperties(std::ostream& os); // NOLINT
2160 void PrintElements(std::ostream& os); // NOLINT
2162 #if defined(DEBUG) || defined(OBJECT_PRINT)
2163 void PrintTransitions(std::ostream& os); // NOLINT
2166 static void PrintElementsTransition(
2167 FILE* file, Handle<JSObject> object,
2168 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2169 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2171 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2174 // Structure for collecting spill information about JSObjects.
2175 class SpillInformation {
2179 int number_of_objects_;
2180 int number_of_objects_with_fast_properties_;
2181 int number_of_objects_with_fast_elements_;
2182 int number_of_fast_used_fields_;
2183 int number_of_fast_unused_fields_;
2184 int number_of_slow_used_properties_;
2185 int number_of_slow_unused_properties_;
2186 int number_of_fast_used_elements_;
2187 int number_of_fast_unused_elements_;
2188 int number_of_slow_used_elements_;
2189 int number_of_slow_unused_elements_;
2192 void IncrementSpillStatistics(SpillInformation* info);
2196 // If a GC was caused while constructing this object, the elements pointer
2197 // may point to a one pointer filler map. The object won't be rooted, but
2198 // our heap verification code could stumble across it.
2199 bool ElementsAreSafeToExamine();
2202 Object* SlowReverseLookup(Object* value);
2204 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2205 // Also maximal value of JSArray's length property.
2206 static const uint32_t kMaxElementCount = 0xffffffffu;
2208 // Constants for heuristics controlling conversion of fast elements
2209 // to slow elements.
2211 // Maximal gap that can be introduced by adding an element beyond
2212 // the current elements length.
2213 static const uint32_t kMaxGap = 1024;
2215 // Maximal length of fast elements array that won't be checked for
2216 // being dense enough on expansion.
2217 static const int kMaxUncheckedFastElementsLength = 5000;
2219 // Same as above but for old arrays. This limit is more strict. We
2220 // don't want to be wasteful with long lived objects.
2221 static const int kMaxUncheckedOldFastElementsLength = 500;
2223 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2224 // permissible values (see the DCHECK in heap.cc).
2225 static const int kInitialMaxFastElementArray = 100000;
2227 // This constant applies only to the initial map of "global.Object" and
2228 // not to arbitrary other JSObject maps.
2229 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2231 static const int kMaxInstanceSize = 255 * kPointerSize;
2232 // When extending the backing storage for property values, we increase
2233 // its size by more than the 1 entry necessary, so sequentially adding fields
2234 // to the same object requires fewer allocations and copies.
2235 static const int kFieldsAdded = 3;
2237 // Layout description.
2238 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2239 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2240 static const int kHeaderSize = kElementsOffset + kPointerSize;
2242 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2244 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2246 static inline int SizeOf(Map* map, HeapObject* object);
2249 Context* GetCreationContext();
2251 // Enqueue change record for Object.observe. May cause GC.
2252 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2253 Handle<JSObject> object, const char* type, Handle<Name> name,
2254 Handle<Object> old_value);
2256 // Gets the number of currently used elements.
2257 int GetFastElementsUsage();
2259 // Deletes an existing named property in a normalized object.
2260 static void DeleteNormalizedProperty(Handle<JSObject> object,
2261 Handle<Name> name, int entry);
2263 static bool AllCanRead(LookupIterator* it);
2264 static bool AllCanWrite(LookupIterator* it);
2267 friend class JSReceiver;
2268 friend class Object;
2270 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2271 static void MigrateFastToSlow(Handle<JSObject> object,
2272 Handle<Map> new_map,
2273 int expected_additional_properties);
2275 // Used from Object::GetProperty().
2276 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2277 LookupIterator* it);
2279 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2280 LookupIterator* it, Handle<Object> value);
2282 // Add a property to a slow-case object.
2283 static void AddSlowProperty(Handle<JSObject> object,
2285 Handle<Object> value,
2286 PropertyAttributes attributes);
2288 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2289 LookupIterator* it);
2291 bool ReferencesObjectFromElements(FixedArray* elements,
2295 // Return the hash table backing store or the inline stored identity hash,
2296 // whatever is found.
2297 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2299 // Return the hash table backing store for hidden properties. If there is no
2300 // backing store, allocate one.
2301 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2302 Handle<JSObject> object);
2304 // Set the hidden property backing store to either a hash table or
2305 // the inline-stored identity hash.
2306 static Handle<Object> SetHiddenPropertiesHashTable(
2307 Handle<JSObject> object,
2308 Handle<Object> value);
2310 MUST_USE_RESULT Object* GetIdentityHash();
2312 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2314 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2315 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2317 // Helper for fast versions of preventExtensions, seal, and freeze.
2318 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2319 template <PropertyAttributes attrs>
2320 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2321 Handle<JSObject> object);
2323 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2327 // Common superclass for FixedArrays that allow implementations to share
2328 // common accessors and some code paths.
2329 class FixedArrayBase: public HeapObject {
2331 // [length]: length of the array.
2332 inline int length() const;
2333 inline void set_length(int value);
2335 // Get and set the length using acquire loads and release stores.
2336 inline int synchronized_length() const;
2337 inline void synchronized_set_length(int value);
2339 DECLARE_CAST(FixedArrayBase)
2341 // Layout description.
2342 // Length is smi tagged when it is stored.
2343 static const int kLengthOffset = HeapObject::kHeaderSize;
2344 static const int kHeaderSize = kLengthOffset + kPointerSize;
2348 class FixedDoubleArray;
2349 class IncrementalMarking;
2352 // FixedArray describes fixed-sized arrays with element type Object*.
2353 class FixedArray: public FixedArrayBase {
2355 // Setter and getter for elements.
2356 inline Object* get(int index) const;
2357 void SetValue(uint32_t index, Object* value);
2358 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2359 // Setter that uses write barrier.
2360 inline void set(int index, Object* value);
2361 inline bool is_the_hole(int index);
2363 // Setter that doesn't need write barrier.
2364 inline void set(int index, Smi* value);
2365 // Setter with explicit barrier mode.
2366 inline void set(int index, Object* value, WriteBarrierMode mode);
2368 // Setters for frequently used oddballs located in old space.
2369 inline void set_undefined(int index);
2370 inline void set_null(int index);
2371 inline void set_the_hole(int index);
2373 inline Object** GetFirstElementAddress();
2374 inline bool ContainsOnlySmisOrHoles();
2376 // Gives access to raw memory which stores the array's data.
2377 inline Object** data_start();
2379 inline void FillWithHoles(int from, int to);
2381 // Shrink length and insert filler objects.
2382 void Shrink(int length);
2384 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2386 // Add the elements of a JSArray to this FixedArray.
2387 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2388 Handle<FixedArray> content, Handle<JSObject> array,
2389 KeyFilter filter = ALL_KEYS);
2391 // Computes the union of keys and return the result.
2392 // Used for implementing "for (n in object) { }"
2393 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2394 Handle<FixedArray> first,
2395 Handle<FixedArray> second);
2397 // Copy a sub array from the receiver to dest.
2398 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2400 // Garbage collection support.
2401 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2403 // Code Generation support.
2404 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2406 // Garbage collection support.
2407 inline Object** RawFieldOfElementAt(int index);
2409 DECLARE_CAST(FixedArray)
2411 // Maximal allowed size, in bytes, of a single FixedArray.
2412 // Prevents overflowing size computations, as well as extreme memory
2414 static const int kMaxSize = 128 * MB * kPointerSize;
2415 // Maximally allowed length of a FixedArray.
2416 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2418 // Dispatched behavior.
2419 DECLARE_PRINTER(FixedArray)
2420 DECLARE_VERIFIER(FixedArray)
2422 // Checks if two FixedArrays have identical contents.
2423 bool IsEqualTo(FixedArray* other);
2426 // Swap two elements in a pair of arrays. If this array and the
2427 // numbers array are the same object, the elements are only swapped
2429 void SwapPairs(FixedArray* numbers, int i, int j);
2431 // Sort prefix of this array and the numbers array as pairs wrt. the
2432 // numbers. If the numbers array and the this array are the same
2433 // object, the prefix of this array is sorted.
2434 void SortPairs(FixedArray* numbers, uint32_t len);
2436 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2438 static inline int SizeOf(Map* map, HeapObject* object);
2442 // Set operation on FixedArray without using write barriers. Can
2443 // only be used for storing old space objects or smis.
2444 static inline void NoWriteBarrierSet(FixedArray* array,
2448 // Set operation on FixedArray without incremental write barrier. Can
2449 // only be used if the object is guaranteed to be white (whiteness witness
2451 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2456 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2458 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2462 // FixedDoubleArray describes fixed-sized arrays with element type double.
2463 class FixedDoubleArray: public FixedArrayBase {
2465 // Setter and getter for elements.
2466 inline double get_scalar(int index);
2467 inline uint64_t get_representation(int index);
2468 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2469 // This accessor has to get a Number as |value|.
2470 void SetValue(uint32_t index, Object* value);
2471 inline void set(int index, double value);
2472 inline void set_the_hole(int index);
2474 // Checking for the hole.
2475 inline bool is_the_hole(int index);
2477 // Garbage collection support.
2478 inline static int SizeFor(int length) {
2479 return kHeaderSize + length * kDoubleSize;
2482 // Gives access to raw memory which stores the array's data.
2483 inline double* data_start();
2485 inline void FillWithHoles(int from, int to);
2487 // Code Generation support.
2488 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2490 DECLARE_CAST(FixedDoubleArray)
2492 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2493 // Prevents overflowing size computations, as well as extreme memory
2495 static const int kMaxSize = 512 * MB;
2496 // Maximally allowed length of a FixedArray.
2497 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2499 // Dispatched behavior.
2500 DECLARE_PRINTER(FixedDoubleArray)
2501 DECLARE_VERIFIER(FixedDoubleArray)
2504 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2508 class WeakFixedArray : public FixedArray {
2510 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2511 // This function does not check if the value exists already, callers must
2512 // ensure this themselves if necessary.
2513 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2514 Handle<HeapObject> value,
2515 int* assigned_index = NULL);
2517 // Returns true if an entry was found and removed.
2518 bool Remove(Handle<HeapObject> value);
2520 class NullCallback {
2522 static void Callback(Object* value, int old_index, int new_index) {}
2525 template <class CompactionCallback>
2528 inline Object* Get(int index) const;
2529 inline void Clear(int index);
2530 inline int Length() const;
2532 inline bool IsEmptySlot(int index) const;
2533 static Object* Empty() { return Smi::FromInt(0); }
2537 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2538 void Reset(Object* maybe_array);
2545 WeakFixedArray* list_;
2547 int last_used_index_;
2548 DisallowHeapAllocation no_gc_;
2550 DISALLOW_COPY_AND_ASSIGN(Iterator);
2553 DECLARE_CAST(WeakFixedArray)
2556 static const int kLastUsedIndexIndex = 0;
2557 static const int kFirstIndex = 1;
2559 static Handle<WeakFixedArray> Allocate(
2560 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2562 static void Set(Handle<WeakFixedArray> array, int index,
2563 Handle<HeapObject> value);
2564 inline void clear(int index);
2566 inline int last_used_index() const;
2567 inline void set_last_used_index(int index);
2569 // Disallow inherited setters.
2570 void set(int index, Smi* value);
2571 void set(int index, Object* value);
2572 void set(int index, Object* value, WriteBarrierMode mode);
2573 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2577 // Generic array grows dynamically with O(1) amortized insertion.
2578 class ArrayList : public FixedArray {
2582 // Use this if GC can delete elements from the array.
2583 kReloadLengthAfterAllocation,
2585 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2586 AddMode mode = kNone);
2587 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2588 Handle<Object> obj2, AddMode = kNone);
2589 inline int Length();
2590 inline void SetLength(int length);
2591 inline Object* Get(int index);
2592 inline Object** Slot(int index);
2593 inline void Set(int index, Object* obj);
2594 inline void Clear(int index, Object* undefined);
2595 DECLARE_CAST(ArrayList)
2598 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2599 static const int kLengthIndex = 0;
2600 static const int kFirstIndex = 1;
2601 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2605 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2606 // The format of the these objects is:
2607 // [0]: Number of descriptors
2608 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2609 // [0]: pointer to fixed array with enum cache
2610 // [1]: either Smi(0) or pointer to fixed array with indices
2612 // [2 + number of descriptors * kDescriptorSize]: start of slack
2613 class DescriptorArray: public FixedArray {
2615 // Returns true for both shared empty_descriptor_array and for smis, which the
2616 // map uses to encode additional bit fields when the descriptor array is not
2618 inline bool IsEmpty();
2620 // Returns the number of descriptors in the array.
2621 inline int number_of_descriptors();
2623 inline int number_of_descriptors_storage();
2625 inline int NumberOfSlackDescriptors();
2627 inline void SetNumberOfDescriptors(int number_of_descriptors);
2628 inline int number_of_entries();
2630 inline bool HasEnumCache();
2632 inline void CopyEnumCacheFrom(DescriptorArray* array);
2634 inline FixedArray* GetEnumCache();
2636 inline bool HasEnumIndicesCache();
2638 inline FixedArray* GetEnumIndicesCache();
2640 inline Object** GetEnumCacheSlot();
2642 void ClearEnumCache();
2644 // Initialize or change the enum cache,
2645 // using the supplied storage for the small "bridge".
2646 void SetEnumCache(FixedArray* bridge_storage,
2647 FixedArray* new_cache,
2648 Object* new_index_cache);
2650 bool CanHoldValue(int descriptor, Object* value);
2652 // Accessors for fetching instance descriptor at descriptor number.
2653 inline Name* GetKey(int descriptor_number);
2654 inline Object** GetKeySlot(int descriptor_number);
2655 inline Object* GetValue(int descriptor_number);
2656 inline void SetValue(int descriptor_number, Object* value);
2657 inline Object** GetValueSlot(int descriptor_number);
2658 static inline int GetValueOffset(int descriptor_number);
2659 inline Object** GetDescriptorStartSlot(int descriptor_number);
2660 inline Object** GetDescriptorEndSlot(int descriptor_number);
2661 inline PropertyDetails GetDetails(int descriptor_number);
2662 inline PropertyType GetType(int descriptor_number);
2663 inline int GetFieldIndex(int descriptor_number);
2664 inline HeapType* GetFieldType(int descriptor_number);
2665 inline Object* GetConstant(int descriptor_number);
2666 inline Object* GetCallbacksObject(int descriptor_number);
2667 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2669 inline Name* GetSortedKey(int descriptor_number);
2670 inline int GetSortedKeyIndex(int descriptor_number);
2671 inline void SetSortedKey(int pointer, int descriptor_number);
2672 inline void SetRepresentation(int descriptor_number,
2673 Representation representation);
2675 // Accessor for complete descriptor.
2676 inline void Get(int descriptor_number, Descriptor* desc);
2677 inline void Set(int descriptor_number, Descriptor* desc);
2678 void Replace(int descriptor_number, Descriptor* descriptor);
2680 // Append automatically sets the enumeration index. This should only be used
2681 // to add descriptors in bulk at the end, followed by sorting the descriptor
2683 inline void Append(Descriptor* desc);
2685 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2686 int enumeration_index,
2689 static Handle<DescriptorArray> CopyUpToAddAttributes(
2690 Handle<DescriptorArray> desc,
2691 int enumeration_index,
2692 PropertyAttributes attributes,
2695 // Sort the instance descriptors by the hash codes of their keys.
2698 // Search the instance descriptors for given name.
2699 INLINE(int Search(Name* name, int number_of_own_descriptors));
2701 // As the above, but uses DescriptorLookupCache and updates it when
2703 INLINE(int SearchWithCache(Name* name, Map* map));
2705 // Allocates a DescriptorArray, but returns the singleton
2706 // empty descriptor array object if number_of_descriptors is 0.
2707 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2708 int number_of_descriptors,
2711 DECLARE_CAST(DescriptorArray)
2713 // Constant for denoting key was not found.
2714 static const int kNotFound = -1;
2716 static const int kDescriptorLengthIndex = 0;
2717 static const int kEnumCacheIndex = 1;
2718 static const int kFirstIndex = 2;
2720 // The length of the "bridge" to the enum cache.
2721 static const int kEnumCacheBridgeLength = 2;
2722 static const int kEnumCacheBridgeCacheIndex = 0;
2723 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2725 // Layout description.
2726 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2727 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2728 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2730 // Layout description for the bridge array.
2731 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2733 // Layout of descriptor.
2734 static const int kDescriptorKey = 0;
2735 static const int kDescriptorDetails = 1;
2736 static const int kDescriptorValue = 2;
2737 static const int kDescriptorSize = 3;
2739 #if defined(DEBUG) || defined(OBJECT_PRINT)
2740 // For our gdb macros, we should perhaps change these in the future.
2743 // Print all the descriptors.
2744 void PrintDescriptors(std::ostream& os); // NOLINT
2748 // Is the descriptor array sorted and without duplicates?
2749 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2751 // Is the descriptor array consistent with the back pointers in targets?
2752 bool IsConsistentWithBackPointers(Map* current_map);
2754 // Are two DescriptorArrays equal?
2755 bool IsEqualTo(DescriptorArray* other);
2758 // Returns the fixed array length required to hold number_of_descriptors
2760 static int LengthFor(int number_of_descriptors) {
2761 return ToKeyIndex(number_of_descriptors);
2765 // WhitenessWitness is used to prove that a descriptor array is white
2766 // (unmarked), so incremental write barriers can be skipped because the
2767 // marking invariant cannot be broken and slots pointing into evacuation
2768 // candidates will be discovered when the object is scanned. A witness is
2769 // always stack-allocated right after creating an array. By allocating a
2770 // witness, incremental marking is globally disabled. The witness is then
2771 // passed along wherever needed to statically prove that the array is known to
2773 class WhitenessWitness {
2775 inline explicit WhitenessWitness(DescriptorArray* array);
2776 inline ~WhitenessWitness();
2779 IncrementalMarking* marking_;
2782 // An entry in a DescriptorArray, represented as an (array, index) pair.
2785 inline explicit Entry(DescriptorArray* descs, int index) :
2786 descs_(descs), index_(index) { }
2788 inline PropertyType type();
2789 inline Object* GetCallbackObject();
2792 DescriptorArray* descs_;
2796 // Conversion from descriptor number to array indices.
2797 static int ToKeyIndex(int descriptor_number) {
2798 return kFirstIndex +
2799 (descriptor_number * kDescriptorSize) +
2803 static int ToDetailsIndex(int descriptor_number) {
2804 return kFirstIndex +
2805 (descriptor_number * kDescriptorSize) +
2809 static int ToValueIndex(int descriptor_number) {
2810 return kFirstIndex +
2811 (descriptor_number * kDescriptorSize) +
2815 // Transfer a complete descriptor from the src descriptor array to this
2816 // descriptor array.
2817 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2819 inline void Set(int descriptor_number,
2821 const WhitenessWitness&);
2823 // Swap first and second descriptor.
2824 inline void SwapSortedKeys(int first, int second);
2826 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2830 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2832 template <SearchMode search_mode, typename T>
2833 inline int Search(T* array, Name* name, int valid_entries = 0,
2834 int* out_insertion_index = NULL);
2837 // HashTable is a subclass of FixedArray that implements a hash table
2838 // that uses open addressing and quadratic probing.
2840 // In order for the quadratic probing to work, elements that have not
2841 // yet been used and elements that have been deleted are
2842 // distinguished. Probing continues when deleted elements are
2843 // encountered and stops when unused elements are encountered.
2845 // - Elements with key == undefined have not been used yet.
2846 // - Elements with key == the_hole have been deleted.
2848 // The hash table class is parameterized with a Shape and a Key.
2849 // Shape must be a class with the following interface:
2850 // class ExampleShape {
2852 // // Tells whether key matches other.
2853 // static bool IsMatch(Key key, Object* other);
2854 // // Returns the hash value for key.
2855 // static uint32_t Hash(Key key);
2856 // // Returns the hash value for object.
2857 // static uint32_t HashForObject(Key key, Object* object);
2858 // // Convert key to an object.
2859 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2860 // // The prefix size indicates number of elements in the beginning
2861 // // of the backing storage.
2862 // static const int kPrefixSize = ..;
2863 // // The Element size indicates number of elements per entry.
2864 // static const int kEntrySize = ..;
2866 // The prefix size indicates an amount of memory in the
2867 // beginning of the backing storage that can be used for non-element
2868 // information by subclasses.
2870 template<typename Key>
2873 static const bool UsesSeed = false;
2874 static uint32_t Hash(Key key) { return 0; }
2875 static uint32_t SeededHash(Key key, uint32_t seed) {
2879 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2880 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2882 return HashForObject(key, object);
2887 class HashTableBase : public FixedArray {
2889 // Returns the number of elements in the hash table.
2890 inline int NumberOfElements();
2892 // Returns the number of deleted elements in the hash table.
2893 inline int NumberOfDeletedElements();
2895 // Returns the capacity of the hash table.
2896 inline int Capacity();
2898 // ElementAdded should be called whenever an element is added to a
2900 inline void ElementAdded();
2902 // ElementRemoved should be called whenever an element is removed from
2904 inline void ElementRemoved();
2905 inline void ElementsRemoved(int n);
2907 // Computes the required capacity for a table holding the given
2908 // number of elements. May be more than HashTable::kMaxCapacity.
2909 static inline int ComputeCapacity(int at_least_space_for);
2911 // Tells whether k is a real key. The hole and undefined are not allowed
2912 // as keys and can be used to indicate missing or deleted elements.
2913 inline bool IsKey(Object* k);
2915 // Compute the probe offset (quadratic probing).
2916 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2917 return (n + n * n) >> 1;
2920 static const int kNumberOfElementsIndex = 0;
2921 static const int kNumberOfDeletedElementsIndex = 1;
2922 static const int kCapacityIndex = 2;
2923 static const int kPrefixStartIndex = 3;
2925 // Constant used for denoting a absent entry.
2926 static const int kNotFound = -1;
2929 // Update the number of elements in the hash table.
2930 inline void SetNumberOfElements(int nof);
2932 // Update the number of deleted elements in the hash table.
2933 inline void SetNumberOfDeletedElements(int nod);
2935 // Returns probe entry.
2936 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2937 DCHECK(base::bits::IsPowerOfTwo32(size));
2938 return (hash + GetProbeOffset(number)) & (size - 1);
2941 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2942 return hash & (size - 1);
2945 inline static uint32_t NextProbe(
2946 uint32_t last, uint32_t number, uint32_t size) {
2947 return (last + number) & (size - 1);
2952 template <typename Derived, typename Shape, typename Key>
2953 class HashTable : public HashTableBase {
2956 inline uint32_t Hash(Key key) {
2957 if (Shape::UsesSeed) {
2958 return Shape::SeededHash(key, GetHeap()->HashSeed());
2960 return Shape::Hash(key);
2964 inline uint32_t HashForObject(Key key, Object* object) {
2965 if (Shape::UsesSeed) {
2966 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2968 return Shape::HashForObject(key, object);
2972 // Returns a new HashTable object.
2973 MUST_USE_RESULT static Handle<Derived> New(
2974 Isolate* isolate, int at_least_space_for,
2975 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2976 PretenureFlag pretenure = NOT_TENURED);
2978 DECLARE_CAST(HashTable)
2980 // Garbage collection support.
2981 void IteratePrefix(ObjectVisitor* visitor);
2982 void IterateElements(ObjectVisitor* visitor);
2984 // Find entry for key otherwise return kNotFound.
2985 inline int FindEntry(Key key);
2986 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2987 int FindEntry(Isolate* isolate, Key key);
2989 // Rehashes the table in-place.
2990 void Rehash(Key key);
2992 // Returns the key at entry.
2993 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2995 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2996 static const int kEntrySize = Shape::kEntrySize;
2997 static const int kElementsStartOffset =
2998 kHeaderSize + kElementsStartIndex * kPointerSize;
2999 static const int kCapacityOffset =
3000 kHeaderSize + kCapacityIndex * kPointerSize;
3002 // Returns the index for an entry (of the key)
3003 static inline int EntryToIndex(int entry) {
3004 return (entry * kEntrySize) + kElementsStartIndex;
3008 friend class ObjectHashTable;
3010 // Find the entry at which to insert element with the given key that
3011 // has the given hash value.
3012 uint32_t FindInsertionEntry(uint32_t hash);
3014 // Attempt to shrink hash table after removal of key.
3015 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3017 // Ensure enough space for n additional elements.
3018 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3019 Handle<Derived> table,
3022 PretenureFlag pretenure = NOT_TENURED);
3024 // Sets the capacity of the hash table.
3025 void SetCapacity(int capacity) {
3026 // To scale a computed hash code to fit within the hash table, we
3027 // use bit-wise AND with a mask, so the capacity must be positive
3029 DCHECK(capacity > 0);
3030 DCHECK(capacity <= kMaxCapacity);
3031 set(kCapacityIndex, Smi::FromInt(capacity));
3034 // Maximal capacity of HashTable. Based on maximal length of underlying
3035 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3037 static const int kMaxCapacity =
3038 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3041 // Returns _expected_ if one of entries given by the first _probe_ probes is
3042 // equal to _expected_. Otherwise, returns the entry given by the probe
3044 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3046 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3048 // Rehashes this hash-table into the new table.
3049 void Rehash(Handle<Derived> new_table, Key key);
3053 // HashTableKey is an abstract superclass for virtual key behavior.
3054 class HashTableKey {
3056 // Returns whether the other object matches this key.
3057 virtual bool IsMatch(Object* other) = 0;
3058 // Returns the hash value for this key.
3059 virtual uint32_t Hash() = 0;
3060 // Returns the hash value for object.
3061 virtual uint32_t HashForObject(Object* key) = 0;
3062 // Returns the key object for storing into the hash table.
3063 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3065 virtual ~HashTableKey() {}
3069 class StringTableShape : public BaseShape<HashTableKey*> {
3071 static inline bool IsMatch(HashTableKey* key, Object* value) {
3072 return key->IsMatch(value);
3075 static inline uint32_t Hash(HashTableKey* key) {
3079 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3080 return key->HashForObject(object);
3083 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3085 static const int kPrefixSize = 0;
3086 static const int kEntrySize = 1;
3089 class SeqOneByteString;
3093 // No special elements in the prefix and the element size is 1
3094 // because only the string itself (the key) needs to be stored.
3095 class StringTable: public HashTable<StringTable,
3099 // Find string in the string table. If it is not there yet, it is
3100 // added. The return value is the string found.
3101 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3102 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3103 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3105 // Tries to internalize given string and returns string handle on success
3106 // or an empty handle otherwise.
3107 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3109 Handle<String> string);
3111 // Looks up a string that is equal to the given string and returns
3112 // string handle if it is found, or an empty handle otherwise.
3113 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3115 Handle<String> str);
3116 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3121 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3123 DECLARE_CAST(StringTable)
3126 template <bool seq_one_byte>
3127 friend class JsonParser;
3129 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3133 template <typename Derived, typename Shape, typename Key>
3134 class Dictionary: public HashTable<Derived, Shape, Key> {
3135 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3138 // Returns the value at entry.
3139 Object* ValueAt(int entry) {
3140 return this->get(Derived::EntryToIndex(entry) + 1);
3143 // Set the value for entry.
3144 void ValueAtPut(int entry, Object* value) {
3145 this->set(Derived::EntryToIndex(entry) + 1, value);
3148 // Returns the property details for the property at entry.
3149 PropertyDetails DetailsAt(int entry) {
3150 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3153 // Set the details for entry.
3154 void DetailsAtPut(int entry, PropertyDetails value) {
3155 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3158 // Returns true if property at given entry is deleted.
3159 bool IsDeleted(int entry) {
3160 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3163 // Delete a property from the dictionary.
3164 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3166 // Attempt to shrink the dictionary after deletion of key.
3167 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3168 Handle<Derived> dictionary,
3170 return DerivedHashTable::Shrink(dictionary, key);
3174 // TODO(dcarney): templatize or move to SeededNumberDictionary
3175 void CopyValuesTo(FixedArray* elements);
3177 // Returns the number of elements in the dictionary filtering out properties
3178 // with the specified attributes.
3179 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3181 // Returns the number of enumerable elements in the dictionary.
3182 int NumberOfEnumElements() {
3183 return NumberOfElementsFilterAttributes(
3184 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3187 // Returns true if the dictionary contains any elements that are non-writable,
3188 // non-configurable, non-enumerable, or have getters/setters.
3189 bool HasComplexElements();
3191 enum SortMode { UNSORTED, SORTED };
3193 // Fill in details for properties into storage.
3194 // Returns the number of properties added.
3195 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3196 SortMode sort_mode);
3198 // Copies enumerable keys to preallocated fixed array.
3199 void CopyEnumKeysTo(FixedArray* storage);
3201 // Accessors for next enumeration index.
3202 void SetNextEnumerationIndex(int index) {
3204 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3207 int NextEnumerationIndex() {
3208 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3211 // Creates a new dictionary.
3212 MUST_USE_RESULT static Handle<Derived> New(
3214 int at_least_space_for,
3215 PretenureFlag pretenure = NOT_TENURED);
3217 // Ensure enough space for n additional elements.
3218 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3221 void Print(std::ostream& os); // NOLINT
3223 // Returns the key (slow).
3224 Object* SlowReverseLookup(Object* value);
3226 // Sets the entry to (key, value) pair.
3227 inline void SetEntry(int entry,
3229 Handle<Object> value);
3230 inline void SetEntry(int entry,
3232 Handle<Object> value,
3233 PropertyDetails details);
3235 MUST_USE_RESULT static Handle<Derived> Add(
3236 Handle<Derived> dictionary,
3238 Handle<Object> value,
3239 PropertyDetails details);
3241 // Returns iteration indices array for the |dictionary|.
3242 // Values are direct indices in the |HashTable| array.
3243 static Handle<FixedArray> BuildIterationIndicesArray(
3244 Handle<Derived> dictionary);
3247 // Generic at put operation.
3248 MUST_USE_RESULT static Handle<Derived> AtPut(
3249 Handle<Derived> dictionary,
3251 Handle<Object> value);
3253 // Add entry to dictionary.
3254 static void AddEntry(
3255 Handle<Derived> dictionary,
3257 Handle<Object> value,
3258 PropertyDetails details,
3261 // Generate new enumeration indices to avoid enumeration index overflow.
3262 // Returns iteration indices array for the |dictionary|.
3263 static Handle<FixedArray> GenerateNewEnumerationIndices(
3264 Handle<Derived> dictionary);
3265 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3266 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3270 template <typename Derived, typename Shape>
3271 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3272 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3275 // Find entry for key, otherwise return kNotFound. Optimized version of
3276 // HashTable::FindEntry.
3277 int FindEntry(Handle<Name> key);
3281 template <typename Key>
3282 class BaseDictionaryShape : public BaseShape<Key> {
3284 template <typename Dictionary>
3285 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3286 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3287 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3288 return PropertyDetails(
3289 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3292 template <typename Dictionary>
3293 static inline void DetailsAtPut(Dictionary* dict, int entry,
3294 PropertyDetails value) {
3295 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3296 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3299 template <typename Dictionary>
3300 static bool IsDeleted(Dictionary* dict, int entry) {
3304 template <typename Dictionary>
3305 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3306 Handle<Object> value, PropertyDetails details);
3310 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3312 static inline bool IsMatch(Handle<Name> key, Object* other);
3313 static inline uint32_t Hash(Handle<Name> key);
3314 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3315 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3316 static const int kPrefixSize = 2;
3317 static const int kEntrySize = 3;
3318 static const bool kIsEnumerable = true;
3322 class NameDictionary
3323 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3324 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3328 DECLARE_CAST(NameDictionary)
3330 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3331 Handle<NameDictionary> dictionary);
3335 class GlobalDictionaryShape : public NameDictionaryShape {
3337 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3339 template <typename Dictionary>
3340 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3342 template <typename Dictionary>
3343 static inline void DetailsAtPut(Dictionary* dict, int entry,
3344 PropertyDetails value);
3346 template <typename Dictionary>
3347 static bool IsDeleted(Dictionary* dict, int entry);
3349 template <typename Dictionary>
3350 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3351 Handle<Object> value, PropertyDetails details);
3355 class GlobalDictionary
3356 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3358 DECLARE_CAST(GlobalDictionary)
3362 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3364 static inline bool IsMatch(uint32_t key, Object* other);
3365 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3366 static const int kEntrySize = 3;
3367 static const bool kIsEnumerable = false;
3371 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3373 static const bool UsesSeed = true;
3374 static const int kPrefixSize = 2;
3376 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3377 static inline uint32_t SeededHashForObject(uint32_t key,
3383 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3385 static const int kPrefixSize = 0;
3387 static inline uint32_t Hash(uint32_t key);
3388 static inline uint32_t HashForObject(uint32_t key, Object* object);
3392 class SeededNumberDictionary
3393 : public Dictionary<SeededNumberDictionary,
3394 SeededNumberDictionaryShape,
3397 DECLARE_CAST(SeededNumberDictionary)
3399 // Type specific at put (default NONE attributes is used when adding).
3400 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3401 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3402 Handle<Object> value, bool used_as_prototype);
3403 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3404 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3405 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3407 // Set an existing entry or add a new one if needed.
3408 // Return the updated dictionary.
3409 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3410 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3411 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3413 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3415 // If slow elements are required we will never go back to fast-case
3416 // for the elements kept in this dictionary. We require slow
3417 // elements if an element has been added at an index larger than
3418 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3419 // when defining a getter or setter with a number key.
3420 inline bool requires_slow_elements();
3421 inline void set_requires_slow_elements();
3423 // Get the value of the max number key that has been added to this
3424 // dictionary. max_number_key can only be called if
3425 // requires_slow_elements returns false.
3426 inline uint32_t max_number_key();
3429 static const int kRequiresSlowElementsMask = 1;
3430 static const int kRequiresSlowElementsTagSize = 1;
3431 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3435 class UnseededNumberDictionary
3436 : public Dictionary<UnseededNumberDictionary,
3437 UnseededNumberDictionaryShape,
3440 DECLARE_CAST(UnseededNumberDictionary)
3442 // Type specific at put (default NONE attributes is used when adding).
3443 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3444 Handle<UnseededNumberDictionary> dictionary,
3446 Handle<Object> value);
3447 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3448 Handle<UnseededNumberDictionary> dictionary,
3450 Handle<Object> value);
3452 // Set an existing entry or add a new one if needed.
3453 // Return the updated dictionary.
3454 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3455 Handle<UnseededNumberDictionary> dictionary,
3457 Handle<Object> value);
3461 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3463 static inline bool IsMatch(Handle<Object> key, Object* other);
3464 static inline uint32_t Hash(Handle<Object> key);
3465 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3466 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3467 static const int kPrefixSize = 0;
3468 static const int kEntrySize = 2;
3472 // ObjectHashTable maps keys that are arbitrary objects to object values by
3473 // using the identity hash of the key for hashing purposes.
3474 class ObjectHashTable: public HashTable<ObjectHashTable,
3475 ObjectHashTableShape,
3478 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3480 DECLARE_CAST(ObjectHashTable)
3482 // Attempt to shrink hash table after removal of key.
3483 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3484 Handle<ObjectHashTable> table,
3485 Handle<Object> key);
3487 // Looks up the value associated with the given key. The hole value is
3488 // returned in case the key is not present.
3489 Object* Lookup(Handle<Object> key);
3490 Object* Lookup(Handle<Object> key, int32_t hash);
3491 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3493 // Adds (or overwrites) the value associated with the given key.
3494 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3496 Handle<Object> value);
3497 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3498 Handle<Object> key, Handle<Object> value,
3501 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3502 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3505 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3506 Handle<Object> key, bool* was_present,
3510 friend class MarkCompactCollector;
3512 void AddEntry(int entry, Object* key, Object* value);
3513 void RemoveEntry(int entry);
3515 // Returns the index to the value of an entry.
3516 static inline int EntryToValueIndex(int entry) {
3517 return EntryToIndex(entry) + 1;
3522 // OrderedHashTable is a HashTable with Object keys that preserves
3523 // insertion order. There are Map and Set interfaces (OrderedHashMap
3524 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3526 // Only Object* keys are supported, with Object::SameValueZero() used as the
3527 // equality operator and Object::GetHash() for the hash function.
3529 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3530 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3531 // Originally attributed to Tyler Close.
3534 // [0]: bucket count
3535 // [1]: element count
3536 // [2]: deleted element count
3537 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3538 // offset into the data table (see below) where the
3539 // first item in this bucket is stored.
3540 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3541 // Capacity() * kEntrySize, where the first entrysize
3542 // items are handled by the derived class and the
3543 // item at kChainOffset is another entry into the
3544 // data table indicating the next entry in this hash
3547 // When we transition the table to a new version we obsolete it and reuse parts
3548 // of the memory to store information how to transition an iterator to the new
3551 // Memory layout for obsolete table:
3552 // [0]: bucket count
3553 // [1]: Next newer table
3554 // [2]: Number of removed holes or -1 when the table was cleared.
3555 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3556 // [3 + NumberOfRemovedHoles()..length]: Not used
3558 template<class Derived, class Iterator, int entrysize>
3559 class OrderedHashTable: public FixedArray {
3561 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3562 static Handle<Derived> Allocate(
3563 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3565 // Returns an OrderedHashTable (possibly |table|) with enough space
3566 // to add at least one new element.
3567 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3569 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3571 static Handle<Derived> Shrink(Handle<Derived> table);
3573 // Returns a new empty OrderedHashTable and records the clearing so that
3574 // exisiting iterators can be updated.
3575 static Handle<Derived> Clear(Handle<Derived> table);
3577 int NumberOfElements() {
3578 return Smi::cast(get(kNumberOfElementsIndex))->value();
3581 int NumberOfDeletedElements() {
3582 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3585 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3587 int NumberOfBuckets() {
3588 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3591 // Returns an index into |this| for the given entry.
3592 int EntryToIndex(int entry) {
3593 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3596 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3599 return !get(kNextTableIndex)->IsSmi();
3602 // The next newer table. This is only valid if the table is obsolete.
3603 Derived* NextTable() {
3604 return Derived::cast(get(kNextTableIndex));
3607 // When the table is obsolete we store the indexes of the removed holes.
3608 int RemovedIndexAt(int index) {
3609 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3612 static const int kNotFound = -1;
3613 static const int kMinCapacity = 4;
3615 static const int kNumberOfBucketsIndex = 0;
3616 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3617 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3618 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3619 static const int kNextTableIndex = kNumberOfElementsIndex;
3621 static const int kNumberOfBucketsOffset =
3622 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3623 static const int kNumberOfElementsOffset =
3624 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3625 static const int kNumberOfDeletedElementsOffset =
3626 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3627 static const int kHashTableStartOffset =
3628 kHeaderSize + kHashTableStartIndex * kPointerSize;
3629 static const int kNextTableOffset =
3630 kHeaderSize + kNextTableIndex * kPointerSize;
3632 static const int kEntrySize = entrysize + 1;
3633 static const int kChainOffset = entrysize;
3635 static const int kLoadFactor = 2;
3637 // NumberOfDeletedElements is set to kClearedTableSentinel when
3638 // the table is cleared, which allows iterator transitions to
3639 // optimize that case.
3640 static const int kClearedTableSentinel = -1;
3643 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3645 void SetNumberOfBuckets(int num) {
3646 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3649 void SetNumberOfElements(int num) {
3650 set(kNumberOfElementsIndex, Smi::FromInt(num));
3653 void SetNumberOfDeletedElements(int num) {
3654 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3658 return NumberOfBuckets() * kLoadFactor;
3661 void SetNextTable(Derived* next_table) {
3662 set(kNextTableIndex, next_table);
3665 void SetRemovedIndexAt(int index, int removed_index) {
3666 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3669 static const int kRemovedHolesIndex = kHashTableStartIndex;
3671 static const int kMaxCapacity =
3672 (FixedArray::kMaxLength - kHashTableStartIndex)
3673 / (1 + (kEntrySize * kLoadFactor));
3677 class JSSetIterator;
3680 class OrderedHashSet: public OrderedHashTable<
3681 OrderedHashSet, JSSetIterator, 1> {
3683 DECLARE_CAST(OrderedHashSet)
3687 class JSMapIterator;
3690 class OrderedHashMap
3691 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3693 DECLARE_CAST(OrderedHashMap)
3695 inline Object* ValueAt(int entry);
3697 static const int kValueOffset = 1;
3701 template <int entrysize>
3702 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3704 static inline bool IsMatch(Handle<Object> key, Object* other);
3705 static inline uint32_t Hash(Handle<Object> key);
3706 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3707 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3708 static const int kPrefixSize = 0;
3709 static const int kEntrySize = entrysize;
3713 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3714 // values. The table wraps the keys in weak cells and store values directly.
3715 // Thus it references keys weakly and values strongly.
3716 class WeakHashTable: public HashTable<WeakHashTable,
3717 WeakHashTableShape<2>,
3720 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3722 DECLARE_CAST(WeakHashTable)
3724 // Looks up the value associated with the given key. The hole value is
3725 // returned in case the key is not present.
3726 Object* Lookup(Handle<HeapObject> key);
3728 // Adds (or overwrites) the value associated with the given key. Mapping a
3729 // key to the hole value causes removal of the whole entry.
3730 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3731 Handle<HeapObject> key,
3732 Handle<HeapObject> value);
3734 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3737 friend class MarkCompactCollector;
3739 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3741 // Returns the index to the value of an entry.
3742 static inline int EntryToValueIndex(int entry) {
3743 return EntryToIndex(entry) + 1;
3748 // ScopeInfo represents information about different scopes of a source
3749 // program and the allocation of the scope's variables. Scope information
3750 // is stored in a compressed form in ScopeInfo objects and is used
3751 // at runtime (stack dumps, deoptimization, etc.).
3753 // This object provides quick access to scope info details for runtime
3755 class ScopeInfo : public FixedArray {
3757 DECLARE_CAST(ScopeInfo)
3759 // Return the type of this scope.
3760 ScopeType scope_type();
3762 // Does this scope call eval?
3765 // Return the language mode of this scope.
3766 LanguageMode language_mode();
3768 // True if this scope is a (var) declaration scope.
3769 bool is_declaration_scope();
3771 // Does this scope make a sloppy eval call?
3772 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3774 // Return the total number of locals allocated on the stack and in the
3775 // context. This includes the parameters that are allocated in the context.
3778 // Return the number of stack slots for code. This number consists of two
3780 // 1. One stack slot per stack allocated local.
3781 // 2. One stack slot for the function name if it is stack allocated.
3782 int StackSlotCount();
3784 // Return the number of context slots for code if a context is allocated. This
3785 // number consists of three parts:
3786 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3787 // 2. One context slot per context allocated local.
3788 // 3. One context slot for the function name if it is context allocated.
3789 // Parameters allocated in the context count as context allocated locals. If
3790 // no contexts are allocated for this scope ContextLength returns 0.
3791 int ContextLength();
3793 // Does this scope declare a "this" binding?
3796 // Does this scope declare a "this" binding, and the "this" binding is stack-
3797 // or context-allocated?
3798 bool HasAllocatedReceiver();
3800 // Is this scope the scope of a named function expression?
3801 bool HasFunctionName();
3803 // Return if this has context allocated locals.
3804 bool HasHeapAllocatedLocals();
3806 // Return if contexts are allocated for this scope.
3809 // Return if this is a function scope with "use asm".
3810 inline bool IsAsmModule();
3812 // Return if this is a nested function within an asm module scope.
3813 inline bool IsAsmFunction();
3815 inline bool HasSimpleParameters();
3817 // Return the function_name if present.
3818 String* FunctionName();
3820 // Return the name of the given parameter.
3821 String* ParameterName(int var);
3823 // Return the name of the given local.
3824 String* LocalName(int var);
3826 // Return the name of the given stack local.
3827 String* StackLocalName(int var);
3829 // Return the name of the given stack local.
3830 int StackLocalIndex(int var);
3832 // Return the name of the given context local.
3833 String* ContextLocalName(int var);
3835 // Return the mode of the given context local.
3836 VariableMode ContextLocalMode(int var);
3838 // Return the initialization flag of the given context local.
3839 InitializationFlag ContextLocalInitFlag(int var);
3841 // Return the initialization flag of the given context local.
3842 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3844 // Return true if this local was introduced by the compiler, and should not be
3845 // exposed to the user in a debugger.
3846 bool LocalIsSynthetic(int var);
3848 String* StrongModeFreeVariableName(int var);
3849 int StrongModeFreeVariableStartPosition(int var);
3850 int StrongModeFreeVariableEndPosition(int var);
3852 // Lookup support for serialized scope info. Returns the
3853 // the stack slot index for a given slot name if the slot is
3854 // present; otherwise returns a value < 0. The name must be an internalized
3856 int StackSlotIndex(String* name);
3858 // Lookup support for serialized scope info. Returns the
3859 // context slot index for a given slot name if the slot is present; otherwise
3860 // returns a value < 0. The name must be an internalized string.
3861 // If the slot is present and mode != NULL, sets *mode to the corresponding
3862 // mode for that variable.
3863 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3864 VariableMode* mode, VariableLocation* location,
3865 InitializationFlag* init_flag,
3866 MaybeAssignedFlag* maybe_assigned_flag);
3868 // Lookup the name of a certain context slot by its index.
3869 String* ContextSlotName(int slot_index);
3871 // Lookup support for serialized scope info. Returns the
3872 // parameter index for a given parameter name if the parameter is present;
3873 // otherwise returns a value < 0. The name must be an internalized string.
3874 int ParameterIndex(String* name);
3876 // Lookup support for serialized scope info. Returns the function context
3877 // slot index if the function name is present and context-allocated (named
3878 // function expressions, only), otherwise returns a value < 0. The name
3879 // must be an internalized string.
3880 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3882 // Lookup support for serialized scope info. Returns the receiver context
3883 // slot index if scope has a "this" binding, and the binding is
3884 // context-allocated. Otherwise returns a value < 0.
3885 int ReceiverContextSlotIndex();
3887 FunctionKind function_kind();
3889 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3890 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3892 // Serializes empty scope info.
3893 static ScopeInfo* Empty(Isolate* isolate);
3899 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3900 // numeric and occupies one array slot.
3901 // 1. A set of properties of the scope
3902 // 2. The number of parameters. This only applies to function scopes. For
3903 // non-function scopes this is 0.
3904 // 3. The number of non-parameter variables allocated on the stack.
3905 // 4. The number of non-parameter and parameter variables allocated in the
3907 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3910 V(StackLocalCount) \
3911 V(ContextLocalCount) \
3912 V(ContextGlobalCount) \
3913 V(StrongModeFreeVariableCount)
3915 #define FIELD_ACCESSORS(name) \
3916 inline void Set##name(int value); \
3918 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3919 #undef FIELD_ACCESSORS
3923 #define DECL_INDEX(name) k##name,
3924 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3929 // The layout of the variable part of a ScopeInfo is as follows:
3930 // 1. ParameterEntries:
3931 // This part stores the names of the parameters for function scopes. One
3932 // slot is used per parameter, so in total this part occupies
3933 // ParameterCount() slots in the array. For other scopes than function
3934 // scopes ParameterCount() is 0.
3935 // 2. StackLocalFirstSlot:
3936 // Index of a first stack slot for stack local. Stack locals belonging to
3937 // this scope are located on a stack at slots starting from this index.
3938 // 3. StackLocalEntries:
3939 // Contains the names of local variables that are allocated on the stack,
3940 // in increasing order of the stack slot index. First local variable has
3941 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3942 // One slot is used per stack local, so in total this part occupies
3943 // StackLocalCount() slots in the array.
3944 // 4. ContextLocalNameEntries:
3945 // Contains the names of local variables and parameters that are allocated
3946 // in the context. They are stored in increasing order of the context slot
3947 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3948 // context local, so in total this part occupies ContextLocalCount() slots
3950 // 5. ContextLocalInfoEntries:
3951 // Contains the variable modes and initialization flags corresponding to
3952 // the context locals in ContextLocalNameEntries. One slot is used per
3953 // context local, so in total this part occupies ContextLocalCount()
3954 // slots in the array.
3955 // 6. StrongModeFreeVariableNameEntries:
3956 // Stores the names of strong mode free variables.
3957 // 7. StrongModeFreeVariablePositionEntries:
3958 // Stores the locations (start and end position) of strong mode free
3960 // 8. RecieverEntryIndex:
3961 // If the scope binds a "this" value, one slot is reserved to hold the
3962 // context or stack slot index for the variable.
3963 // 9. FunctionNameEntryIndex:
3964 // If the scope belongs to a named function expression this part contains
3965 // information about the function variable. It always occupies two array
3966 // slots: a. The name of the function variable.
3967 // b. The context or stack slot index for the variable.
3968 int ParameterEntriesIndex();
3969 int StackLocalFirstSlotIndex();
3970 int StackLocalEntriesIndex();
3971 int ContextLocalNameEntriesIndex();
3972 int ContextGlobalNameEntriesIndex();
3973 int ContextLocalInfoEntriesIndex();
3974 int ContextGlobalInfoEntriesIndex();
3975 int StrongModeFreeVariableNameEntriesIndex();
3976 int StrongModeFreeVariablePositionEntriesIndex();
3977 int ReceiverEntryIndex();
3978 int FunctionNameEntryIndex();
3980 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3981 VariableLocation* location, InitializationFlag* init_flag,
3982 MaybeAssignedFlag* maybe_assigned_flag);
3984 // Used for the function name variable for named function expressions, and for
3986 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3988 // Properties of scopes.
3989 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3990 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3991 STATIC_ASSERT(LANGUAGE_END == 3);
3992 class LanguageModeField
3993 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
3994 class DeclarationScopeField
3995 : public BitField<bool, LanguageModeField::kNext, 1> {};
3996 class ReceiverVariableField
3997 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
3999 class FunctionVariableField
4000 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4002 class FunctionVariableMode
4003 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4004 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4006 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4007 class HasSimpleParametersField
4008 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4009 class FunctionKindField
4010 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4012 // BitFields representing the encoded information for context locals in the
4013 // ContextLocalInfoEntries part.
4014 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4015 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4016 class ContextLocalMaybeAssignedFlag
4017 : public BitField<MaybeAssignedFlag, 4, 1> {};
4019 friend class ScopeIterator;
4023 // The cache for maps used by normalized (dictionary mode) objects.
4024 // Such maps do not have property descriptors, so a typical program
4025 // needs very limited number of distinct normalized maps.
4026 class NormalizedMapCache: public FixedArray {
4028 static Handle<NormalizedMapCache> New(Isolate* isolate);
4030 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4031 PropertyNormalizationMode mode);
4032 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4036 DECLARE_CAST(NormalizedMapCache)
4038 static inline bool IsNormalizedMapCache(const Object* obj);
4040 DECLARE_VERIFIER(NormalizedMapCache)
4042 static const int kEntries = 64;
4044 static inline int GetIndex(Handle<Map> map);
4046 // The following declarations hide base class methods.
4047 Object* get(int index);
4048 void set(int index, Object* value);
4052 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4053 // that is attached to code objects.
4054 class ByteArray: public FixedArrayBase {
4058 // Setter and getter.
4059 inline byte get(int index);
4060 inline void set(int index, byte value);
4062 // Treat contents as an int array.
4063 inline int get_int(int index);
4065 static int SizeFor(int length) {
4066 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4068 // We use byte arrays for free blocks in the heap. Given a desired size in
4069 // bytes that is a multiple of the word size and big enough to hold a byte
4070 // array, this function returns the number of elements a byte array should
4072 static int LengthFor(int size_in_bytes) {
4073 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4074 DCHECK(size_in_bytes >= kHeaderSize);
4075 return size_in_bytes - kHeaderSize;
4078 // Returns data start address.
4079 inline Address GetDataStartAddress();
4081 // Returns a pointer to the ByteArray object for a given data start address.
4082 static inline ByteArray* FromDataStartAddress(Address address);
4084 DECLARE_CAST(ByteArray)
4086 // Dispatched behavior.
4087 inline int ByteArraySize();
4088 DECLARE_PRINTER(ByteArray)
4089 DECLARE_VERIFIER(ByteArray)
4091 // Layout description.
4092 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4094 // Maximal memory consumption for a single ByteArray.
4095 static const int kMaxSize = 512 * MB;
4096 // Maximal length of a single ByteArray.
4097 static const int kMaxLength = kMaxSize - kHeaderSize;
4100 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4104 // BytecodeArray represents a sequence of interpreter bytecodes.
4105 class BytecodeArray : public FixedArrayBase {
4107 static int SizeFor(int length) {
4108 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4111 // Setter and getter
4112 inline byte get(int index);
4113 inline void set(int index, byte value);
4115 // Returns data start address.
4116 inline Address GetFirstBytecodeAddress();
4118 // Accessors for frame size.
4119 inline int frame_size() const;
4120 inline void set_frame_size(int frame_size);
4122 // Accessors for parameter count (including implicit 'this' receiver).
4123 inline int parameter_count() const;
4124 inline void set_parameter_count(int number_of_parameters);
4126 // Accessors for the constant pool.
4127 DECL_ACCESSORS(constant_pool, FixedArray)
4129 DECLARE_CAST(BytecodeArray)
4131 // Dispatched behavior.
4132 inline int BytecodeArraySize();
4133 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4135 DECLARE_PRINTER(BytecodeArray)
4136 DECLARE_VERIFIER(BytecodeArray)
4138 void Disassemble(std::ostream& os);
4140 // Layout description.
4141 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4142 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4143 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4144 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4146 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4148 // Maximal memory consumption for a single BytecodeArray.
4149 static const int kMaxSize = 512 * MB;
4150 // Maximal length of a single BytecodeArray.
4151 static const int kMaxLength = kMaxSize - kHeaderSize;
4154 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4158 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4159 // They look like heap objects (are heap object tagged and have a map) so that
4160 // the heap remains iterable. They have a size and a next pointer.
4161 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4162 // in the free list.
4163 class FreeSpace: public HeapObject {
4165 // [size]: size of the free space including the header.
4166 inline int size() const;
4167 inline void set_size(int value);
4169 inline int nobarrier_size() const;
4170 inline void nobarrier_set_size(int value);
4174 // Accessors for the next field.
4175 inline FreeSpace* next();
4176 inline FreeSpace** next_address();
4177 inline void set_next(FreeSpace* next);
4179 inline static FreeSpace* cast(HeapObject* obj);
4181 // Dispatched behavior.
4182 DECLARE_PRINTER(FreeSpace)
4183 DECLARE_VERIFIER(FreeSpace)
4185 // Layout description.
4186 // Size is smi tagged when it is stored.
4187 static const int kSizeOffset = HeapObject::kHeaderSize;
4188 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4191 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4195 // V has parameters (Type, type, TYPE, C type, element_size)
4196 #define TYPED_ARRAYS(V) \
4197 V(Uint8, uint8, UINT8, uint8_t, 1) \
4198 V(Int8, int8, INT8, int8_t, 1) \
4199 V(Uint16, uint16, UINT16, uint16_t, 2) \
4200 V(Int16, int16, INT16, int16_t, 2) \
4201 V(Uint32, uint32, UINT32, uint32_t, 4) \
4202 V(Int32, int32, INT32, int32_t, 4) \
4203 V(Float32, float32, FLOAT32, float, 4) \
4204 V(Float64, float64, FLOAT64, double, 8) \
4205 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4208 class FixedTypedArrayBase: public FixedArrayBase {
4210 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4211 DECL_ACCESSORS(base_pointer, Object)
4213 // [external_pointer]: Contains the offset between base_pointer and the start
4214 // of the data. If the base_pointer is a nullptr, the external_pointer
4215 // therefore points to the actual backing store.
4216 DECL_ACCESSORS(external_pointer, void)
4218 // Dispatched behavior.
4219 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4221 template <typename StaticVisitor>
4222 inline void FixedTypedArrayBaseIterateBody();
4224 DECLARE_CAST(FixedTypedArrayBase)
4226 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4227 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4228 static const int kHeaderSize =
4229 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4231 static const int kDataOffset = kHeaderSize;
4235 static inline int TypedArraySize(InstanceType type, int length);
4236 inline int TypedArraySize(InstanceType type);
4238 // Use with care: returns raw pointer into heap.
4239 inline void* DataPtr();
4241 inline int DataSize();
4244 static inline int ElementSize(InstanceType type);
4246 inline int DataSize(InstanceType type);
4248 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4252 template <class Traits>
4253 class FixedTypedArray: public FixedTypedArrayBase {
4255 typedef typename Traits::ElementType ElementType;
4256 static const InstanceType kInstanceType = Traits::kInstanceType;
4258 DECLARE_CAST(FixedTypedArray<Traits>)
4260 inline ElementType get_scalar(int index);
4261 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4262 inline void set(int index, ElementType value);
4264 static inline ElementType from_int(int value);
4265 static inline ElementType from_double(double value);
4267 // This accessor applies the correct conversion from Smi, HeapNumber
4269 void SetValue(uint32_t index, Object* value);
4271 DECLARE_PRINTER(FixedTypedArray)
4272 DECLARE_VERIFIER(FixedTypedArray)
4275 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4278 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4279 class Type##ArrayTraits { \
4280 public: /* NOLINT */ \
4281 typedef elementType ElementType; \
4282 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4283 static const char* Designator() { return #type " array"; } \
4284 static inline Handle<Object> ToHandle(Isolate* isolate, \
4285 elementType scalar); \
4286 static inline elementType defaultValue(); \
4289 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4291 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4293 #undef FIXED_TYPED_ARRAY_TRAITS
4296 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4297 // data for code generated by the Hydrogen/Lithium compiler. It also
4298 // contains information about functions that were inlined. If N different
4299 // functions were inlined then first N elements of the literal array will
4300 // contain these functions.
4303 class DeoptimizationInputData: public FixedArray {
4305 // Layout description. Indices in the array.
4306 static const int kTranslationByteArrayIndex = 0;
4307 static const int kInlinedFunctionCountIndex = 1;
4308 static const int kLiteralArrayIndex = 2;
4309 static const int kOsrAstIdIndex = 3;
4310 static const int kOsrPcOffsetIndex = 4;
4311 static const int kOptimizationIdIndex = 5;
4312 static const int kSharedFunctionInfoIndex = 6;
4313 static const int kWeakCellCacheIndex = 7;
4314 static const int kFirstDeoptEntryIndex = 8;
4316 // Offsets of deopt entry elements relative to the start of the entry.
4317 static const int kAstIdRawOffset = 0;
4318 static const int kTranslationIndexOffset = 1;
4319 static const int kArgumentsStackHeightOffset = 2;
4320 static const int kPcOffset = 3;
4321 static const int kDeoptEntrySize = 4;
4323 // Simple element accessors.
4324 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4325 inline type* name(); \
4326 inline void Set##name(type* value);
4328 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4329 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4330 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4331 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4332 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4333 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4334 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4335 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4337 #undef DECLARE_ELEMENT_ACCESSORS
4339 // Accessors for elements of the ith deoptimization entry.
4340 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4341 inline type* name(int i); \
4342 inline void Set##name(int i, type* value);
4344 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4345 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4346 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4347 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4349 #undef DECLARE_ENTRY_ACCESSORS
4351 inline BailoutId AstId(int i);
4353 inline void SetAstId(int i, BailoutId value);
4355 inline int DeoptCount();
4357 // Allocates a DeoptimizationInputData.
4358 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4359 int deopt_entry_count,
4360 PretenureFlag pretenure);
4362 DECLARE_CAST(DeoptimizationInputData)
4364 #ifdef ENABLE_DISASSEMBLER
4365 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4369 static int IndexForEntry(int i) {
4370 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4374 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4378 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4379 // data for code generated by the full compiler.
4380 // The format of the these objects is
4381 // [i * 2]: Ast ID for ith deoptimization.
4382 // [i * 2 + 1]: PC and state of ith deoptimization
4383 class DeoptimizationOutputData: public FixedArray {
4385 inline int DeoptPoints();
4387 inline BailoutId AstId(int index);
4389 inline void SetAstId(int index, BailoutId id);
4391 inline Smi* PcAndState(int index);
4392 inline void SetPcAndState(int index, Smi* offset);
4394 static int LengthOfFixedArray(int deopt_points) {
4395 return deopt_points * 2;
4398 // Allocates a DeoptimizationOutputData.
4399 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4400 int number_of_deopt_points,
4401 PretenureFlag pretenure);
4403 DECLARE_CAST(DeoptimizationOutputData)
4405 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4406 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4411 // HandlerTable is a fixed array containing entries for exception handlers in
4412 // the code object it is associated with. The tables comes in two flavors:
4413 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4414 // exception handler and a range representing the try-block covered by that
4415 // handler. Layout looks as follows:
4416 // [ range-start , range-end , handler-offset , stack-depth ]
4417 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4418 // per call-site that could throw an exception. Layout looks as follows:
4419 // [ return-address-offset , handler-offset ]
4420 class HandlerTable : public FixedArray {
4422 // Conservative prediction whether a given handler will locally catch an
4423 // exception or cause a re-throw to outside the code boundary. Since this is
4424 // undecidable it is merely an approximation (e.g. useful for debugger).
4425 enum CatchPrediction { UNCAUGHT, CAUGHT };
4427 // Accessors for handler table based on ranges.
4428 inline void SetRangeStart(int index, int value);
4429 inline void SetRangeEnd(int index, int value);
4430 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4431 inline void SetRangeDepth(int index, int value);
4433 // Accessors for handler table based on return addresses.
4434 inline void SetReturnOffset(int index, int value);
4435 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4437 // Lookup handler in a table based on ranges.
4438 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4440 // Lookup handler in a table based on return addresses.
4441 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4443 // Returns the required length of the underlying fixed array.
4444 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4445 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4447 DECLARE_CAST(HandlerTable)
4449 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4450 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4451 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4455 // Layout description for handler table based on ranges.
4456 static const int kRangeStartIndex = 0;
4457 static const int kRangeEndIndex = 1;
4458 static const int kRangeHandlerIndex = 2;
4459 static const int kRangeDepthIndex = 3;
4460 static const int kRangeEntrySize = 4;
4462 // Layout description for handler table based on return addresses.
4463 static const int kReturnOffsetIndex = 0;
4464 static const int kReturnHandlerIndex = 1;
4465 static const int kReturnEntrySize = 2;
4467 // Encoding of the {handler} field.
4468 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4469 class HandlerOffsetField : public BitField<int, 1, 30> {};
4473 // Code describes objects with on-the-fly generated machine code.
4474 class Code: public HeapObject {
4476 // Opaque data type for encapsulating code flags like kind, inline
4477 // cache state, and arguments count.
4478 typedef uint32_t Flags;
4480 #define NON_IC_KIND_LIST(V) \
4482 V(OPTIMIZED_FUNCTION) \
4489 #define IC_KIND_LIST(V) \
4500 #define CODE_KIND_LIST(V) \
4501 NON_IC_KIND_LIST(V) \
4505 #define DEFINE_CODE_KIND_ENUM(name) name,
4506 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4507 #undef DEFINE_CODE_KIND_ENUM
4511 // No more than 16 kinds. The value is currently encoded in four bits in
4513 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4515 static const char* Kind2String(Kind kind);
4523 static const int kPrologueOffsetNotSet = -1;
4525 #ifdef ENABLE_DISASSEMBLER
4527 static const char* ICState2String(InlineCacheState state);
4528 static const char* StubType2String(StubType type);
4529 static void PrintExtraICState(std::ostream& os, // NOLINT
4530 Kind kind, ExtraICState extra);
4531 void Disassemble(const char* name, std::ostream& os); // NOLINT
4532 #endif // ENABLE_DISASSEMBLER
4534 // [instruction_size]: Size of the native instructions
4535 inline int instruction_size() const;
4536 inline void set_instruction_size(int value);
4538 // [relocation_info]: Code relocation information
4539 DECL_ACCESSORS(relocation_info, ByteArray)
4540 void InvalidateRelocation();
4541 void InvalidateEmbeddedObjects();
4543 // [handler_table]: Fixed array containing offsets of exception handlers.
4544 DECL_ACCESSORS(handler_table, FixedArray)
4546 // [deoptimization_data]: Array containing data for deopt.
4547 DECL_ACCESSORS(deoptimization_data, FixedArray)
4549 // [raw_type_feedback_info]: This field stores various things, depending on
4550 // the kind of the code object.
4551 // FUNCTION => type feedback information.
4552 // STUB and ICs => major/minor key as Smi.
4553 DECL_ACCESSORS(raw_type_feedback_info, Object)
4554 inline Object* type_feedback_info();
4555 inline void set_type_feedback_info(
4556 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4557 inline uint32_t stub_key();
4558 inline void set_stub_key(uint32_t key);
4560 // [next_code_link]: Link for lists of optimized or deoptimized code.
4561 // Note that storage for this field is overlapped with typefeedback_info.
4562 DECL_ACCESSORS(next_code_link, Object)
4564 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4565 // field does not have to be traced during garbage collection since
4566 // it is only used by the garbage collector itself.
4567 DECL_ACCESSORS(gc_metadata, Object)
4569 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4570 // at the moment when this object was created.
4571 inline void set_ic_age(int count);
4572 inline int ic_age() const;
4574 // [prologue_offset]: Offset of the function prologue, used for aging
4575 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4576 inline int prologue_offset() const;
4577 inline void set_prologue_offset(int offset);
4579 // [constant_pool offset]: Offset of the constant pool.
4580 // Valid for FLAG_enable_embedded_constant_pool only
4581 inline int constant_pool_offset() const;
4582 inline void set_constant_pool_offset(int offset);
4584 // Unchecked accessors to be used during GC.
4585 inline ByteArray* unchecked_relocation_info();
4587 inline int relocation_size();
4589 // [flags]: Various code flags.
4590 inline Flags flags();
4591 inline void set_flags(Flags flags);
4593 // [flags]: Access to specific code flags.
4595 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4596 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4598 inline StubType type(); // Only valid for monomorphic IC stubs.
4600 // Testers for IC stub kinds.
4601 inline bool is_inline_cache_stub();
4602 inline bool is_debug_stub();
4603 inline bool is_handler();
4604 inline bool is_load_stub();
4605 inline bool is_keyed_load_stub();
4606 inline bool is_store_stub();
4607 inline bool is_keyed_store_stub();
4608 inline bool is_call_stub();
4609 inline bool is_binary_op_stub();
4610 inline bool is_compare_ic_stub();
4611 inline bool is_compare_nil_ic_stub();
4612 inline bool is_to_boolean_ic_stub();
4613 inline bool is_keyed_stub();
4614 inline bool is_optimized_code();
4615 inline bool embeds_maps_weakly();
4617 inline bool IsCodeStubOrIC();
4618 inline bool IsJavaScriptCode();
4620 inline void set_raw_kind_specific_flags1(int value);
4621 inline void set_raw_kind_specific_flags2(int value);
4623 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4624 // object was generated by either the hydrogen or the TurboFan optimizing
4625 // compiler (but it may not be an optimized function).
4626 inline bool is_crankshafted();
4627 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4628 inline void set_is_crankshafted(bool value);
4630 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4631 // code object was generated by the TurboFan optimizing compiler.
4632 inline bool is_turbofanned();
4633 inline void set_is_turbofanned(bool value);
4635 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4636 // embedded objects in code should be treated weakly.
4637 inline bool can_have_weak_objects();
4638 inline void set_can_have_weak_objects(bool value);
4640 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4641 // deoptimization support.
4642 inline bool has_deoptimization_support();
4643 inline void set_has_deoptimization_support(bool value);
4645 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4646 // been compiled with debug break slots.
4647 inline bool has_debug_break_slots();
4648 inline void set_has_debug_break_slots(bool value);
4650 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4651 // reloc info includes runtime and external references to support
4652 // serialization/deserialization.
4653 inline bool has_reloc_info_for_serialization();
4654 inline void set_has_reloc_info_for_serialization(bool value);
4656 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4657 // how long the function has been marked for OSR and therefore which
4658 // level of loop nesting we are willing to do on-stack replacement
4660 inline void set_allow_osr_at_loop_nesting_level(int level);
4661 inline int allow_osr_at_loop_nesting_level();
4663 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4664 // the code object was seen on the stack with no IC patching going on.
4665 inline int profiler_ticks();
4666 inline void set_profiler_ticks(int ticks);
4668 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4669 // For builtins, tells which builtin index it has.
4670 // Note that builtins can have a code kind other than BUILTIN, which means
4671 // that for arbitrary code objects, this index value may be random garbage.
4672 // To verify in that case, compare the code object to the indexed builtin.
4673 inline int builtin_index();
4674 inline void set_builtin_index(int id);
4676 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4677 // reserved in the code prologue.
4678 inline unsigned stack_slots();
4679 inline void set_stack_slots(unsigned slots);
4681 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4682 // the instruction stream where the safepoint table starts.
4683 inline unsigned safepoint_table_offset();
4684 inline void set_safepoint_table_offset(unsigned offset);
4686 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4687 // instruction stream where the back edge table starts.
4688 inline unsigned back_edge_table_offset();
4689 inline void set_back_edge_table_offset(unsigned offset);
4691 inline bool back_edges_patched_for_osr();
4693 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4694 inline uint16_t to_boolean_state();
4696 // [has_function_cache]: For kind STUB tells whether there is a function
4697 // cache is passed to the stub.
4698 inline bool has_function_cache();
4699 inline void set_has_function_cache(bool flag);
4702 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4703 // the code is going to be deoptimized because of dead embedded maps.
4704 inline bool marked_for_deoptimization();
4705 inline void set_marked_for_deoptimization(bool flag);
4707 // [constant_pool]: The constant pool for this function.
4708 inline Address constant_pool();
4710 // Get the safepoint entry for the given pc.
4711 SafepointEntry GetSafepointEntry(Address pc);
4713 // Find an object in a stub with a specified map
4714 Object* FindNthObject(int n, Map* match_map);
4716 // Find the first allocation site in an IC stub.
4717 AllocationSite* FindFirstAllocationSite();
4719 // Find the first map in an IC stub.
4720 Map* FindFirstMap();
4721 void FindAllMaps(MapHandleList* maps);
4723 // Find the first handler in an IC stub.
4724 Code* FindFirstHandler();
4726 // Find |length| handlers and put them into |code_list|. Returns false if not
4727 // enough handlers can be found.
4728 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4730 // Find the handler for |map|.
4731 MaybeHandle<Code> FindHandlerForMap(Map* map);
4733 // Find the first name in an IC stub.
4734 Name* FindFirstName();
4736 class FindAndReplacePattern;
4737 // For each (map-to-find, object-to-replace) pair in the pattern, this
4738 // function replaces the corresponding placeholder in the code with the
4739 // object-to-replace. The function assumes that pairs in the pattern come in
4740 // the same order as the placeholders in the code.
4741 // If the placeholder is a weak cell, then the value of weak cell is matched
4742 // against the map-to-find.
4743 void FindAndReplace(const FindAndReplacePattern& pattern);
4745 // The entire code object including its header is copied verbatim to the
4746 // snapshot so that it can be written in one, fast, memcpy during
4747 // deserialization. The deserializer will overwrite some pointers, rather
4748 // like a runtime linker, but the random allocation addresses used in the
4749 // mksnapshot process would still be present in the unlinked snapshot data,
4750 // which would make snapshot production non-reproducible. This method wipes
4751 // out the to-be-overwritten header data for reproducible snapshots.
4752 inline void WipeOutHeader();
4754 // Flags operations.
4755 static inline Flags ComputeFlags(
4756 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4757 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4758 CacheHolderFlag holder = kCacheOnReceiver);
4760 static inline Flags ComputeMonomorphicFlags(
4761 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4762 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4764 static inline Flags ComputeHandlerFlags(
4765 Kind handler_kind, StubType type = NORMAL,
4766 CacheHolderFlag holder = kCacheOnReceiver);
4768 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4769 static inline StubType ExtractTypeFromFlags(Flags flags);
4770 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4771 static inline Kind ExtractKindFromFlags(Flags flags);
4772 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4774 static inline Flags RemoveTypeFromFlags(Flags flags);
4775 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4777 // Convert a target address into a code object.
4778 static inline Code* GetCodeFromTargetAddress(Address address);
4780 // Convert an entry address into an object.
4781 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4783 // Returns the address of the first instruction.
4784 inline byte* instruction_start();
4786 // Returns the address right after the last instruction.
4787 inline byte* instruction_end();
4789 // Returns the size of the instructions, padding, and relocation information.
4790 inline int body_size();
4792 // Returns the address of the first relocation info (read backwards!).
4793 inline byte* relocation_start();
4795 // Code entry point.
4796 inline byte* entry();
4798 // Returns true if pc is inside this object's instructions.
4799 inline bool contains(byte* pc);
4801 // Relocate the code by delta bytes. Called to signal that this code
4802 // object has been moved by delta bytes.
4803 void Relocate(intptr_t delta);
4805 // Migrate code described by desc.
4806 void CopyFrom(const CodeDesc& desc);
4808 // Returns the object size for a given body (used for allocation).
4809 static int SizeFor(int body_size) {
4810 DCHECK_SIZE_TAG_ALIGNED(body_size);
4811 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4814 // Calculate the size of the code object to report for log events. This takes
4815 // the layout of the code object into account.
4816 inline int ExecutableSize();
4818 // Locating source position.
4819 int SourcePosition(Address pc);
4820 int SourceStatementPosition(Address pc);
4824 // Dispatched behavior.
4825 inline int CodeSize();
4826 inline void CodeIterateBody(ObjectVisitor* v);
4828 template<typename StaticVisitor>
4829 inline void CodeIterateBody(Heap* heap);
4831 DECLARE_PRINTER(Code)
4832 DECLARE_VERIFIER(Code)
4834 void ClearInlineCaches();
4835 void ClearInlineCaches(Kind kind);
4837 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4838 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4840 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4842 kToBeExecutedOnceCodeAge = -3,
4843 kNotExecutedCodeAge = -2,
4844 kExecutedOnceCodeAge = -1,
4846 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4848 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4849 kLastCodeAge = kAfterLastCodeAge - 1,
4850 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4851 kIsOldCodeAge = kSexagenarianCodeAge,
4852 kPreAgedCodeAge = kIsOldCodeAge - 1
4854 #undef DECLARE_CODE_AGE_ENUM
4856 // Code aging. Indicates how many full GCs this code has survived without
4857 // being entered through the prologue. Used to determine when it is
4858 // relatively safe to flush this code object and replace it with the lazy
4859 // compilation stub.
4860 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4861 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4862 void MakeYoung(Isolate* isolate);
4863 void MarkToBeExecutedOnce(Isolate* isolate);
4864 void MakeOlder(MarkingParity);
4865 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4868 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4869 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4872 void PrintDeoptLocation(FILE* out, Address pc);
4873 bool CanDeoptAt(Address pc);
4876 void VerifyEmbeddedObjectsDependency();
4880 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4881 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4882 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4885 inline bool CanContainWeakObjects();
4887 inline bool IsWeakObject(Object* object);
4889 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4891 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4892 WeakCell* CachedWeakCell();
4894 // Max loop nesting marker used to postpose OSR. We don't take loop
4895 // nesting that is deeper than 5 levels into account.
4896 static const int kMaxLoopNestingMarker = 6;
4898 static const int kConstantPoolSize =
4899 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4901 // Layout description.
4902 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4903 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4904 static const int kDeoptimizationDataOffset =
4905 kHandlerTableOffset + kPointerSize;
4906 // For FUNCTION kind, we store the type feedback info here.
4907 static const int kTypeFeedbackInfoOffset =
4908 kDeoptimizationDataOffset + kPointerSize;
4909 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4910 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4911 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4912 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4913 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4914 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4915 static const int kKindSpecificFlags2Offset =
4916 kKindSpecificFlags1Offset + kIntSize;
4917 // Note: We might be able to squeeze this into the flags above.
4918 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4919 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4920 static const int kHeaderPaddingStart =
4921 kConstantPoolOffset + kConstantPoolSize;
4923 // Add padding to align the instruction start following right after
4924 // the Code object header.
4925 static const int kHeaderSize =
4926 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4928 // Byte offsets within kKindSpecificFlags1Offset.
4929 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4930 class FullCodeFlagsHasDeoptimizationSupportField:
4931 public BitField<bool, 0, 1> {}; // NOLINT
4932 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4933 class FullCodeFlagsHasRelocInfoForSerialization
4934 : public BitField<bool, 2, 1> {};
4935 // Bit 3 in this bitfield is unused.
4936 class ProfilerTicksField : public BitField<int, 4, 28> {};
4938 // Flags layout. BitField<type, shift, size>.
4939 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4940 class TypeField : public BitField<StubType, 4, 1> {};
4941 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4942 class KindField : public BitField<Kind, 7, 4> {};
4943 class ExtraICStateField: public BitField<ExtraICState, 11,
4944 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4946 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4947 static const int kStackSlotsFirstBit = 0;
4948 static const int kStackSlotsBitCount = 24;
4949 static const int kHasFunctionCacheBit =
4950 kStackSlotsFirstBit + kStackSlotsBitCount;
4951 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4952 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4953 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4955 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4956 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4958 class StackSlotsField: public BitField<int,
4959 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4960 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4962 class MarkedForDeoptimizationField
4963 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4964 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4966 class CanHaveWeakObjectsField
4967 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4969 // KindSpecificFlags2 layout (ALL)
4970 static const int kIsCrankshaftedBit = 0;
4971 class IsCrankshaftedField: public BitField<bool,
4972 kIsCrankshaftedBit, 1> {}; // NOLINT
4974 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4975 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4976 static const int kSafepointTableOffsetBitCount = 30;
4978 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4979 kSafepointTableOffsetBitCount <= 32);
4980 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4982 class SafepointTableOffsetField: public BitField<int,
4983 kSafepointTableOffsetFirstBit,
4984 kSafepointTableOffsetBitCount> {}; // NOLINT
4986 // KindSpecificFlags2 layout (FUNCTION)
4987 class BackEdgeTableOffsetField: public BitField<int,
4988 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4989 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4990 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4991 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4993 static const int kArgumentsBits = 16;
4994 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4996 // This constant should be encodable in an ARM instruction.
4997 static const int kFlagsNotUsedInLookup =
4998 TypeField::kMask | CacheHolderField::kMask;
5001 friend class RelocIterator;
5002 friend class Deoptimizer; // For FindCodeAgeSequence.
5004 void ClearInlineCaches(Kind* kind);
5007 byte* FindCodeAgeSequence();
5008 static void GetCodeAgeAndParity(Code* code, Age* age,
5009 MarkingParity* parity);
5010 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5011 MarkingParity* parity);
5012 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5014 // Code aging -- platform-specific
5015 static void PatchPlatformCodeAge(Isolate* isolate,
5016 byte* sequence, Age age,
5017 MarkingParity parity);
5019 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5023 // This class describes the layout of dependent codes array of a map. The
5024 // array is partitioned into several groups of dependent codes. Each group
5025 // contains codes with the same dependency on the map. The array has the
5026 // following layout for n dependency groups:
5028 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5029 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5030 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5032 // The first n elements are Smis, each of them specifies the number of codes
5033 // in the corresponding group. The subsequent elements contain grouped code
5034 // objects in weak cells. The suffix of the array can be filled with the
5035 // undefined value if the number of codes is less than the length of the
5036 // array. The order of the code objects within a group is not preserved.
5038 // All code indexes used in the class are counted starting from the first
5039 // code object of the first group. In other words, code index 0 corresponds
5040 // to array index n = kCodesStartIndex.
5042 class DependentCode: public FixedArray {
5044 enum DependencyGroup {
5045 // Group of code that weakly embed this map and depend on being
5046 // deoptimized when the map is garbage collected.
5048 // Group of code that embed a transition to this map, and depend on being
5049 // deoptimized when the transition is replaced by a new version.
5051 // Group of code that omit run-time prototype checks for prototypes
5052 // described by this map. The group is deoptimized whenever an object
5053 // described by this map changes shape (and transitions to a new map),
5054 // possibly invalidating the assumptions embedded in the code.
5055 kPrototypeCheckGroup,
5056 // Group of code that depends on global property values in property cells
5057 // not being changed.
5058 kPropertyCellChangedGroup,
5059 // Group of code that omit run-time type checks for the field(s) introduced
5062 // Group of code that omit run-time type checks for initial maps of
5064 kInitialMapChangedGroup,
5065 // Group of code that depends on tenuring information in AllocationSites
5066 // not being changed.
5067 kAllocationSiteTenuringChangedGroup,
5068 // Group of code that depends on element transition information in
5069 // AllocationSites not being changed.
5070 kAllocationSiteTransitionChangedGroup
5073 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5075 // Array for holding the index of the first code object of each group.
5076 // The last element stores the total number of code objects.
5077 class GroupStartIndexes {
5079 explicit GroupStartIndexes(DependentCode* entries);
5080 void Recompute(DependentCode* entries);
5081 int at(int i) { return start_indexes_[i]; }
5082 int number_of_entries() { return start_indexes_[kGroupCount]; }
5084 int start_indexes_[kGroupCount + 1];
5087 bool Contains(DependencyGroup group, WeakCell* code_cell);
5089 static Handle<DependentCode> InsertCompilationDependencies(
5090 Handle<DependentCode> entries, DependencyGroup group,
5091 Handle<Foreign> info);
5093 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5094 DependencyGroup group,
5095 Handle<WeakCell> code_cell);
5097 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5098 WeakCell* code_cell);
5100 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5103 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5104 DependentCode::DependencyGroup group);
5106 bool MarkCodeForDeoptimization(Isolate* isolate,
5107 DependentCode::DependencyGroup group);
5109 // The following low-level accessors should only be used by this class
5110 // and the mark compact collector.
5111 inline int number_of_entries(DependencyGroup group);
5112 inline void set_number_of_entries(DependencyGroup group, int value);
5113 inline Object* object_at(int i);
5114 inline void set_object_at(int i, Object* object);
5115 inline void clear_at(int i);
5116 inline void copy(int from, int to);
5117 DECLARE_CAST(DependentCode)
5119 static const char* DependencyGroupName(DependencyGroup group);
5120 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5123 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5124 DependencyGroup group,
5125 Handle<Object> object);
5126 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5127 // Make a room at the end of the given group by moving out the first
5128 // code objects of the subsequent groups.
5129 inline void ExtendGroup(DependencyGroup group);
5130 // Compact by removing cleared weak cells and return true if there was
5131 // any cleared weak cell.
5133 static int Grow(int number_of_entries) {
5134 if (number_of_entries < 5) return number_of_entries + 1;
5135 return number_of_entries * 5 / 4;
5137 static const int kCodesStartIndex = kGroupCount;
5141 class PrototypeInfo;
5144 // All heap objects have a Map that describes their structure.
5145 // A Map contains information about:
5146 // - Size information about the object
5147 // - How to iterate over an object (for garbage collection)
5148 class Map: public HeapObject {
5151 // Size in bytes or kVariableSizeSentinel if instances do not have
5153 inline int instance_size();
5154 inline void set_instance_size(int value);
5156 // Only to clear an unused byte, remove once byte is used.
5157 inline void clear_unused();
5159 // [inobject_properties_or_constructor_function_index]: Provides access
5160 // to the inobject properties in case of JSObject maps, or the constructor
5161 // function index in case of primitive maps.
5162 inline int inobject_properties_or_constructor_function_index();
5163 inline void set_inobject_properties_or_constructor_function_index(int value);
5164 // Count of properties allocated in the object (JSObject only).
5165 inline int GetInObjectProperties();
5166 inline void SetInObjectProperties(int value);
5167 // Index of the constructor function in the native context (primitives only),
5168 // or the special sentinel value to indicate that there is no object wrapper
5169 // for the primitive (i.e. in case of null or undefined).
5170 static const int kNoConstructorFunctionIndex = 0;
5171 inline int GetConstructorFunctionIndex();
5172 inline void SetConstructorFunctionIndex(int value);
5175 inline InstanceType instance_type();
5176 inline void set_instance_type(InstanceType value);
5178 // Tells how many unused property fields are available in the
5179 // instance (only used for JSObject in fast mode).
5180 inline int unused_property_fields();
5181 inline void set_unused_property_fields(int value);
5184 inline byte bit_field() const;
5185 inline void set_bit_field(byte value);
5188 inline byte bit_field2() const;
5189 inline void set_bit_field2(byte value);
5192 inline uint32_t bit_field3() const;
5193 inline void set_bit_field3(uint32_t bits);
5195 class EnumLengthBits: public BitField<int,
5196 0, kDescriptorIndexBitCount> {}; // NOLINT
5197 class NumberOfOwnDescriptorsBits: public BitField<int,
5198 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5199 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5200 class DictionaryMap : public BitField<bool, 20, 1> {};
5201 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5202 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5203 class Deprecated : public BitField<bool, 23, 1> {};
5204 class IsUnstable : public BitField<bool, 24, 1> {};
5205 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5206 class IsStrong : public BitField<bool, 26, 1> {};
5209 // Keep this bit field at the very end for better code in
5210 // Builtins::kJSConstructStubGeneric stub.
5211 // This counter is used for in-object slack tracking and for map aging.
5212 // The in-object slack tracking is considered enabled when the counter is
5213 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5214 class Counter : public BitField<int, 28, 4> {};
5215 static const int kSlackTrackingCounterStart = 14;
5216 static const int kSlackTrackingCounterEnd = 8;
5217 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5218 static const int kRetainingCounterEnd = 0;
5220 // Tells whether the object in the prototype property will be used
5221 // for instances created from this function. If the prototype
5222 // property is set to a value that is not a JSObject, the prototype
5223 // property will not be used to create instances of the function.
5224 // See ECMA-262, 13.2.2.
5225 inline void set_non_instance_prototype(bool value);
5226 inline bool has_non_instance_prototype();
5228 // Tells whether function has special prototype property. If not, prototype
5229 // property will not be created when accessed (will return undefined),
5230 // and construction from this function will not be allowed.
5231 inline void set_function_with_prototype(bool value);
5232 inline bool function_with_prototype();
5234 // Tells whether the instance with this map should be ignored by the
5235 // Object.getPrototypeOf() function and the __proto__ accessor.
5236 inline void set_is_hidden_prototype();
5237 inline bool is_hidden_prototype();
5239 // Records and queries whether the instance has a named interceptor.
5240 inline void set_has_named_interceptor();
5241 inline bool has_named_interceptor();
5243 // Records and queries whether the instance has an indexed interceptor.
5244 inline void set_has_indexed_interceptor();
5245 inline bool has_indexed_interceptor();
5247 // Tells whether the instance is undetectable.
5248 // An undetectable object is a special class of JSObject: 'typeof' operator
5249 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5250 // a normal JS object. It is useful for implementing undetectable
5251 // document.all in Firefox & Safari.
5252 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5253 inline void set_is_undetectable();
5254 inline bool is_undetectable();
5256 // Tells whether the instance has a call-as-function handler.
5257 inline void set_is_observed();
5258 inline bool is_observed();
5260 inline void set_is_strong();
5261 inline bool is_strong();
5262 inline void set_is_extensible(bool value);
5263 inline bool is_extensible();
5264 inline void set_is_prototype_map(bool value);
5265 inline bool is_prototype_map() const;
5267 inline void set_elements_kind(ElementsKind elements_kind);
5268 inline ElementsKind elements_kind();
5270 // Tells whether the instance has fast elements that are only Smis.
5271 inline bool has_fast_smi_elements();
5273 // Tells whether the instance has fast elements.
5274 inline bool has_fast_object_elements();
5275 inline bool has_fast_smi_or_object_elements();
5276 inline bool has_fast_double_elements();
5277 inline bool has_fast_elements();
5278 inline bool has_sloppy_arguments_elements();
5279 inline bool has_fixed_typed_array_elements();
5280 inline bool has_dictionary_elements();
5282 static bool IsValidElementsTransition(ElementsKind from_kind,
5283 ElementsKind to_kind);
5285 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5286 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5287 bool DictionaryElementsInPrototypeChainOnly();
5289 inline Map* ElementsTransitionMap();
5291 inline FixedArrayBase* GetInitialElements();
5293 // [raw_transitions]: Provides access to the transitions storage field.
5294 // Don't call set_raw_transitions() directly to overwrite transitions, use
5295 // the TransitionArray::ReplaceTransitions() wrapper instead!
5296 DECL_ACCESSORS(raw_transitions, Object)
5297 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5298 // (which prototype maps don't have).
5299 DECL_ACCESSORS(prototype_info, Object)
5300 // PrototypeInfo is created lazily using this helper (which installs it on
5301 // the given prototype's map).
5302 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5303 Handle<JSObject> prototype, Isolate* isolate);
5304 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5305 Handle<Map> prototype_map, Isolate* isolate);
5307 // [prototype chain validity cell]: Associated with a prototype object,
5308 // stored in that object's map's PrototypeInfo, indicates that prototype
5309 // chains through this object are currently valid. The cell will be
5310 // invalidated and replaced when the prototype chain changes.
5311 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5313 static const int kPrototypeChainValid = 0;
5314 static const int kPrototypeChainInvalid = 1;
5317 Map* FindFieldOwner(int descriptor);
5319 inline int GetInObjectPropertyOffset(int index);
5321 int NumberOfFields();
5323 // TODO(ishell): candidate with JSObject::MigrateToMap().
5324 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5325 int target_inobject, int target_unused,
5326 int* old_number_of_fields);
5327 // TODO(ishell): moveit!
5328 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5329 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5330 Handle<HeapType> type1,
5331 Handle<HeapType> type2,
5333 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5334 Representation new_representation,
5335 Handle<HeapType> new_field_type);
5336 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5337 PropertyKind new_kind,
5338 PropertyAttributes new_attributes,
5339 Representation new_representation,
5340 Handle<HeapType> new_field_type,
5341 StoreMode store_mode);
5342 static Handle<Map> CopyGeneralizeAllRepresentations(
5343 Handle<Map> map, int modify_index, StoreMode store_mode,
5344 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5346 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5347 int descriptor_number,
5348 Handle<Object> value);
5350 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5351 const char* reason);
5353 // Returns the constructor name (the name (possibly, inferred name) of the
5354 // function that was used to instantiate the object).
5355 String* constructor_name();
5357 // Tells whether the map is used for JSObjects in dictionary mode (ie
5358 // normalized objects, ie objects for which HasFastProperties returns false).
5359 // A map can never be used for both dictionary mode and fast mode JSObjects.
5360 // False by default and for HeapObjects that are not JSObjects.
5361 inline void set_dictionary_map(bool value);
5362 inline bool is_dictionary_map();
5364 // Tells whether the instance needs security checks when accessing its
5366 inline void set_is_access_check_needed(bool access_check_needed);
5367 inline bool is_access_check_needed();
5369 // Returns true if map has a non-empty stub code cache.
5370 inline bool has_code_cache();
5372 // [prototype]: implicit prototype object.
5373 DECL_ACCESSORS(prototype, Object)
5374 // TODO(jkummerow): make set_prototype private.
5375 static void SetPrototype(
5376 Handle<Map> map, Handle<Object> prototype,
5377 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5379 // [constructor]: points back to the function responsible for this map.
5380 // The field overlaps with the back pointer. All maps in a transition tree
5381 // have the same constructor, so maps with back pointers can walk the
5382 // back pointer chain until they find the map holding their constructor.
5383 DECL_ACCESSORS(constructor_or_backpointer, Object)
5384 inline Object* GetConstructor() const;
5385 inline void SetConstructor(Object* constructor,
5386 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5387 // [back pointer]: points back to the parent map from which a transition
5388 // leads to this map. The field overlaps with the constructor (see above).
5389 inline Object* GetBackPointer();
5390 inline void SetBackPointer(Object* value,
5391 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5393 // [instance descriptors]: describes the object.
5394 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5396 // [layout descriptor]: describes the object layout.
5397 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5398 // |layout descriptor| accessor which can be used from GC.
5399 inline LayoutDescriptor* layout_descriptor_gc_safe();
5400 inline bool HasFastPointerLayout() const;
5402 // |layout descriptor| accessor that is safe to call even when
5403 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5404 // |layout_descriptor| field at all).
5405 inline LayoutDescriptor* GetLayoutDescriptor();
5407 inline void UpdateDescriptors(DescriptorArray* descriptors,
5408 LayoutDescriptor* layout_descriptor);
5409 inline void InitializeDescriptors(DescriptorArray* descriptors,
5410 LayoutDescriptor* layout_descriptor);
5412 // [stub cache]: contains stubs compiled for this map.
5413 DECL_ACCESSORS(code_cache, Object)
5415 // [dependent code]: list of optimized codes that weakly embed this map.
5416 DECL_ACCESSORS(dependent_code, DependentCode)
5418 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5419 DECL_ACCESSORS(weak_cell_cache, Object)
5421 inline PropertyDetails GetLastDescriptorDetails();
5423 inline int LastAdded();
5425 inline int NumberOfOwnDescriptors();
5426 inline void SetNumberOfOwnDescriptors(int number);
5428 inline Cell* RetrieveDescriptorsPointer();
5430 inline int EnumLength();
5431 inline void SetEnumLength(int length);
5433 inline bool owns_descriptors();
5434 inline void set_owns_descriptors(bool owns_descriptors);
5435 inline bool has_instance_call_handler();
5436 inline void set_has_instance_call_handler();
5437 inline void mark_unstable();
5438 inline bool is_stable();
5439 inline void set_migration_target(bool value);
5440 inline bool is_migration_target();
5441 inline void set_counter(int value);
5442 inline int counter();
5443 inline void deprecate();
5444 inline bool is_deprecated();
5445 inline bool CanBeDeprecated();
5446 // Returns a non-deprecated version of the input. If the input was not
5447 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5448 // is found by re-transitioning from the root of the transition tree using the
5449 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5451 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5453 // Returns a non-deprecated version of the input. This method may deprecate
5454 // existing maps along the way if encodings conflict. Not for use while
5455 // gathering type feedback. Use TryUpdate in those cases instead.
5456 static Handle<Map> Update(Handle<Map> map);
5458 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5459 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5460 Descriptor* descriptor,
5461 TransitionFlag flag);
5463 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5466 Handle<HeapType> type,
5467 PropertyAttributes attributes,
5468 Representation representation,
5469 TransitionFlag flag);
5471 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5474 Handle<Object> constant,
5475 PropertyAttributes attributes,
5476 TransitionFlag flag);
5478 // Returns a new map with all transitions dropped from the given map and
5479 // the ElementsKind set.
5480 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5481 ElementsKind to_kind);
5483 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5485 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5487 TransitionFlag flag);
5489 static Handle<Map> CopyForObserved(Handle<Map> map);
5491 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5492 PropertyAttributes attrs_to_add,
5493 Handle<Symbol> transition_marker,
5494 const char* reason);
5496 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5499 // Maximal number of fast properties. Used to restrict the number of map
5500 // transitions to avoid an explosion in the number of maps for objects used as
5502 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5503 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5505 Handle<Object> value,
5506 PropertyAttributes attributes,
5507 StoreFromKeyed store_mode);
5508 static Handle<Map> TransitionToAccessorProperty(
5509 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5510 Handle<Object> accessor, PropertyAttributes attributes);
5511 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5514 PropertyAttributes attributes);
5516 inline void AppendDescriptor(Descriptor* desc);
5518 // Returns a copy of the map, prepared for inserting into the transition
5519 // tree (if the |map| owns descriptors then the new one will share
5520 // descriptors with |map|).
5521 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5523 // Returns a copy of the map, with all transitions dropped from the
5524 // instance descriptors.
5525 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5526 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5528 // Returns the next free property index (only valid for FAST MODE).
5529 int NextFreePropertyIndex();
5531 // Returns the number of properties described in instance_descriptors
5532 // filtering out properties with the specified attributes.
5533 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5534 PropertyAttributes filter = NONE);
5538 // Code cache operations.
5540 // Clears the code cache.
5541 inline void ClearCodeCache(Heap* heap);
5543 // Update code cache.
5544 static void UpdateCodeCache(Handle<Map> map,
5548 // Extend the descriptor array of the map with the list of descriptors.
5549 // In case of duplicates, the latest descriptor is used.
5550 static void AppendCallbackDescriptors(Handle<Map> map,
5551 Handle<Object> descriptors);
5553 static inline int SlackForArraySize(int old_size, int size_limit);
5555 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5557 // Returns the found code or undefined if absent.
5558 Object* FindInCodeCache(Name* name, Code::Flags flags);
5560 // Returns the non-negative index of the code object if it is in the
5561 // cache and -1 otherwise.
5562 int IndexInCodeCache(Object* name, Code* code);
5564 // Removes a code object from the code cache at the given index.
5565 void RemoveFromCodeCache(Name* name, Code* code, int index);
5567 // Computes a hash value for this map, to be used in HashTables and such.
5570 // Returns the map that this map transitions to if its elements_kind
5571 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5572 // |safe_to_add_transitions| is set to false if adding transitions is not
5574 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5576 // Returns the transitioned map for this map with the most generic
5577 // elements_kind that's found in |candidates|, or null handle if no match is
5579 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5580 MapHandleList* candidates);
5582 inline bool CanTransition();
5584 inline bool IsPrimitiveMap();
5585 inline bool IsJSObjectMap();
5586 inline bool IsJSArrayMap();
5587 inline bool IsStringMap();
5588 inline bool IsJSProxyMap();
5589 inline bool IsJSGlobalProxyMap();
5590 inline bool IsJSGlobalObjectMap();
5591 inline bool IsGlobalObjectMap();
5593 inline bool CanOmitMapChecks();
5595 static void AddDependentCode(Handle<Map> map,
5596 DependentCode::DependencyGroup group,
5599 bool IsMapInArrayPrototypeChain();
5601 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5603 // Dispatched behavior.
5604 DECLARE_PRINTER(Map)
5605 DECLARE_VERIFIER(Map)
5608 void DictionaryMapVerify();
5609 void VerifyOmittedMapChecks();
5612 inline int visitor_id();
5613 inline void set_visitor_id(int visitor_id);
5615 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5616 Handle<Object> prototype,
5617 PrototypeOptimizationMode mode);
5619 static const int kMaxPreAllocatedPropertyFields = 255;
5621 // Layout description.
5622 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5623 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5624 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5625 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5626 static const int kConstructorOrBackPointerOffset =
5627 kPrototypeOffset + kPointerSize;
5628 // When there is only one transition, it is stored directly in this field;
5629 // otherwise a transition array is used.
5630 // For prototype maps, this slot is used to store this map's PrototypeInfo
5632 static const int kTransitionsOrPrototypeInfoOffset =
5633 kConstructorOrBackPointerOffset + kPointerSize;
5634 static const int kDescriptorsOffset =
5635 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5636 #if V8_DOUBLE_FIELDS_UNBOXING
5637 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5638 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5640 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5641 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5643 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5644 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5645 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5647 // Layout of pointer fields. Heap iteration code relies on them
5648 // being continuously allocated.
5649 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5650 static const int kPointerFieldsEndOffset = kSize;
5652 // Byte offsets within kInstanceSizesOffset.
5653 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5654 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5655 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5656 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5657 // Note there is one byte available for use here.
5658 static const int kUnusedByte = 2;
5659 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5660 static const int kVisitorIdByte = 3;
5661 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5663 // Byte offsets within kInstanceAttributesOffset attributes.
5664 #if V8_TARGET_LITTLE_ENDIAN
5665 // Order instance type and bit field together such that they can be loaded
5666 // together as a 16-bit word with instance type in the lower 8 bits regardless
5667 // of endianess. Also provide endian-independent offset to that 16-bit word.
5668 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5669 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5671 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5672 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5674 static const int kInstanceTypeAndBitFieldOffset =
5675 kInstanceAttributesOffset + 0;
5676 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5677 static const int kUnusedPropertyFieldsByte = 3;
5678 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5680 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5681 Internals::kMapInstanceTypeAndBitFieldOffset);
5683 // Bit positions for bit field.
5684 static const int kHasNonInstancePrototype = 0;
5685 static const int kIsHiddenPrototype = 1;
5686 static const int kHasNamedInterceptor = 2;
5687 static const int kHasIndexedInterceptor = 3;
5688 static const int kIsUndetectable = 4;
5689 static const int kIsObserved = 5;
5690 static const int kIsAccessCheckNeeded = 6;
5691 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5693 // Bit positions for bit field 2
5694 static const int kIsExtensible = 0;
5695 static const int kStringWrapperSafeForDefaultValueOf = 1;
5696 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5697 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5699 // Derived values from bit field 2
5700 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5701 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5702 static const int8_t kMaximumBitField2FastSmiElementValue =
5703 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5704 Map::ElementsKindBits::kShift) - 1;
5705 static const int8_t kMaximumBitField2FastHoleyElementValue =
5706 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5707 Map::ElementsKindBits::kShift) - 1;
5708 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5709 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5710 Map::ElementsKindBits::kShift) - 1;
5712 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5713 kPointerFieldsEndOffset,
5714 kSize> BodyDescriptor;
5716 // Compares this map to another to see if they describe equivalent objects.
5717 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5718 // it had exactly zero inobject properties.
5719 // The "shared" flags of both this map and |other| are ignored.
5720 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5722 // Returns true if given field is unboxed double.
5723 inline bool IsUnboxedDoubleField(FieldIndex index);
5726 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5727 static void TraceAllTransitions(Map* map);
5730 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5731 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5732 Handle<LayoutDescriptor> layout_descriptor);
5735 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5736 Handle<Name> name, SimpleTransitionFlag flag);
5738 bool EquivalentToForTransition(Map* other);
5739 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5740 static Handle<Map> ShareDescriptor(Handle<Map> map,
5741 Handle<DescriptorArray> descriptors,
5742 Descriptor* descriptor);
5743 static Handle<Map> CopyInstallDescriptors(
5744 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5745 Handle<LayoutDescriptor> layout_descriptor);
5746 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5747 Descriptor* descriptor,
5748 TransitionFlag flag);
5749 static Handle<Map> CopyReplaceDescriptors(
5750 Handle<Map> map, Handle<DescriptorArray> descriptors,
5751 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5752 MaybeHandle<Name> maybe_name, const char* reason,
5753 SimpleTransitionFlag simple_flag);
5755 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5756 Handle<DescriptorArray> descriptors,
5757 Descriptor* descriptor,
5759 TransitionFlag flag);
5760 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5761 Handle<Map> map, int descriptor, PropertyKind kind,
5762 PropertyAttributes attributes, const char** reason);
5764 static Handle<Map> CopyNormalized(Handle<Map> map,
5765 PropertyNormalizationMode mode);
5767 // Fires when the layout of an object with a leaf map changes.
5768 // This includes adding transitions to the leaf map or changing
5769 // the descriptor array.
5770 inline void NotifyLeafMapLayoutChange();
5772 void DeprecateTransitionTree();
5773 bool DeprecateTarget(PropertyKind kind, Name* key,
5774 PropertyAttributes attributes,
5775 DescriptorArray* new_descriptors,
5776 LayoutDescriptor* new_layout_descriptor);
5778 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5780 // Update field type of the given descriptor to new representation and new
5781 // type. The type must be prepared for storing in descriptor array:
5782 // it must be either a simple type or a map wrapped in a weak cell.
5783 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5784 Representation new_representation,
5785 Handle<Object> new_wrapped_type);
5787 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5788 PropertyAttributes attributes);
5789 void PrintGeneralization(FILE* file,
5794 bool constant_to_field,
5795 Representation old_representation,
5796 Representation new_representation,
5797 HeapType* old_field_type,
5798 HeapType* new_field_type);
5800 static const int kFastPropertiesSoftLimit = 12;
5801 static const int kMaxFastProperties = 128;
5803 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5807 // An abstract superclass, a marker class really, for simple structure classes.
5808 // It doesn't carry much functionality but allows struct classes to be
5809 // identified in the type system.
5810 class Struct: public HeapObject {
5812 inline void InitializeBody(int object_size);
5813 DECLARE_CAST(Struct)
5817 // A simple one-element struct, useful where smis need to be boxed.
5818 class Box : public Struct {
5820 // [value]: the boxed contents.
5821 DECL_ACCESSORS(value, Object)
5825 // Dispatched behavior.
5826 DECLARE_PRINTER(Box)
5827 DECLARE_VERIFIER(Box)
5829 static const int kValueOffset = HeapObject::kHeaderSize;
5830 static const int kSize = kValueOffset + kPointerSize;
5833 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5837 // Container for metadata stored on each prototype map.
5838 class PrototypeInfo : public Struct {
5840 static const int UNREGISTERED = -1;
5842 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5843 // or Smi(0) if uninitialized.
5844 DECL_ACCESSORS(prototype_users, Object)
5845 // [registry_slot]: Slot in prototype's user registry where this user
5846 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5847 inline int registry_slot() const;
5848 inline void set_registry_slot(int slot);
5849 // [validity_cell]: Cell containing the validity bit for prototype chains
5850 // going through this object, or Smi(0) if uninitialized.
5851 DECL_ACCESSORS(validity_cell, Object)
5852 // [constructor_name]: User-friendly name of the original constructor.
5853 DECL_ACCESSORS(constructor_name, Object)
5855 DECLARE_CAST(PrototypeInfo)
5857 // Dispatched behavior.
5858 DECLARE_PRINTER(PrototypeInfo)
5859 DECLARE_VERIFIER(PrototypeInfo)
5861 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5862 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5863 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5864 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5865 static const int kSize = kConstructorNameOffset + kPointerSize;
5868 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5872 // Pair used to store both a ScopeInfo and an extension object in the extension
5873 // slot of a block context. Needed in the rare case where a declaration block
5874 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5875 // a sloppy direct eval. (In no other case both are needed at the same time.)
5876 class SloppyBlockWithEvalContextExtension : public Struct {
5878 // [scope_info]: Scope info.
5879 DECL_ACCESSORS(scope_info, ScopeInfo)
5880 // [extension]: Extension object.
5881 DECL_ACCESSORS(extension, JSObject)
5883 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5885 // Dispatched behavior.
5886 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5887 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5889 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5890 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5891 static const int kSize = kExtensionOffset + kPointerSize;
5894 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5898 // Script describes a script which has been added to the VM.
5899 class Script: public Struct {
5908 // Script compilation types.
5909 enum CompilationType {
5910 COMPILATION_TYPE_HOST = 0,
5911 COMPILATION_TYPE_EVAL = 1
5914 // Script compilation state.
5915 enum CompilationState {
5916 COMPILATION_STATE_INITIAL = 0,
5917 COMPILATION_STATE_COMPILED = 1
5920 // [source]: the script source.
5921 DECL_ACCESSORS(source, Object)
5923 // [name]: the script name.
5924 DECL_ACCESSORS(name, Object)
5926 // [id]: the script id.
5927 DECL_ACCESSORS(id, Smi)
5929 // [line_offset]: script line offset in resource from where it was extracted.
5930 DECL_ACCESSORS(line_offset, Smi)
5932 // [column_offset]: script column offset in resource from where it was
5934 DECL_ACCESSORS(column_offset, Smi)
5936 // [context_data]: context data for the context this script was compiled in.
5937 DECL_ACCESSORS(context_data, Object)
5939 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5940 DECL_ACCESSORS(wrapper, HeapObject)
5942 // [type]: the script type.
5943 DECL_ACCESSORS(type, Smi)
5945 // [line_ends]: FixedArray of line ends positions.
5946 DECL_ACCESSORS(line_ends, Object)
5948 // [eval_from_shared]: for eval scripts the shared funcion info for the
5949 // function from which eval was called.
5950 DECL_ACCESSORS(eval_from_shared, Object)
5952 // [eval_from_instructions_offset]: the instruction offset in the code for the
5953 // function from which eval was called where eval was called.
5954 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5956 // [shared_function_infos]: weak fixed array containing all shared
5957 // function infos created from this script.
5958 DECL_ACCESSORS(shared_function_infos, Object)
5960 // [flags]: Holds an exciting bitfield.
5961 DECL_ACCESSORS(flags, Smi)
5963 // [source_url]: sourceURL from magic comment
5964 DECL_ACCESSORS(source_url, Object)
5966 // [source_url]: sourceMappingURL magic comment
5967 DECL_ACCESSORS(source_mapping_url, Object)
5969 // [compilation_type]: how the the script was compiled. Encoded in the
5971 inline CompilationType compilation_type();
5972 inline void set_compilation_type(CompilationType type);
5974 // [compilation_state]: determines whether the script has already been
5975 // compiled. Encoded in the 'flags' field.
5976 inline CompilationState compilation_state();
5977 inline void set_compilation_state(CompilationState state);
5979 // [hide_source]: determines whether the script source can be exposed as
5980 // function source. Encoded in the 'flags' field.
5981 inline bool hide_source();
5982 inline void set_hide_source(bool value);
5984 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5985 // and used by the embedder to make decisions about the script. V8 just passes
5986 // this through. Encoded in the 'flags' field.
5987 inline v8::ScriptOriginOptions origin_options();
5988 inline void set_origin_options(ScriptOriginOptions origin_options);
5990 DECLARE_CAST(Script)
5992 // If script source is an external string, check that the underlying
5993 // resource is accessible. Otherwise, always return true.
5994 inline bool HasValidSource();
5996 // Convert code position into column number.
5997 static int GetColumnNumber(Handle<Script> script, int code_pos);
5999 // Convert code position into (zero-based) line number.
6000 // The non-handlified version does not allocate, but may be much slower.
6001 static int GetLineNumber(Handle<Script> script, int code_pos);
6002 int GetLineNumber(int code_pos);
6004 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6006 // Init line_ends array with code positions of line ends inside script source.
6007 static void InitLineEnds(Handle<Script> script);
6009 // Get the JS object wrapping the given script; create it if none exists.
6010 static Handle<JSObject> GetWrapper(Handle<Script> script);
6012 // Look through the list of existing shared function infos to find one
6013 // that matches the function literal. Return empty handle if not found.
6014 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6016 // Iterate over all script objects on the heap.
6019 explicit Iterator(Isolate* isolate);
6023 WeakFixedArray::Iterator iterator_;
6024 DISALLOW_COPY_AND_ASSIGN(Iterator);
6027 // Dispatched behavior.
6028 DECLARE_PRINTER(Script)
6029 DECLARE_VERIFIER(Script)
6031 static const int kSourceOffset = HeapObject::kHeaderSize;
6032 static const int kNameOffset = kSourceOffset + kPointerSize;
6033 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6034 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6035 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6036 static const int kWrapperOffset = kContextOffset + kPointerSize;
6037 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6038 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6039 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6040 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6041 static const int kEvalFrominstructionsOffsetOffset =
6042 kEvalFromSharedOffset + kPointerSize;
6043 static const int kSharedFunctionInfosOffset =
6044 kEvalFrominstructionsOffsetOffset + kPointerSize;
6045 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6046 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6047 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6048 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6051 int GetLineNumberWithArray(int code_pos);
6053 // Bit positions in the flags field.
6054 static const int kCompilationTypeBit = 0;
6055 static const int kCompilationStateBit = 1;
6056 static const int kHideSourceBit = 2;
6057 static const int kOriginOptionsShift = 3;
6058 static const int kOriginOptionsSize = 3;
6059 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6060 << kOriginOptionsShift;
6062 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6066 // List of builtin functions we want to identify to improve code
6069 // Each entry has a name of a global object property holding an object
6070 // optionally followed by ".prototype", a name of a builtin function
6071 // on the object (the one the id is set for), and a label.
6073 // Installation of ids for the selected builtin functions is handled
6074 // by the bootstrapper.
6075 #define FUNCTIONS_WITH_ID_LIST(V) \
6076 V(Array.prototype, indexOf, ArrayIndexOf) \
6077 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6078 V(Array.prototype, push, ArrayPush) \
6079 V(Array.prototype, pop, ArrayPop) \
6080 V(Array.prototype, shift, ArrayShift) \
6081 V(Function.prototype, apply, FunctionApply) \
6082 V(Function.prototype, call, FunctionCall) \
6083 V(String.prototype, charCodeAt, StringCharCodeAt) \
6084 V(String.prototype, charAt, StringCharAt) \
6085 V(String, fromCharCode, StringFromCharCode) \
6086 V(Math, random, MathRandom) \
6087 V(Math, floor, MathFloor) \
6088 V(Math, round, MathRound) \
6089 V(Math, ceil, MathCeil) \
6090 V(Math, abs, MathAbs) \
6091 V(Math, log, MathLog) \
6092 V(Math, exp, MathExp) \
6093 V(Math, sqrt, MathSqrt) \
6094 V(Math, pow, MathPow) \
6095 V(Math, max, MathMax) \
6096 V(Math, min, MathMin) \
6097 V(Math, cos, MathCos) \
6098 V(Math, sin, MathSin) \
6099 V(Math, tan, MathTan) \
6100 V(Math, acos, MathAcos) \
6101 V(Math, asin, MathAsin) \
6102 V(Math, atan, MathAtan) \
6103 V(Math, atan2, MathAtan2) \
6104 V(Math, imul, MathImul) \
6105 V(Math, clz32, MathClz32) \
6106 V(Math, fround, MathFround)
6108 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6109 V(Atomics, load, AtomicsLoad) \
6110 V(Atomics, store, AtomicsStore)
6112 enum BuiltinFunctionId {
6114 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6116 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6117 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6118 #undef DECLARE_FUNCTION_ID
6119 // Fake id for a special case of Math.pow. Note, it continues the
6120 // list of math functions.
6125 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6126 // that both {code} and {literals} can be NULL to pass search result status.
6127 struct CodeAndLiterals {
6128 Code* code; // Cached optimized code.
6129 FixedArray* literals; // Cached literals array.
6133 // SharedFunctionInfo describes the JSFunction information that can be
6134 // shared by multiple instances of the function.
6135 class SharedFunctionInfo: public HeapObject {
6137 // [name]: Function name.
6138 DECL_ACCESSORS(name, Object)
6140 // [code]: Function code.
6141 DECL_ACCESSORS(code, Code)
6142 inline void ReplaceCode(Code* code);
6144 // [optimized_code_map]: Map from native context to optimized code
6145 // and a shared literals array or Smi(0) if none.
6146 DECL_ACCESSORS(optimized_code_map, Object)
6148 // Returns entry from optimized code map for specified context and OSR entry.
6149 // Note that {code == nullptr} indicates no matching entry has been found,
6150 // whereas {literals == nullptr} indicates the code is context-independent.
6151 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6152 BailoutId osr_ast_id);
6154 // Clear optimized code map.
6155 void ClearOptimizedCodeMap();
6157 // Removed a specific optimized code object from the optimized code map.
6158 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6160 // Trims the optimized code map after entries have been removed.
6161 void TrimOptimizedCodeMap(int shrink_by);
6163 // Add a new entry to the optimized code map for context-independent code.
6164 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6167 // Add a new entry to the optimized code map for context-dependent code.
6168 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6169 Handle<Context> native_context,
6171 Handle<FixedArray> literals,
6172 BailoutId osr_ast_id);
6174 // Set up the link between shared function info and the script. The shared
6175 // function info is added to the list on the script.
6176 static void SetScript(Handle<SharedFunctionInfo> shared,
6177 Handle<Object> script_object);
6179 // Layout description of the optimized code map.
6180 static const int kNextMapIndex = 0;
6181 static const int kSharedCodeIndex = 1;
6182 static const int kEntriesStart = 2;
6183 static const int kContextOffset = 0;
6184 static const int kCachedCodeOffset = 1;
6185 static const int kLiteralsOffset = 2;
6186 static const int kOsrAstIdOffset = 3;
6187 static const int kEntryLength = 4;
6188 static const int kInitialLength = kEntriesStart + kEntryLength;
6190 // [scope_info]: Scope info.
6191 DECL_ACCESSORS(scope_info, ScopeInfo)
6193 // [construct stub]: Code stub for constructing instances of this function.
6194 DECL_ACCESSORS(construct_stub, Code)
6196 // Returns if this function has been compiled to native code yet.
6197 inline bool is_compiled();
6199 // [length]: The function length - usually the number of declared parameters.
6200 // Use up to 2^30 parameters.
6201 inline int length() const;
6202 inline void set_length(int value);
6204 // [internal formal parameter count]: The declared number of parameters.
6205 // For subclass constructors, also includes new.target.
6206 // The size of function's frame is internal_formal_parameter_count + 1.
6207 inline int internal_formal_parameter_count() const;
6208 inline void set_internal_formal_parameter_count(int value);
6210 // Set the formal parameter count so the function code will be
6211 // called without using argument adaptor frames.
6212 inline void DontAdaptArguments();
6214 // [expected_nof_properties]: Expected number of properties for the function.
6215 inline int expected_nof_properties() const;
6216 inline void set_expected_nof_properties(int value);
6218 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6219 // (increasingly) from crankshafted code where sufficient feedback isn't
6221 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6223 // Unconditionally clear the type feedback vector (including vector ICs).
6224 void ClearTypeFeedbackInfo();
6226 // Clear the type feedback vector with a more subtle policy at GC time.
6227 void ClearTypeFeedbackInfoAtGCTime();
6230 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6231 // even if the GC moves this SharedFunctionInfo.
6232 inline int unique_id() const;
6233 inline void set_unique_id(int value);
6236 // [instance class name]: class name for instances.
6237 DECL_ACCESSORS(instance_class_name, Object)
6239 // [function data]: This field holds some additional data for function.
6240 // Currently it has one of:
6241 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6242 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6243 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6244 // In the long run we don't want all functions to have this field but
6245 // we can fix that when we have a better model for storing hidden data
6247 DECL_ACCESSORS(function_data, Object)
6249 inline bool IsApiFunction();
6250 inline FunctionTemplateInfo* get_api_func_data();
6251 inline bool HasBuiltinFunctionId();
6252 inline BuiltinFunctionId builtin_function_id();
6253 inline bool HasBytecodeArray();
6254 inline BytecodeArray* bytecode_array();
6256 // [script info]: Script from which the function originates.
6257 DECL_ACCESSORS(script, Object)
6259 // [num_literals]: Number of literals used by this function.
6260 inline int num_literals() const;
6261 inline void set_num_literals(int value);
6263 // [start_position_and_type]: Field used to store both the source code
6264 // position, whether or not the function is a function expression,
6265 // and whether or not the function is a toplevel function. The two
6266 // least significants bit indicates whether the function is an
6267 // expression and the rest contains the source code position.
6268 inline int start_position_and_type() const;
6269 inline void set_start_position_and_type(int value);
6271 // The function is subject to debugging if a debug info is attached.
6272 inline bool HasDebugInfo();
6273 inline DebugInfo* GetDebugInfo();
6275 // A function has debug code if the compiled code has debug break slots.
6276 inline bool HasDebugCode();
6278 // [debug info]: Debug information.
6279 DECL_ACCESSORS(debug_info, Object)
6281 // [inferred name]: Name inferred from variable or property
6282 // assignment of this function. Used to facilitate debugging and
6283 // profiling of JavaScript code written in OO style, where almost
6284 // all functions are anonymous but are assigned to object
6286 DECL_ACCESSORS(inferred_name, String)
6288 // The function's name if it is non-empty, otherwise the inferred name.
6289 String* DebugName();
6291 // Position of the 'function' token in the script source.
6292 inline int function_token_position() const;
6293 inline void set_function_token_position(int function_token_position);
6295 // Position of this function in the script source.
6296 inline int start_position() const;
6297 inline void set_start_position(int start_position);
6299 // End position of this function in the script source.
6300 inline int end_position() const;
6301 inline void set_end_position(int end_position);
6303 // Is this function a function expression in the source code.
6304 DECL_BOOLEAN_ACCESSORS(is_expression)
6306 // Is this function a top-level function (scripts, evals).
6307 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6309 // Bit field containing various information collected by the compiler to
6310 // drive optimization.
6311 inline int compiler_hints() const;
6312 inline void set_compiler_hints(int value);
6314 inline int ast_node_count() const;
6315 inline void set_ast_node_count(int count);
6317 inline int profiler_ticks() const;
6318 inline void set_profiler_ticks(int ticks);
6320 // Inline cache age is used to infer whether the function survived a context
6321 // disposal or not. In the former case we reset the opt_count.
6322 inline int ic_age();
6323 inline void set_ic_age(int age);
6325 // Indicates if this function can be lazy compiled.
6326 // This is used to determine if we can safely flush code from a function
6327 // when doing GC if we expect that the function will no longer be used.
6328 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6330 // Indicates if this function can be lazy compiled without a context.
6331 // This is used to determine if we can force compilation without reaching
6332 // the function through program execution but through other means (e.g. heap
6333 // iteration by the debugger).
6334 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6336 // Indicates whether optimizations have been disabled for this
6337 // shared function info. If a function is repeatedly optimized or if
6338 // we cannot optimize the function we disable optimization to avoid
6339 // spending time attempting to optimize it again.
6340 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6342 // Indicates the language mode.
6343 inline LanguageMode language_mode();
6344 inline void set_language_mode(LanguageMode language_mode);
6346 // False if the function definitely does not allocate an arguments object.
6347 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6349 // Indicates that this function uses a super property (or an eval that may
6350 // use a super property).
6351 // This is needed to set up the [[HomeObject]] on the function instance.
6352 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6354 // True if the function has any duplicated parameter names.
6355 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6357 // Indicates whether the function is a native function.
6358 // These needs special treatment in .call and .apply since
6359 // null passed as the receiver should not be translated to the
6361 DECL_BOOLEAN_ACCESSORS(native)
6363 // Indicate that this function should always be inlined in optimized code.
6364 DECL_BOOLEAN_ACCESSORS(force_inline)
6366 // Indicates that the function was created by the Function function.
6367 // Though it's anonymous, toString should treat it as if it had the name
6368 // "anonymous". We don't set the name itself so that the system does not
6369 // see a binding for it.
6370 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6372 // Indicates whether the function is a bound function created using
6373 // the bind function.
6374 DECL_BOOLEAN_ACCESSORS(bound)
6376 // Indicates that the function is anonymous (the name field can be set
6377 // through the API, which does not change this flag).
6378 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6380 // Is this a function or top-level/eval code.
6381 DECL_BOOLEAN_ACCESSORS(is_function)
6383 // Indicates that code for this function cannot be compiled with Crankshaft.
6384 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6386 // Indicates that code for this function cannot be flushed.
6387 DECL_BOOLEAN_ACCESSORS(dont_flush)
6389 // Indicates that this function is a generator.
6390 DECL_BOOLEAN_ACCESSORS(is_generator)
6392 // Indicates that this function is an arrow function.
6393 DECL_BOOLEAN_ACCESSORS(is_arrow)
6395 // Indicates that this function is a concise method.
6396 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6398 // Indicates that this function is an accessor (getter or setter).
6399 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6401 // Indicates that this function is a default constructor.
6402 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6404 // Indicates that this function is an asm function.
6405 DECL_BOOLEAN_ACCESSORS(asm_function)
6407 // Indicates that the the shared function info is deserialized from cache.
6408 DECL_BOOLEAN_ACCESSORS(deserialized)
6410 // Indicates that the the shared function info has never been compiled before.
6411 DECL_BOOLEAN_ACCESSORS(never_compiled)
6413 inline FunctionKind kind();
6414 inline void set_kind(FunctionKind kind);
6416 // Indicates whether or not the code in the shared function support
6418 inline bool has_deoptimization_support();
6420 // Enable deoptimization support through recompiled code.
6421 void EnableDeoptimizationSupport(Code* recompiled);
6423 // Disable (further) attempted optimization of all functions sharing this
6424 // shared function info.
6425 void DisableOptimization(BailoutReason reason);
6427 inline BailoutReason disable_optimization_reason();
6429 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6430 // code, returns whether it asserted (i.e., always true if assertions are
6432 bool VerifyBailoutId(BailoutId id);
6434 // [source code]: Source code for the function.
6435 bool HasSourceCode() const;
6436 Handle<Object> GetSourceCode();
6438 // Number of times the function was optimized.
6439 inline int opt_count();
6440 inline void set_opt_count(int opt_count);
6442 // Number of times the function was deoptimized.
6443 inline void set_deopt_count(int value);
6444 inline int deopt_count();
6445 inline void increment_deopt_count();
6447 // Number of time we tried to re-enable optimization after it
6448 // was disabled due to high number of deoptimizations.
6449 inline void set_opt_reenable_tries(int value);
6450 inline int opt_reenable_tries();
6452 inline void TryReenableOptimization();
6454 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6455 inline void set_counters(int value);
6456 inline int counters() const;
6458 // Stores opt_count and bailout_reason as bit-fields.
6459 inline void set_opt_count_and_bailout_reason(int value);
6460 inline int opt_count_and_bailout_reason() const;
6462 inline void set_disable_optimization_reason(BailoutReason reason);
6464 // Tells whether this function should be subject to debugging.
6465 inline bool IsSubjectToDebugging();
6467 // Whether this function is defined in native code or extensions.
6468 inline bool IsBuiltin();
6470 // Check whether or not this function is inlineable.
6471 bool IsInlineable();
6473 // Source size of this function.
6476 // Calculate the instance size.
6477 int CalculateInstanceSize();
6479 // Calculate the number of in-object properties.
6480 int CalculateInObjectProperties();
6482 inline bool has_simple_parameters();
6484 // Initialize a SharedFunctionInfo from a parsed function literal.
6485 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6486 FunctionLiteral* lit);
6488 // Dispatched behavior.
6489 DECLARE_PRINTER(SharedFunctionInfo)
6490 DECLARE_VERIFIER(SharedFunctionInfo)
6492 void ResetForNewContext(int new_ic_age);
6494 // Iterate over all shared function infos that are created from a script.
6495 // That excludes shared function infos created for API functions and C++
6499 explicit Iterator(Isolate* isolate);
6500 SharedFunctionInfo* Next();
6505 Script::Iterator script_iterator_;
6506 WeakFixedArray::Iterator sfi_iterator_;
6507 DisallowHeapAllocation no_gc_;
6508 DISALLOW_COPY_AND_ASSIGN(Iterator);
6511 DECLARE_CAST(SharedFunctionInfo)
6514 static const int kDontAdaptArgumentsSentinel = -1;
6516 // Layout description.
6518 static const int kNameOffset = HeapObject::kHeaderSize;
6519 static const int kCodeOffset = kNameOffset + kPointerSize;
6520 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6521 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6522 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6523 static const int kInstanceClassNameOffset =
6524 kConstructStubOffset + kPointerSize;
6525 static const int kFunctionDataOffset =
6526 kInstanceClassNameOffset + kPointerSize;
6527 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6528 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6529 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6530 static const int kFeedbackVectorOffset =
6531 kInferredNameOffset + kPointerSize;
6533 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6534 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6536 // Just to not break the postmortrem support with conditional offsets
6537 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6538 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6541 #if V8_HOST_ARCH_32_BIT
6543 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6544 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6545 static const int kExpectedNofPropertiesOffset =
6546 kFormalParameterCountOffset + kPointerSize;
6547 static const int kNumLiteralsOffset =
6548 kExpectedNofPropertiesOffset + kPointerSize;
6549 static const int kStartPositionAndTypeOffset =
6550 kNumLiteralsOffset + kPointerSize;
6551 static const int kEndPositionOffset =
6552 kStartPositionAndTypeOffset + kPointerSize;
6553 static const int kFunctionTokenPositionOffset =
6554 kEndPositionOffset + kPointerSize;
6555 static const int kCompilerHintsOffset =
6556 kFunctionTokenPositionOffset + kPointerSize;
6557 static const int kOptCountAndBailoutReasonOffset =
6558 kCompilerHintsOffset + kPointerSize;
6559 static const int kCountersOffset =
6560 kOptCountAndBailoutReasonOffset + kPointerSize;
6561 static const int kAstNodeCountOffset =
6562 kCountersOffset + kPointerSize;
6563 static const int kProfilerTicksOffset =
6564 kAstNodeCountOffset + kPointerSize;
6567 static const int kSize = kProfilerTicksOffset + kPointerSize;
6569 // The only reason to use smi fields instead of int fields
6570 // is to allow iteration without maps decoding during
6571 // garbage collections.
6572 // To avoid wasting space on 64-bit architectures we use
6573 // the following trick: we group integer fields into pairs
6574 // The least significant integer in each pair is shifted left by 1.
6575 // By doing this we guarantee that LSB of each kPointerSize aligned
6576 // word is not set and thus this word cannot be treated as pointer
6577 // to HeapObject during old space traversal.
6578 #if V8_TARGET_LITTLE_ENDIAN
6579 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6580 static const int kFormalParameterCountOffset =
6581 kLengthOffset + kIntSize;
6583 static const int kExpectedNofPropertiesOffset =
6584 kFormalParameterCountOffset + kIntSize;
6585 static const int kNumLiteralsOffset =
6586 kExpectedNofPropertiesOffset + kIntSize;
6588 static const int kEndPositionOffset =
6589 kNumLiteralsOffset + kIntSize;
6590 static const int kStartPositionAndTypeOffset =
6591 kEndPositionOffset + kIntSize;
6593 static const int kFunctionTokenPositionOffset =
6594 kStartPositionAndTypeOffset + kIntSize;
6595 static const int kCompilerHintsOffset =
6596 kFunctionTokenPositionOffset + kIntSize;
6598 static const int kOptCountAndBailoutReasonOffset =
6599 kCompilerHintsOffset + kIntSize;
6600 static const int kCountersOffset =
6601 kOptCountAndBailoutReasonOffset + kIntSize;
6603 static const int kAstNodeCountOffset =
6604 kCountersOffset + kIntSize;
6605 static const int kProfilerTicksOffset =
6606 kAstNodeCountOffset + kIntSize;
6609 static const int kSize = kProfilerTicksOffset + kIntSize;
6611 #elif V8_TARGET_BIG_ENDIAN
6612 static const int kFormalParameterCountOffset =
6613 kLastPointerFieldOffset + kPointerSize;
6614 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6616 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6617 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6619 static const int kStartPositionAndTypeOffset =
6620 kExpectedNofPropertiesOffset + kIntSize;
6621 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6623 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6624 static const int kFunctionTokenPositionOffset =
6625 kCompilerHintsOffset + kIntSize;
6627 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6628 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6630 static const int kProfilerTicksOffset =
6631 kOptCountAndBailoutReasonOffset + kIntSize;
6632 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6635 static const int kSize = kAstNodeCountOffset + kIntSize;
6638 #error Unknown byte ordering
6639 #endif // Big endian
6643 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6645 typedef FixedBodyDescriptor<kNameOffset,
6646 kLastPointerFieldOffset + kPointerSize,
6647 kSize> BodyDescriptor;
6649 // Bit positions in start_position_and_type.
6650 // The source code start position is in the 30 most significant bits of
6651 // the start_position_and_type field.
6652 static const int kIsExpressionBit = 0;
6653 static const int kIsTopLevelBit = 1;
6654 static const int kStartPositionShift = 2;
6655 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6657 // Bit positions in compiler_hints.
6658 enum CompilerHints {
6659 kAllowLazyCompilation,
6660 kAllowLazyCompilationWithoutContext,
6661 kOptimizationDisabled,
6662 kStrictModeFunction,
6663 kStrongModeFunction,
6666 kHasDuplicateParameters,
6671 kNameShouldPrintAsAnonymous,
6678 kIsAccessorFunction,
6679 kIsDefaultConstructor,
6680 kIsSubclassConstructor,
6686 kCompilerHintsCount // Pseudo entry
6688 // Add hints for other modes when they're added.
6689 STATIC_ASSERT(LANGUAGE_END == 3);
6691 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6693 class DeoptCountBits : public BitField<int, 0, 4> {};
6694 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6695 class ICAgeBits : public BitField<int, 22, 8> {};
6697 class OptCountBits : public BitField<int, 0, 22> {};
6698 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6701 #if V8_HOST_ARCH_32_BIT
6702 // On 32 bit platforms, compiler hints is a smi.
6703 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6704 static const int kCompilerHintsSize = kPointerSize;
6706 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6707 static const int kCompilerHintsSmiTagSize = 0;
6708 static const int kCompilerHintsSize = kIntSize;
6711 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6712 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6715 // Constants for optimizing codegen for strict mode function and
6717 // Allows to use byte-width instructions.
6718 static const int kStrictModeBitWithinByte =
6719 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6720 static const int kStrongModeBitWithinByte =
6721 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6723 static const int kNativeBitWithinByte =
6724 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6726 static const int kBoundBitWithinByte =
6727 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6729 #if defined(V8_TARGET_LITTLE_ENDIAN)
6730 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6731 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6732 static const int kStrongModeByteOffset =
6733 kCompilerHintsOffset +
6734 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6735 static const int kNativeByteOffset = kCompilerHintsOffset +
6736 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6737 static const int kBoundByteOffset =
6738 kCompilerHintsOffset +
6739 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6740 #elif defined(V8_TARGET_BIG_ENDIAN)
6741 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6742 (kCompilerHintsSize - 1) -
6743 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6744 static const int kStrongModeByteOffset =
6745 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6746 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6747 static const int kNativeByteOffset = kCompilerHintsOffset +
6748 (kCompilerHintsSize - 1) -
6749 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6750 static const int kBoundByteOffset =
6751 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6752 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6754 #error Unknown byte ordering
6758 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6762 // Printing support.
6763 struct SourceCodeOf {
6764 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6765 : value(v), max_length(max) {}
6766 const SharedFunctionInfo* value;
6771 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6774 class JSGeneratorObject: public JSObject {
6776 // [function]: The function corresponding to this generator object.
6777 DECL_ACCESSORS(function, JSFunction)
6779 // [context]: The context of the suspended computation.
6780 DECL_ACCESSORS(context, Context)
6782 // [receiver]: The receiver of the suspended computation.
6783 DECL_ACCESSORS(receiver, Object)
6785 // [continuation]: Offset into code of continuation.
6787 // A positive offset indicates a suspended generator. The special
6788 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6789 // cannot be resumed.
6790 inline int continuation() const;
6791 inline void set_continuation(int continuation);
6792 inline bool is_closed();
6793 inline bool is_executing();
6794 inline bool is_suspended();
6796 // [operand_stack]: Saved operand stack.
6797 DECL_ACCESSORS(operand_stack, FixedArray)
6799 DECLARE_CAST(JSGeneratorObject)
6801 // Dispatched behavior.
6802 DECLARE_PRINTER(JSGeneratorObject)
6803 DECLARE_VERIFIER(JSGeneratorObject)
6805 // Magic sentinel values for the continuation.
6806 static const int kGeneratorExecuting = -1;
6807 static const int kGeneratorClosed = 0;
6809 // Layout description.
6810 static const int kFunctionOffset = JSObject::kHeaderSize;
6811 static const int kContextOffset = kFunctionOffset + kPointerSize;
6812 static const int kReceiverOffset = kContextOffset + kPointerSize;
6813 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6814 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6815 static const int kSize = kOperandStackOffset + kPointerSize;
6817 // Resume mode, for use by runtime functions.
6818 enum ResumeMode { NEXT, THROW };
6820 // Yielding from a generator returns an object with the following inobject
6821 // properties. See Context::iterator_result_map() for the map.
6822 static const int kResultValuePropertyIndex = 0;
6823 static const int kResultDonePropertyIndex = 1;
6824 static const int kResultPropertyCount = 2;
6826 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6827 static const int kResultDonePropertyOffset =
6828 kResultValuePropertyOffset + kPointerSize;
6829 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6832 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6836 // Representation for module instance objects.
6837 class JSModule: public JSObject {
6839 // [context]: the context holding the module's locals, or undefined if none.
6840 DECL_ACCESSORS(context, Object)
6842 // [scope_info]: Scope info.
6843 DECL_ACCESSORS(scope_info, ScopeInfo)
6845 DECLARE_CAST(JSModule)
6847 // Dispatched behavior.
6848 DECLARE_PRINTER(JSModule)
6849 DECLARE_VERIFIER(JSModule)
6851 // Layout description.
6852 static const int kContextOffset = JSObject::kHeaderSize;
6853 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6854 static const int kSize = kScopeInfoOffset + kPointerSize;
6857 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6861 // JSFunction describes JavaScript functions.
6862 class JSFunction: public JSObject {
6864 // [prototype_or_initial_map]:
6865 DECL_ACCESSORS(prototype_or_initial_map, Object)
6867 // [shared]: The information about the function that
6868 // can be shared by instances.
6869 DECL_ACCESSORS(shared, SharedFunctionInfo)
6871 // [context]: The context for this function.
6872 inline Context* context();
6873 inline void set_context(Object* context);
6874 inline JSObject* global_proxy();
6876 // [code]: The generated code object for this function. Executed
6877 // when the function is invoked, e.g. foo() or new foo(). See
6878 // [[Call]] and [[Construct]] description in ECMA-262, section
6880 inline Code* code();
6881 inline void set_code(Code* code);
6882 inline void set_code_no_write_barrier(Code* code);
6883 inline void ReplaceCode(Code* code);
6885 // Tells whether this function is builtin.
6886 inline bool IsBuiltin();
6888 // Tells whether this function inlines the given shared function info.
6889 bool Inlines(SharedFunctionInfo* candidate);
6891 // Tells whether this function should be subject to debugging.
6892 inline bool IsSubjectToDebugging();
6894 // Tells whether or not the function needs arguments adaption.
6895 inline bool NeedsArgumentsAdaption();
6897 // Tells whether or not this function has been optimized.
6898 inline bool IsOptimized();
6900 // Mark this function for lazy recompilation. The function will be
6901 // recompiled the next time it is executed.
6902 void MarkForOptimization();
6903 void AttemptConcurrentOptimization();
6905 // Tells whether or not the function is already marked for lazy
6907 inline bool IsMarkedForOptimization();
6908 inline bool IsMarkedForConcurrentOptimization();
6910 // Tells whether or not the function is on the concurrent recompilation queue.
6911 inline bool IsInOptimizationQueue();
6913 // Inobject slack tracking is the way to reclaim unused inobject space.
6915 // The instance size is initially determined by adding some slack to
6916 // expected_nof_properties (to allow for a few extra properties added
6917 // after the constructor). There is no guarantee that the extra space
6918 // will not be wasted.
6920 // Here is the algorithm to reclaim the unused inobject space:
6921 // - Detect the first constructor call for this JSFunction.
6922 // When it happens enter the "in progress" state: initialize construction
6923 // counter in the initial_map.
6924 // - While the tracking is in progress create objects filled with
6925 // one_pointer_filler_map instead of undefined_value. This way they can be
6926 // resized quickly and safely.
6927 // - Once enough objects have been created compute the 'slack'
6928 // (traverse the map transition tree starting from the
6929 // initial_map and find the lowest value of unused_property_fields).
6930 // - Traverse the transition tree again and decrease the instance size
6931 // of every map. Existing objects will resize automatically (they are
6932 // filled with one_pointer_filler_map). All further allocations will
6933 // use the adjusted instance size.
6934 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6935 // allocations made using different closures could actually create different
6936 // kind of objects (see prototype inheritance pattern).
6938 // Important: inobject slack tracking is not attempted during the snapshot
6941 // True if the initial_map is set and the object constructions countdown
6942 // counter is not zero.
6943 static const int kGenerousAllocationCount =
6944 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6945 inline bool IsInobjectSlackTrackingInProgress();
6947 // Starts the tracking.
6948 // Initializes object constructions countdown counter in the initial map.
6949 void StartInobjectSlackTracking();
6951 // Completes the tracking.
6952 void CompleteInobjectSlackTracking();
6954 // [literals_or_bindings]: Fixed array holding either
6955 // the materialized literals or the bindings of a bound function.
6957 // If the function contains object, regexp or array literals, the
6958 // literals array prefix contains the object, regexp, and array
6959 // function to be used when creating these literals. This is
6960 // necessary so that we do not dynamically lookup the object, regexp
6961 // or array functions. Performing a dynamic lookup, we might end up
6962 // using the functions from a new context that we should not have
6965 // On bound functions, the array is a (copy-on-write) fixed-array containing
6966 // the function that was bound, bound this-value and any bound
6967 // arguments. Bound functions never contain literals.
6968 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6970 inline FixedArray* literals();
6971 inline void set_literals(FixedArray* literals);
6973 inline FixedArray* function_bindings();
6974 inline void set_function_bindings(FixedArray* bindings);
6976 // The initial map for an object created by this constructor.
6977 inline Map* initial_map();
6978 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6979 Handle<Object> prototype);
6980 inline bool has_initial_map();
6981 static void EnsureHasInitialMap(Handle<JSFunction> function);
6983 // Get and set the prototype property on a JSFunction. If the
6984 // function has an initial map the prototype is set on the initial
6985 // map. Otherwise, the prototype is put in the initial map field
6986 // until an initial map is needed.
6987 inline bool has_prototype();
6988 inline bool has_instance_prototype();
6989 inline Object* prototype();
6990 inline Object* instance_prototype();
6991 static void SetPrototype(Handle<JSFunction> function,
6992 Handle<Object> value);
6993 static void SetInstancePrototype(Handle<JSFunction> function,
6994 Handle<Object> value);
6996 // Creates a new closure for the fucntion with the same bindings,
6997 // bound values, and prototype. An equivalent of spec operations
6998 // ``CloneMethod`` and ``CloneBoundFunction``.
6999 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7001 // After prototype is removed, it will not be created when accessed, and
7002 // [[Construct]] from this function will not be allowed.
7003 bool RemovePrototype();
7004 inline bool should_have_prototype();
7006 // Accessor for this function's initial map's [[class]]
7007 // property. This is primarily used by ECMA native functions. This
7008 // method sets the class_name field of this function's initial map
7009 // to a given value. It creates an initial map if this function does
7010 // not have one. Note that this method does not copy the initial map
7011 // if it has one already, but simply replaces it with the new value.
7012 // Instances created afterwards will have a map whose [[class]] is
7013 // set to 'value', but there is no guarantees on instances created
7015 void SetInstanceClassName(String* name);
7017 // Returns if this function has been compiled to native code yet.
7018 inline bool is_compiled();
7020 // Returns `false` if formal parameters include rest parameters, optional
7021 // parameters, or destructuring parameters.
7022 // TODO(caitp): make this a flag set during parsing
7023 inline bool has_simple_parameters();
7025 // [next_function_link]: Links functions into various lists, e.g. the list
7026 // of optimized functions hanging off the native_context. The CodeFlusher
7027 // uses this link to chain together flushing candidates. Treated weakly
7028 // by the garbage collector.
7029 DECL_ACCESSORS(next_function_link, Object)
7031 // Prints the name of the function using PrintF.
7032 void PrintName(FILE* out = stdout);
7034 DECLARE_CAST(JSFunction)
7036 // Iterates the objects, including code objects indirectly referenced
7037 // through pointers to the first instruction in the code object.
7038 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7040 // Dispatched behavior.
7041 DECLARE_PRINTER(JSFunction)
7042 DECLARE_VERIFIER(JSFunction)
7044 // Returns the number of allocated literals.
7045 inline int NumberOfLiterals();
7047 // Used for flags such as --hydrogen-filter.
7048 bool PassesFilter(const char* raw_filter);
7050 // The function's name if it is configured, otherwise shared function info
7052 static Handle<String> GetDebugName(Handle<JSFunction> function);
7054 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7055 // kSize) is weak and has special handling during garbage collection.
7056 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7057 static const int kPrototypeOrInitialMapOffset =
7058 kCodeEntryOffset + kPointerSize;
7059 static const int kSharedFunctionInfoOffset =
7060 kPrototypeOrInitialMapOffset + kPointerSize;
7061 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7062 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7063 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7064 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7065 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7067 // Layout of the bound-function binding array.
7068 static const int kBoundFunctionIndex = 0;
7069 static const int kBoundThisIndex = 1;
7070 static const int kBoundArgumentsStartIndex = 2;
7073 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7077 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7078 // and the prototype is hidden. JSGlobalProxy always delegates
7079 // property accesses to its prototype if the prototype is not null.
7081 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7083 // Accessing a JSGlobalProxy requires security check.
7085 class JSGlobalProxy : public JSObject {
7087 // [native_context]: the owner native context of this global proxy object.
7088 // It is null value if this object is not used by any context.
7089 DECL_ACCESSORS(native_context, Object)
7091 // [hash]: The hash code property (undefined if not initialized yet).
7092 DECL_ACCESSORS(hash, Object)
7094 DECLARE_CAST(JSGlobalProxy)
7096 inline bool IsDetachedFrom(GlobalObject* global) const;
7098 // Dispatched behavior.
7099 DECLARE_PRINTER(JSGlobalProxy)
7100 DECLARE_VERIFIER(JSGlobalProxy)
7102 // Layout description.
7103 static const int kNativeContextOffset = JSObject::kHeaderSize;
7104 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7105 static const int kSize = kHashOffset + kPointerSize;
7108 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7112 // Common super class for JavaScript global objects and the special
7113 // builtins global objects.
7114 class GlobalObject: public JSObject {
7116 // [builtins]: the object holding the runtime routines written in JS.
7117 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7119 // [native context]: the natives corresponding to this global object.
7120 DECL_ACCESSORS(native_context, Context)
7122 // [global proxy]: the global proxy object of the context
7123 DECL_ACCESSORS(global_proxy, JSObject)
7125 DECLARE_CAST(GlobalObject)
7127 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7129 // Ensure that the global object has a cell for the given property name.
7130 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7133 // Layout description.
7134 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7135 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7136 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7137 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7140 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7144 // JavaScript global object.
7145 class JSGlobalObject: public GlobalObject {
7147 DECLARE_CAST(JSGlobalObject)
7149 inline bool IsDetached();
7151 // Dispatched behavior.
7152 DECLARE_PRINTER(JSGlobalObject)
7153 DECLARE_VERIFIER(JSGlobalObject)
7155 // Layout description.
7156 static const int kSize = GlobalObject::kHeaderSize;
7159 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7163 // Builtins global object which holds the runtime routines written in
7165 class JSBuiltinsObject: public GlobalObject {
7167 DECLARE_CAST(JSBuiltinsObject)
7169 // Dispatched behavior.
7170 DECLARE_PRINTER(JSBuiltinsObject)
7171 DECLARE_VERIFIER(JSBuiltinsObject)
7173 // Layout description.
7174 static const int kSize = GlobalObject::kHeaderSize;
7177 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7181 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7182 class JSValue: public JSObject {
7184 // [value]: the object being wrapped.
7185 DECL_ACCESSORS(value, Object)
7187 DECLARE_CAST(JSValue)
7189 // Dispatched behavior.
7190 DECLARE_PRINTER(JSValue)
7191 DECLARE_VERIFIER(JSValue)
7193 // Layout description.
7194 static const int kValueOffset = JSObject::kHeaderSize;
7195 static const int kSize = kValueOffset + kPointerSize;
7198 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7204 // Representation for JS date objects.
7205 class JSDate: public JSObject {
7207 // If one component is NaN, all of them are, indicating a NaN time value.
7208 // [value]: the time value.
7209 DECL_ACCESSORS(value, Object)
7210 // [year]: caches year. Either undefined, smi, or NaN.
7211 DECL_ACCESSORS(year, Object)
7212 // [month]: caches month. Either undefined, smi, or NaN.
7213 DECL_ACCESSORS(month, Object)
7214 // [day]: caches day. Either undefined, smi, or NaN.
7215 DECL_ACCESSORS(day, Object)
7216 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7217 DECL_ACCESSORS(weekday, Object)
7218 // [hour]: caches hours. Either undefined, smi, or NaN.
7219 DECL_ACCESSORS(hour, Object)
7220 // [min]: caches minutes. Either undefined, smi, or NaN.
7221 DECL_ACCESSORS(min, Object)
7222 // [sec]: caches seconds. Either undefined, smi, or NaN.
7223 DECL_ACCESSORS(sec, Object)
7224 // [cache stamp]: sample of the date cache stamp at the
7225 // moment when chached fields were cached.
7226 DECL_ACCESSORS(cache_stamp, Object)
7228 DECLARE_CAST(JSDate)
7230 // Returns the date field with the specified index.
7231 // See FieldIndex for the list of date fields.
7232 static Object* GetField(Object* date, Smi* index);
7234 void SetValue(Object* value, bool is_value_nan);
7237 // Dispatched behavior.
7238 DECLARE_PRINTER(JSDate)
7239 DECLARE_VERIFIER(JSDate)
7241 // The order is important. It must be kept in sync with date macros
7252 kFirstUncachedField,
7253 kMillisecond = kFirstUncachedField,
7257 kYearUTC = kFirstUTCField,
7270 // Layout description.
7271 static const int kValueOffset = JSObject::kHeaderSize;
7272 static const int kYearOffset = kValueOffset + kPointerSize;
7273 static const int kMonthOffset = kYearOffset + kPointerSize;
7274 static const int kDayOffset = kMonthOffset + kPointerSize;
7275 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7276 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7277 static const int kMinOffset = kHourOffset + kPointerSize;
7278 static const int kSecOffset = kMinOffset + kPointerSize;
7279 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7280 static const int kSize = kCacheStampOffset + kPointerSize;
7283 inline Object* DoGetField(FieldIndex index);
7285 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7287 // Computes and caches the cacheable fields of the date.
7288 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7291 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7295 // Representation of message objects used for error reporting through
7296 // the API. The messages are formatted in JavaScript so this object is
7297 // a real JavaScript object. The information used for formatting the
7298 // error messages are not directly accessible from JavaScript to
7299 // prevent leaking information to user code called during error
7301 class JSMessageObject: public JSObject {
7303 // [type]: the type of error message.
7304 inline int type() const;
7305 inline void set_type(int value);
7307 // [arguments]: the arguments for formatting the error message.
7308 DECL_ACCESSORS(argument, Object)
7310 // [script]: the script from which the error message originated.
7311 DECL_ACCESSORS(script, Object)
7313 // [stack_frames]: an array of stack frames for this error object.
7314 DECL_ACCESSORS(stack_frames, Object)
7316 // [start_position]: the start position in the script for the error message.
7317 inline int start_position() const;
7318 inline void set_start_position(int value);
7320 // [end_position]: the end position in the script for the error message.
7321 inline int end_position() const;
7322 inline void set_end_position(int value);
7324 DECLARE_CAST(JSMessageObject)
7326 // Dispatched behavior.
7327 DECLARE_PRINTER(JSMessageObject)
7328 DECLARE_VERIFIER(JSMessageObject)
7330 // Layout description.
7331 static const int kTypeOffset = JSObject::kHeaderSize;
7332 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7333 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7334 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7335 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7336 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7337 static const int kSize = kEndPositionOffset + kPointerSize;
7339 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7340 kStackFramesOffset + kPointerSize,
7341 kSize> BodyDescriptor;
7345 // Regular expressions
7346 // The regular expression holds a single reference to a FixedArray in
7347 // the kDataOffset field.
7348 // The FixedArray contains the following data:
7349 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7350 // - reference to the original source string
7351 // - reference to the original flag string
7352 // If it is an atom regexp
7353 // - a reference to a literal string to search for
7354 // If it is an irregexp regexp:
7355 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7356 // used for tracking the last usage (used for code flushing).
7357 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7358 // used for tracking the last usage (used for code flushing)..
7359 // - max number of registers used by irregexp implementations.
7360 // - number of capture registers (output values) of the regexp.
7361 class JSRegExp: public JSObject {
7364 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7365 // ATOM: A simple string to match against using an indexOf operation.
7366 // IRREGEXP: Compiled with Irregexp.
7367 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7368 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7375 UNICODE_ESCAPES = 16
7380 explicit Flags(uint32_t value) : value_(value) { }
7381 bool is_global() { return (value_ & GLOBAL) != 0; }
7382 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7383 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7384 bool is_sticky() { return (value_ & STICKY) != 0; }
7385 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7386 uint32_t value() { return value_; }
7391 DECL_ACCESSORS(data, Object)
7393 inline Type TypeTag();
7394 inline int CaptureCount();
7395 inline Flags GetFlags();
7396 inline String* Pattern();
7397 inline Object* DataAt(int index);
7398 // Set implementation data after the object has been prepared.
7399 inline void SetDataAt(int index, Object* value);
7401 static int code_index(bool is_latin1) {
7403 return kIrregexpLatin1CodeIndex;
7405 return kIrregexpUC16CodeIndex;
7409 static int saved_code_index(bool is_latin1) {
7411 return kIrregexpLatin1CodeSavedIndex;
7413 return kIrregexpUC16CodeSavedIndex;
7417 DECLARE_CAST(JSRegExp)
7419 // Dispatched behavior.
7420 DECLARE_VERIFIER(JSRegExp)
7422 static const int kDataOffset = JSObject::kHeaderSize;
7423 static const int kSize = kDataOffset + kPointerSize;
7425 // Indices in the data array.
7426 static const int kTagIndex = 0;
7427 static const int kSourceIndex = kTagIndex + 1;
7428 static const int kFlagsIndex = kSourceIndex + 1;
7429 static const int kDataIndex = kFlagsIndex + 1;
7430 // The data fields are used in different ways depending on the
7431 // value of the tag.
7432 // Atom regexps (literal strings).
7433 static const int kAtomPatternIndex = kDataIndex;
7435 static const int kAtomDataSize = kAtomPatternIndex + 1;
7437 // Irregexp compiled code or bytecode for Latin1. If compilation
7438 // fails, this fields hold an exception object that should be
7439 // thrown if the regexp is used again.
7440 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7441 // Irregexp compiled code or bytecode for UC16. If compilation
7442 // fails, this fields hold an exception object that should be
7443 // thrown if the regexp is used again.
7444 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7446 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7447 // is a potential candidate for flushing.
7448 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7449 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7450 // a potential candidate for flushing.
7451 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7453 // Maximal number of registers used by either Latin1 or UC16.
7454 // Only used to check that there is enough stack space
7455 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7456 // Number of captures in the compiled regexp.
7457 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7459 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7461 // Offsets directly into the data fixed array.
7462 static const int kDataTagOffset =
7463 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7464 static const int kDataOneByteCodeOffset =
7465 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7466 static const int kDataUC16CodeOffset =
7467 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7468 static const int kIrregexpCaptureCountOffset =
7469 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7471 // In-object fields.
7472 static const int kSourceFieldIndex = 0;
7473 static const int kGlobalFieldIndex = 1;
7474 static const int kIgnoreCaseFieldIndex = 2;
7475 static const int kMultilineFieldIndex = 3;
7476 static const int kLastIndexFieldIndex = 4;
7477 static const int kInObjectFieldCount = 5;
7479 // The uninitialized value for a regexp code object.
7480 static const int kUninitializedValue = -1;
7482 // The compilation error value for the regexp code object. The real error
7483 // object is in the saved code field.
7484 static const int kCompilationErrorValue = -2;
7486 // When we store the sweep generation at which we moved the code from the
7487 // code index to the saved code index we mask it of to be in the [0:255]
7489 static const int kCodeAgeMask = 0xff;
7493 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7495 static inline bool IsMatch(HashTableKey* key, Object* value) {
7496 return key->IsMatch(value);
7499 static inline uint32_t Hash(HashTableKey* key) {
7503 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7504 return key->HashForObject(object);
7507 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7509 static const int kPrefixSize = 0;
7510 static const int kEntrySize = 2;
7514 // This cache is used in two different variants. For regexp caching, it simply
7515 // maps identifying info of the regexp to the cached regexp object. Scripts and
7516 // eval code only gets cached after a second probe for the code object. To do
7517 // so, on first "put" only a hash identifying the source is entered into the
7518 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7519 // such lifetimes get reduced, and removed once they reach zero. If a second put
7520 // is called while such a hash is live in the cache, the hash gets replaced by
7521 // an actual cache entry. Age also removes stale live entries from the cache.
7522 // Such entries are identified by SharedFunctionInfos pointing to either the
7523 // recompilation stub, or to "old" code. This avoids memory leaks due to
7524 // premature caching of scripts and eval strings that are never needed later.
7525 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7526 CompilationCacheShape,
7529 // Find cached value for a string key, otherwise return null.
7530 Handle<Object> Lookup(
7531 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7532 Handle<Object> LookupEval(
7533 Handle<String> src, Handle<SharedFunctionInfo> shared,
7534 LanguageMode language_mode, int scope_position);
7535 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7536 static Handle<CompilationCacheTable> Put(
7537 Handle<CompilationCacheTable> cache, Handle<String> src,
7538 Handle<Context> context, LanguageMode language_mode,
7539 Handle<Object> value);
7540 static Handle<CompilationCacheTable> PutEval(
7541 Handle<CompilationCacheTable> cache, Handle<String> src,
7542 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7543 int scope_position);
7544 static Handle<CompilationCacheTable> PutRegExp(
7545 Handle<CompilationCacheTable> cache, Handle<String> src,
7546 JSRegExp::Flags flags, Handle<FixedArray> value);
7547 void Remove(Object* value);
7549 static const int kHashGenerations = 10;
7551 DECLARE_CAST(CompilationCacheTable)
7554 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7558 class CodeCache: public Struct {
7560 DECL_ACCESSORS(default_cache, FixedArray)
7561 DECL_ACCESSORS(normal_type_cache, Object)
7563 // Add the code object to the cache.
7565 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7567 // Lookup code object in the cache. Returns code object if found and undefined
7569 Object* Lookup(Name* name, Code::Flags flags);
7571 // Get the internal index of a code object in the cache. Returns -1 if the
7572 // code object is not in that cache. This index can be used to later call
7573 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7575 int GetIndex(Object* name, Code* code);
7577 // Remove an object from the cache with the provided internal index.
7578 void RemoveByIndex(Object* name, Code* code, int index);
7580 DECLARE_CAST(CodeCache)
7582 // Dispatched behavior.
7583 DECLARE_PRINTER(CodeCache)
7584 DECLARE_VERIFIER(CodeCache)
7586 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7587 static const int kNormalTypeCacheOffset =
7588 kDefaultCacheOffset + kPointerSize;
7589 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7592 static void UpdateDefaultCache(
7593 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7594 static void UpdateNormalTypeCache(
7595 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7596 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7597 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7599 // Code cache layout of the default cache. Elements are alternating name and
7600 // code objects for non normal load/store/call IC's.
7601 static const int kCodeCacheEntrySize = 2;
7602 static const int kCodeCacheEntryNameOffset = 0;
7603 static const int kCodeCacheEntryCodeOffset = 1;
7605 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7609 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7611 static inline bool IsMatch(HashTableKey* key, Object* value) {
7612 return key->IsMatch(value);
7615 static inline uint32_t Hash(HashTableKey* key) {
7619 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7620 return key->HashForObject(object);
7623 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7625 static const int kPrefixSize = 0;
7626 static const int kEntrySize = 2;
7630 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7631 CodeCacheHashTableShape,
7634 Object* Lookup(Name* name, Code::Flags flags);
7635 static Handle<CodeCacheHashTable> Put(
7636 Handle<CodeCacheHashTable> table,
7640 int GetIndex(Name* name, Code::Flags flags);
7641 void RemoveByIndex(int index);
7643 DECLARE_CAST(CodeCacheHashTable)
7645 // Initial size of the fixed array backing the hash table.
7646 static const int kInitialSize = 64;
7649 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7653 class PolymorphicCodeCache: public Struct {
7655 DECL_ACCESSORS(cache, Object)
7657 static void Update(Handle<PolymorphicCodeCache> cache,
7658 MapHandleList* maps,
7663 // Returns an undefined value if the entry is not found.
7664 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7666 DECLARE_CAST(PolymorphicCodeCache)
7668 // Dispatched behavior.
7669 DECLARE_PRINTER(PolymorphicCodeCache)
7670 DECLARE_VERIFIER(PolymorphicCodeCache)
7672 static const int kCacheOffset = HeapObject::kHeaderSize;
7673 static const int kSize = kCacheOffset + kPointerSize;
7676 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7680 class PolymorphicCodeCacheHashTable
7681 : public HashTable<PolymorphicCodeCacheHashTable,
7682 CodeCacheHashTableShape,
7685 Object* Lookup(MapHandleList* maps, int code_kind);
7687 static Handle<PolymorphicCodeCacheHashTable> Put(
7688 Handle<PolymorphicCodeCacheHashTable> hash_table,
7689 MapHandleList* maps,
7693 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7695 static const int kInitialSize = 64;
7697 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7701 class TypeFeedbackInfo: public Struct {
7703 inline int ic_total_count();
7704 inline void set_ic_total_count(int count);
7706 inline int ic_with_type_info_count();
7707 inline void change_ic_with_type_info_count(int delta);
7709 inline int ic_generic_count();
7710 inline void change_ic_generic_count(int delta);
7712 inline void initialize_storage();
7714 inline void change_own_type_change_checksum();
7715 inline int own_type_change_checksum();
7717 inline void set_inlined_type_change_checksum(int checksum);
7718 inline bool matches_inlined_type_change_checksum(int checksum);
7720 DECLARE_CAST(TypeFeedbackInfo)
7722 // Dispatched behavior.
7723 DECLARE_PRINTER(TypeFeedbackInfo)
7724 DECLARE_VERIFIER(TypeFeedbackInfo)
7726 static const int kStorage1Offset = HeapObject::kHeaderSize;
7727 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7728 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7729 static const int kSize = kStorage3Offset + kPointerSize;
7732 static const int kTypeChangeChecksumBits = 7;
7734 class ICTotalCountField: public BitField<int, 0,
7735 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7736 class OwnTypeChangeChecksum: public BitField<int,
7737 kSmiValueSize - kTypeChangeChecksumBits,
7738 kTypeChangeChecksumBits> {}; // NOLINT
7739 class ICsWithTypeInfoCountField: public BitField<int, 0,
7740 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7741 class InlinedTypeChangeChecksum: public BitField<int,
7742 kSmiValueSize - kTypeChangeChecksumBits,
7743 kTypeChangeChecksumBits> {}; // NOLINT
7745 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7749 enum AllocationSiteMode {
7750 DONT_TRACK_ALLOCATION_SITE,
7751 TRACK_ALLOCATION_SITE,
7752 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7756 class AllocationSite: public Struct {
7758 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7759 static const double kPretenureRatio;
7760 static const int kPretenureMinimumCreated = 100;
7762 // Values for pretenure decision field.
7763 enum PretenureDecision {
7769 kLastPretenureDecisionValue = kZombie
7772 const char* PretenureDecisionName(PretenureDecision decision);
7774 DECL_ACCESSORS(transition_info, Object)
7775 // nested_site threads a list of sites that represent nested literals
7776 // walked in a particular order. So [[1, 2], 1, 2] will have one
7777 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7778 DECL_ACCESSORS(nested_site, Object)
7779 DECL_ACCESSORS(pretenure_data, Smi)
7780 DECL_ACCESSORS(pretenure_create_count, Smi)
7781 DECL_ACCESSORS(dependent_code, DependentCode)
7782 DECL_ACCESSORS(weak_next, Object)
7784 inline void Initialize();
7786 // This method is expensive, it should only be called for reporting.
7787 bool IsNestedSite();
7789 // transition_info bitfields, for constructed array transition info.
7790 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7791 class UnusedBits: public BitField<int, 15, 14> {};
7792 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7794 // Bitfields for pretenure_data
7795 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7796 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7797 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7798 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7800 // Increments the mementos found counter and returns true when the first
7801 // memento was found for a given allocation site.
7802 inline bool IncrementMementoFoundCount();
7804 inline void IncrementMementoCreateCount();
7806 PretenureFlag GetPretenureMode();
7808 void ResetPretenureDecision();
7810 inline PretenureDecision pretenure_decision();
7811 inline void set_pretenure_decision(PretenureDecision decision);
7813 inline bool deopt_dependent_code();
7814 inline void set_deopt_dependent_code(bool deopt);
7816 inline int memento_found_count();
7817 inline void set_memento_found_count(int count);
7819 inline int memento_create_count();
7820 inline void set_memento_create_count(int count);
7822 // The pretenuring decision is made during gc, and the zombie state allows
7823 // us to recognize when an allocation site is just being kept alive because
7824 // a later traversal of new space may discover AllocationMementos that point
7825 // to this AllocationSite.
7826 inline bool IsZombie();
7828 inline bool IsMaybeTenure();
7830 inline void MarkZombie();
7832 inline bool MakePretenureDecision(PretenureDecision current_decision,
7834 bool maximum_size_scavenge);
7836 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7838 inline ElementsKind GetElementsKind();
7839 inline void SetElementsKind(ElementsKind kind);
7841 inline bool CanInlineCall();
7842 inline void SetDoNotInlineCall();
7844 inline bool SitePointsToLiteral();
7846 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7847 ElementsKind to_kind);
7849 DECLARE_PRINTER(AllocationSite)
7850 DECLARE_VERIFIER(AllocationSite)
7852 DECLARE_CAST(AllocationSite)
7853 static inline AllocationSiteMode GetMode(
7854 ElementsKind boilerplate_elements_kind);
7855 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7856 static inline bool CanTrack(InstanceType type);
7858 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7859 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7860 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7861 static const int kPretenureCreateCountOffset =
7862 kPretenureDataOffset + kPointerSize;
7863 static const int kDependentCodeOffset =
7864 kPretenureCreateCountOffset + kPointerSize;
7865 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7866 static const int kSize = kWeakNextOffset + kPointerSize;
7868 // During mark compact we need to take special care for the dependent code
7870 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7871 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7873 // For other visitors, use the fixed body descriptor below.
7874 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7875 kDependentCodeOffset + kPointerSize,
7876 kSize> BodyDescriptor;
7879 inline bool PretenuringDecisionMade();
7881 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7885 class AllocationMemento: public Struct {
7887 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7888 static const int kSize = kAllocationSiteOffset + kPointerSize;
7890 DECL_ACCESSORS(allocation_site, Object)
7892 inline bool IsValid();
7893 inline AllocationSite* GetAllocationSite();
7895 DECLARE_PRINTER(AllocationMemento)
7896 DECLARE_VERIFIER(AllocationMemento)
7898 DECLARE_CAST(AllocationMemento)
7901 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7905 // Representation of a slow alias as part of a sloppy arguments objects.
7906 // For fast aliases (if HasSloppyArgumentsElements()):
7907 // - the parameter map contains an index into the context
7908 // - all attributes of the element have default values
7909 // For slow aliases (if HasDictionaryArgumentsElements()):
7910 // - the parameter map contains no fast alias mapping (i.e. the hole)
7911 // - this struct (in the slow backing store) contains an index into the context
7912 // - all attributes are available as part if the property details
7913 class AliasedArgumentsEntry: public Struct {
7915 inline int aliased_context_slot() const;
7916 inline void set_aliased_context_slot(int count);
7918 DECLARE_CAST(AliasedArgumentsEntry)
7920 // Dispatched behavior.
7921 DECLARE_PRINTER(AliasedArgumentsEntry)
7922 DECLARE_VERIFIER(AliasedArgumentsEntry)
7924 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7925 static const int kSize = kAliasedContextSlot + kPointerSize;
7928 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7932 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7933 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7936 class StringHasher {
7938 explicit inline StringHasher(int length, uint32_t seed);
7940 template <typename schar>
7941 static inline uint32_t HashSequentialString(const schar* chars,
7945 // Reads all the data, even for long strings and computes the utf16 length.
7946 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7948 int* utf16_length_out);
7950 // Calculated hash value for a string consisting of 1 to
7951 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7952 // value is represented decimal value.
7953 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7955 // No string is allowed to have a hash of zero. That value is reserved
7956 // for internal properties. If the hash calculation yields zero then we
7958 static const int kZeroHash = 27;
7960 // Reusable parts of the hashing algorithm.
7961 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7962 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7963 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7964 const uc16* chars, int length));
7965 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7970 // Returns the value to store in the hash field of a string with
7971 // the given length and contents.
7972 uint32_t GetHashField();
7973 // Returns true if the hash of this string can be computed without
7974 // looking at the contents.
7975 inline bool has_trivial_hash();
7976 // Adds a block of characters to the hash.
7977 template<typename Char>
7978 inline void AddCharacters(const Char* chars, int len);
7981 // Add a character to the hash.
7982 inline void AddCharacter(uint16_t c);
7983 // Update index. Returns true if string is still an index.
7984 inline bool UpdateIndex(uint16_t c);
7987 uint32_t raw_running_hash_;
7988 uint32_t array_index_;
7989 bool is_array_index_;
7990 bool is_first_char_;
7991 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7995 class IteratingStringHasher : public StringHasher {
7997 static inline uint32_t Hash(String* string, uint32_t seed);
7998 inline void VisitOneByteString(const uint8_t* chars, int length);
7999 inline void VisitTwoByteString(const uint16_t* chars, int length);
8002 inline IteratingStringHasher(int len, uint32_t seed);
8003 void VisitConsString(ConsString* cons_string);
8004 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8008 // The characteristics of a string are stored in its map. Retrieving these
8009 // few bits of information is moderately expensive, involving two memory
8010 // loads where the second is dependent on the first. To improve efficiency
8011 // the shape of the string is given its own class so that it can be retrieved
8012 // once and used for several string operations. A StringShape is small enough
8013 // to be passed by value and is immutable, but be aware that flattening a
8014 // string can potentially alter its shape. Also be aware that a GC caused by
8015 // something else can alter the shape of a string due to ConsString
8016 // shortcutting. Keeping these restrictions in mind has proven to be error-
8017 // prone and so we no longer put StringShapes in variables unless there is a
8018 // concrete performance benefit at that particular point in the code.
8019 class StringShape BASE_EMBEDDED {
8021 inline explicit StringShape(const String* s);
8022 inline explicit StringShape(Map* s);
8023 inline explicit StringShape(InstanceType t);
8024 inline bool IsSequential();
8025 inline bool IsExternal();
8026 inline bool IsCons();
8027 inline bool IsSliced();
8028 inline bool IsIndirect();
8029 inline bool IsExternalOneByte();
8030 inline bool IsExternalTwoByte();
8031 inline bool IsSequentialOneByte();
8032 inline bool IsSequentialTwoByte();
8033 inline bool IsInternalized();
8034 inline StringRepresentationTag representation_tag();
8035 inline uint32_t encoding_tag();
8036 inline uint32_t full_representation_tag();
8037 inline uint32_t size_tag();
8039 inline uint32_t type() { return type_; }
8040 inline void invalidate() { valid_ = false; }
8041 inline bool valid() { return valid_; }
8043 inline void invalidate() { }
8049 inline void set_valid() { valid_ = true; }
8052 inline void set_valid() { }
8057 // The Name abstract class captures anything that can be used as a property
8058 // name, i.e., strings and symbols. All names store a hash value.
8059 class Name: public HeapObject {
8061 // Get and set the hash field of the name.
8062 inline uint32_t hash_field();
8063 inline void set_hash_field(uint32_t value);
8065 // Tells whether the hash code has been computed.
8066 inline bool HasHashCode();
8068 // Returns a hash value used for the property table
8069 inline uint32_t Hash();
8071 // Equality operations.
8072 inline bool Equals(Name* other);
8073 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8076 inline bool AsArrayIndex(uint32_t* index);
8078 // If the name is private, it can only name own properties.
8079 inline bool IsPrivate();
8081 // If the name is a non-flat string, this method returns a flat version of the
8082 // string. Otherwise it'll just return the input.
8083 static inline Handle<Name> Flatten(Handle<Name> name,
8084 PretenureFlag pretenure = NOT_TENURED);
8088 DECLARE_PRINTER(Name)
8090 void NameShortPrint();
8091 int NameShortPrint(Vector<char> str);
8094 // Layout description.
8095 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8096 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8097 static const int kHashFieldOffset = kHashFieldSlot;
8099 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8101 static const int kSize = kHashFieldSlot + kPointerSize;
8103 // Mask constant for checking if a name has a computed hash code
8104 // and if it is a string that is an array index. The least significant bit
8105 // indicates whether a hash code has been computed. If the hash code has
8106 // been computed the 2nd bit tells whether the string can be used as an
8108 static const int kHashNotComputedMask = 1;
8109 static const int kIsNotArrayIndexMask = 1 << 1;
8110 static const int kNofHashBitFields = 2;
8112 // Shift constant retrieving hash code from hash field.
8113 static const int kHashShift = kNofHashBitFields;
8115 // Only these bits are relevant in the hash, since the top two are shifted
8117 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8119 // Array index strings this short can keep their index in the hash field.
8120 static const int kMaxCachedArrayIndexLength = 7;
8122 // For strings which are array indexes the hash value has the string length
8123 // mixed into the hash, mainly to avoid a hash value of zero which would be
8124 // the case for the string '0'. 24 bits are used for the array index value.
8125 static const int kArrayIndexValueBits = 24;
8126 static const int kArrayIndexLengthBits =
8127 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8129 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8131 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8132 kArrayIndexValueBits> {}; // NOLINT
8133 class ArrayIndexLengthBits : public BitField<unsigned int,
8134 kNofHashBitFields + kArrayIndexValueBits,
8135 kArrayIndexLengthBits> {}; // NOLINT
8137 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8138 // could use a mask to test if the length of string is less than or equal to
8139 // kMaxCachedArrayIndexLength.
8140 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8142 static const unsigned int kContainsCachedArrayIndexMask =
8143 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8144 << ArrayIndexLengthBits::kShift) |
8145 kIsNotArrayIndexMask;
8147 // Value of empty hash field indicating that the hash is not computed.
8148 static const int kEmptyHashField =
8149 kIsNotArrayIndexMask | kHashNotComputedMask;
8152 static inline bool IsHashFieldComputed(uint32_t field);
8155 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8160 class Symbol: public Name {
8162 // [name]: The print name of a symbol, or undefined if none.
8163 DECL_ACCESSORS(name, Object)
8165 DECL_ACCESSORS(flags, Smi)
8167 // [is_private]: Whether this is a private symbol. Private symbols can only
8168 // be used to designate own properties of objects.
8169 DECL_BOOLEAN_ACCESSORS(is_private)
8171 DECLARE_CAST(Symbol)
8173 // Dispatched behavior.
8174 DECLARE_PRINTER(Symbol)
8175 DECLARE_VERIFIER(Symbol)
8177 // Layout description.
8178 static const int kNameOffset = Name::kSize;
8179 static const int kFlagsOffset = kNameOffset + kPointerSize;
8180 static const int kSize = kFlagsOffset + kPointerSize;
8182 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8184 void SymbolShortPrint(std::ostream& os);
8187 static const int kPrivateBit = 0;
8189 const char* PrivateSymbolToName() const;
8192 friend class Name; // For PrivateSymbolToName.
8195 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8201 // The String abstract class captures JavaScript string values:
8204 // 4.3.16 String Value
8205 // A string value is a member of the type String and is a finite
8206 // ordered sequence of zero or more 16-bit unsigned integer values.
8208 // All string values have a length field.
8209 class String: public Name {
8211 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8213 // Array index strings this short can keep their index in the hash field.
8214 static const int kMaxCachedArrayIndexLength = 7;
8216 // For strings which are array indexes the hash value has the string length
8217 // mixed into the hash, mainly to avoid a hash value of zero which would be
8218 // the case for the string '0'. 24 bits are used for the array index value.
8219 static const int kArrayIndexValueBits = 24;
8220 static const int kArrayIndexLengthBits =
8221 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8223 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8225 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8226 kArrayIndexValueBits> {}; // NOLINT
8227 class ArrayIndexLengthBits : public BitField<unsigned int,
8228 kNofHashBitFields + kArrayIndexValueBits,
8229 kArrayIndexLengthBits> {}; // NOLINT
8231 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8232 // could use a mask to test if the length of string is less than or equal to
8233 // kMaxCachedArrayIndexLength.
8234 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8236 static const unsigned int kContainsCachedArrayIndexMask =
8237 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8238 << ArrayIndexLengthBits::kShift) |
8239 kIsNotArrayIndexMask;
8241 class SubStringRange {
8243 explicit inline SubStringRange(String* string, int first = 0,
8246 inline iterator begin();
8247 inline iterator end();
8255 // Representation of the flat content of a String.
8256 // A non-flat string doesn't have flat content.
8257 // A flat string has content that's encoded as a sequence of either
8258 // one-byte chars or two-byte UC16.
8259 // Returned by String::GetFlatContent().
8262 // Returns true if the string is flat and this structure contains content.
8263 bool IsFlat() { return state_ != NON_FLAT; }
8264 // Returns true if the structure contains one-byte content.
8265 bool IsOneByte() { return state_ == ONE_BYTE; }
8266 // Returns true if the structure contains two-byte content.
8267 bool IsTwoByte() { return state_ == TWO_BYTE; }
8269 // Return the one byte content of the string. Only use if IsOneByte()
8271 Vector<const uint8_t> ToOneByteVector() {
8272 DCHECK_EQ(ONE_BYTE, state_);
8273 return Vector<const uint8_t>(onebyte_start, length_);
8275 // Return the two-byte content of the string. Only use if IsTwoByte()
8277 Vector<const uc16> ToUC16Vector() {
8278 DCHECK_EQ(TWO_BYTE, state_);
8279 return Vector<const uc16>(twobyte_start, length_);
8283 DCHECK(i < length_);
8284 DCHECK(state_ != NON_FLAT);
8285 if (state_ == ONE_BYTE) return onebyte_start[i];
8286 return twobyte_start[i];
8289 bool UsesSameString(const FlatContent& other) const {
8290 return onebyte_start == other.onebyte_start;
8294 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8296 // Constructors only used by String::GetFlatContent().
8297 explicit FlatContent(const uint8_t* start, int length)
8298 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8299 explicit FlatContent(const uc16* start, int length)
8300 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8301 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8304 const uint8_t* onebyte_start;
8305 const uc16* twobyte_start;
8310 friend class String;
8311 friend class IterableSubString;
8314 template <typename Char>
8315 INLINE(Vector<const Char> GetCharVector());
8317 // Get and set the length of the string.
8318 inline int length() const;
8319 inline void set_length(int value);
8321 // Get and set the length of the string using acquire loads and release
8323 inline int synchronized_length() const;
8324 inline void synchronized_set_length(int value);
8326 // Returns whether this string has only one-byte chars, i.e. all of them can
8327 // be one-byte encoded. This might be the case even if the string is
8328 // two-byte. Such strings may appear when the embedder prefers
8329 // two-byte external representations even for one-byte data.
8330 inline bool IsOneByteRepresentation() const;
8331 inline bool IsTwoByteRepresentation() const;
8333 // Cons and slices have an encoding flag that may not represent the actual
8334 // encoding of the underlying string. This is taken into account here.
8335 // Requires: this->IsFlat()
8336 inline bool IsOneByteRepresentationUnderneath();
8337 inline bool IsTwoByteRepresentationUnderneath();
8339 // NOTE: this should be considered only a hint. False negatives are
8341 inline bool HasOnlyOneByteChars();
8343 // Get and set individual two byte chars in the string.
8344 inline void Set(int index, uint16_t value);
8345 // Get individual two byte char in the string. Repeated calls
8346 // to this method are not efficient unless the string is flat.
8347 INLINE(uint16_t Get(int index));
8349 // Flattens the string. Checks first inline to see if it is
8350 // necessary. Does nothing if the string is not a cons string.
8351 // Flattening allocates a sequential string with the same data as
8352 // the given string and mutates the cons string to a degenerate
8353 // form, where the first component is the new sequential string and
8354 // the second component is the empty string. If allocation fails,
8355 // this function returns a failure. If flattening succeeds, this
8356 // function returns the sequential string that is now the first
8357 // component of the cons string.
8359 // Degenerate cons strings are handled specially by the garbage
8360 // collector (see IsShortcutCandidate).
8362 static inline Handle<String> Flatten(Handle<String> string,
8363 PretenureFlag pretenure = NOT_TENURED);
8365 // Tries to return the content of a flat string as a structure holding either
8366 // a flat vector of char or of uc16.
8367 // If the string isn't flat, and therefore doesn't have flat content, the
8368 // returned structure will report so, and can't provide a vector of either
8370 FlatContent GetFlatContent();
8372 // Returns the parent of a sliced string or first part of a flat cons string.
8373 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8374 inline String* GetUnderlying();
8376 // String equality operations.
8377 inline bool Equals(String* other);
8378 inline static bool Equals(Handle<String> one, Handle<String> two);
8379 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8380 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8381 bool IsTwoByteEqualTo(Vector<const uc16> str);
8383 // Return a UTF8 representation of the string. The string is null
8384 // terminated but may optionally contain nulls. Length is returned
8385 // in length_output if length_output is not a null pointer The string
8386 // should be nearly flat, otherwise the performance of this method may
8387 // be very slow (quadratic in the length). Setting robustness_flag to
8388 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8389 // handles unexpected data without causing assert failures and it does not
8390 // do any heap allocations. This is useful when printing stack traces.
8391 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8392 RobustnessFlag robustness_flag,
8393 int offset, int length,
8394 int* length_output = 0);
8395 base::SmartArrayPointer<char> ToCString(
8396 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8397 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8398 int* length_output = 0);
8400 // Return a 16 bit Unicode representation of the string.
8401 // The string should be nearly flat, otherwise the performance of
8402 // of this method may be very bad. Setting robustness_flag to
8403 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8404 // handles unexpected data without causing assert failures and it does not
8405 // do any heap allocations. This is useful when printing stack traces.
8406 base::SmartArrayPointer<uc16> ToWideCString(
8407 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8409 bool ComputeArrayIndex(uint32_t* index);
8412 bool MakeExternal(v8::String::ExternalStringResource* resource);
8413 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8416 inline bool AsArrayIndex(uint32_t* index);
8418 DECLARE_CAST(String)
8420 void PrintOn(FILE* out);
8422 // For use during stack traces. Performs rudimentary sanity check.
8425 // Dispatched behavior.
8426 void StringShortPrint(StringStream* accumulator);
8427 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8428 #if defined(DEBUG) || defined(OBJECT_PRINT)
8429 char* ToAsciiArray();
8431 DECLARE_PRINTER(String)
8432 DECLARE_VERIFIER(String)
8434 inline bool IsFlat();
8436 // Layout description.
8437 static const int kLengthOffset = Name::kSize;
8438 static const int kSize = kLengthOffset + kPointerSize;
8440 // Maximum number of characters to consider when trying to convert a string
8441 // value into an array index.
8442 static const int kMaxArrayIndexSize = 10;
8443 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8446 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8447 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8448 static const int kMaxUtf16CodeUnit = 0xffff;
8449 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8451 // Value of hash field containing computed hash equal to zero.
8452 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8454 // Maximal string length.
8455 static const int kMaxLength = (1 << 28) - 16;
8457 // Max length for computing hash. For strings longer than this limit the
8458 // string length is used as the hash value.
8459 static const int kMaxHashCalcLength = 16383;
8461 // Limit for truncation in short printing.
8462 static const int kMaxShortPrintLength = 1024;
8464 // Support for regular expressions.
8465 const uc16* GetTwoByteData(unsigned start);
8467 // Helper function for flattening strings.
8468 template <typename sinkchar>
8469 static void WriteToFlat(String* source,
8474 // The return value may point to the first aligned word containing the first
8475 // non-one-byte character, rather than directly to the non-one-byte character.
8476 // If the return value is >= the passed length, the entire string was
8478 static inline int NonAsciiStart(const char* chars, int length) {
8479 const char* start = chars;
8480 const char* limit = chars + length;
8482 if (length >= kIntptrSize) {
8483 // Check unaligned bytes.
8484 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8485 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8486 return static_cast<int>(chars - start);
8490 // Check aligned words.
8491 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8492 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8493 while (chars + sizeof(uintptr_t) <= limit) {
8494 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8495 return static_cast<int>(chars - start);
8497 chars += sizeof(uintptr_t);
8500 // Check remaining unaligned bytes.
8501 while (chars < limit) {
8502 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8503 return static_cast<int>(chars - start);
8508 return static_cast<int>(chars - start);
8511 static inline bool IsAscii(const char* chars, int length) {
8512 return NonAsciiStart(chars, length) >= length;
8515 static inline bool IsAscii(const uint8_t* chars, int length) {
8517 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8520 static inline int NonOneByteStart(const uc16* chars, int length) {
8521 const uc16* limit = chars + length;
8522 const uc16* start = chars;
8523 while (chars < limit) {
8524 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8527 return static_cast<int>(chars - start);
8530 static inline bool IsOneByte(const uc16* chars, int length) {
8531 return NonOneByteStart(chars, length) >= length;
8534 template<class Visitor>
8535 static inline ConsString* VisitFlat(Visitor* visitor,
8539 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8540 bool include_ending_line);
8542 // Use the hash field to forward to the canonical internalized string
8543 // when deserializing an internalized string.
8544 inline void SetForwardedInternalizedString(String* string);
8545 inline String* GetForwardedInternalizedString();
8549 friend class StringTableInsertionKey;
8551 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8552 PretenureFlag tenure);
8554 // Slow case of String::Equals. This implementation works on any strings
8555 // but it is most efficient on strings that are almost flat.
8556 bool SlowEquals(String* other);
8558 static bool SlowEquals(Handle<String> one, Handle<String> two);
8560 // Slow case of AsArrayIndex.
8561 bool SlowAsArrayIndex(uint32_t* index);
8563 // Compute and set the hash code.
8564 uint32_t ComputeAndSetHash();
8566 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8570 // The SeqString abstract class captures sequential string values.
8571 class SeqString: public String {
8573 DECLARE_CAST(SeqString)
8575 // Layout description.
8576 static const int kHeaderSize = String::kSize;
8578 // Truncate the string in-place if possible and return the result.
8579 // In case of new_length == 0, the empty string is returned without
8580 // truncating the original string.
8581 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8584 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8588 // The OneByteString class captures sequential one-byte string objects.
8589 // Each character in the OneByteString is an one-byte character.
8590 class SeqOneByteString: public SeqString {
8592 static const bool kHasOneByteEncoding = true;
8594 // Dispatched behavior.
8595 inline uint16_t SeqOneByteStringGet(int index);
8596 inline void SeqOneByteStringSet(int index, uint16_t value);
8598 // Get the address of the characters in this string.
8599 inline Address GetCharsAddress();
8601 inline uint8_t* GetChars();
8603 DECLARE_CAST(SeqOneByteString)
8605 // Garbage collection support. This method is called by the
8606 // garbage collector to compute the actual size of an OneByteString
8608 inline int SeqOneByteStringSize(InstanceType instance_type);
8610 // Computes the size for an OneByteString instance of a given length.
8611 static int SizeFor(int length) {
8612 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8615 // Maximal memory usage for a single sequential one-byte string.
8616 static const int kMaxSize = 512 * MB - 1;
8617 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8620 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8624 // The TwoByteString class captures sequential unicode string objects.
8625 // Each character in the TwoByteString is a two-byte uint16_t.
8626 class SeqTwoByteString: public SeqString {
8628 static const bool kHasOneByteEncoding = false;
8630 // Dispatched behavior.
8631 inline uint16_t SeqTwoByteStringGet(int index);
8632 inline void SeqTwoByteStringSet(int index, uint16_t value);
8634 // Get the address of the characters in this string.
8635 inline Address GetCharsAddress();
8637 inline uc16* GetChars();
8640 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8642 DECLARE_CAST(SeqTwoByteString)
8644 // Garbage collection support. This method is called by the
8645 // garbage collector to compute the actual size of a TwoByteString
8647 inline int SeqTwoByteStringSize(InstanceType instance_type);
8649 // Computes the size for a TwoByteString instance of a given length.
8650 static int SizeFor(int length) {
8651 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8654 // Maximal memory usage for a single sequential two-byte string.
8655 static const int kMaxSize = 512 * MB - 1;
8656 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8657 String::kMaxLength);
8660 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8664 // The ConsString class describes string values built by using the
8665 // addition operator on strings. A ConsString is a pair where the
8666 // first and second components are pointers to other string values.
8667 // One or both components of a ConsString can be pointers to other
8668 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8669 // are non-ConsString string values. The string value represented by
8670 // a ConsString can be obtained by concatenating the leaf string
8671 // values in a left-to-right depth-first traversal of the tree.
8672 class ConsString: public String {
8674 // First string of the cons cell.
8675 inline String* first();
8676 // Doesn't check that the result is a string, even in debug mode. This is
8677 // useful during GC where the mark bits confuse the checks.
8678 inline Object* unchecked_first();
8679 inline void set_first(String* first,
8680 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8682 // Second string of the cons cell.
8683 inline String* second();
8684 // Doesn't check that the result is a string, even in debug mode. This is
8685 // useful during GC where the mark bits confuse the checks.
8686 inline Object* unchecked_second();
8687 inline void set_second(String* second,
8688 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8690 // Dispatched behavior.
8691 uint16_t ConsStringGet(int index);
8693 DECLARE_CAST(ConsString)
8695 // Layout description.
8696 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8697 static const int kSecondOffset = kFirstOffset + kPointerSize;
8698 static const int kSize = kSecondOffset + kPointerSize;
8700 // Minimum length for a cons string.
8701 static const int kMinLength = 13;
8703 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8706 DECLARE_VERIFIER(ConsString)
8709 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8713 // The Sliced String class describes strings that are substrings of another
8714 // sequential string. The motivation is to save time and memory when creating
8715 // a substring. A Sliced String is described as a pointer to the parent,
8716 // the offset from the start of the parent string and the length. Using
8717 // a Sliced String therefore requires unpacking of the parent string and
8718 // adding the offset to the start address. A substring of a Sliced String
8719 // are not nested since the double indirection is simplified when creating
8720 // such a substring.
8721 // Currently missing features are:
8722 // - handling externalized parent strings
8723 // - external strings as parent
8724 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8725 class SlicedString: public String {
8727 inline String* parent();
8728 inline void set_parent(String* parent,
8729 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8730 inline int offset() const;
8731 inline void set_offset(int offset);
8733 // Dispatched behavior.
8734 uint16_t SlicedStringGet(int index);
8736 DECLARE_CAST(SlicedString)
8738 // Layout description.
8739 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8740 static const int kOffsetOffset = kParentOffset + kPointerSize;
8741 static const int kSize = kOffsetOffset + kPointerSize;
8743 // Minimum length for a sliced string.
8744 static const int kMinLength = 13;
8746 typedef FixedBodyDescriptor<kParentOffset,
8747 kOffsetOffset + kPointerSize, kSize>
8750 DECLARE_VERIFIER(SlicedString)
8753 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8757 // The ExternalString class describes string values that are backed by
8758 // a string resource that lies outside the V8 heap. ExternalStrings
8759 // consist of the length field common to all strings, a pointer to the
8760 // external resource. It is important to ensure (externally) that the
8761 // resource is not deallocated while the ExternalString is live in the
8764 // The API expects that all ExternalStrings are created through the
8765 // API. Therefore, ExternalStrings should not be used internally.
8766 class ExternalString: public String {
8768 DECLARE_CAST(ExternalString)
8770 // Layout description.
8771 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8772 static const int kShortSize = kResourceOffset + kPointerSize;
8773 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8774 static const int kSize = kResourceDataOffset + kPointerSize;
8776 static const int kMaxShortLength =
8777 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8779 // Return whether external string is short (data pointer is not cached).
8780 inline bool is_short();
8782 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8785 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8789 // The ExternalOneByteString class is an external string backed by an
8791 class ExternalOneByteString : public ExternalString {
8793 static const bool kHasOneByteEncoding = true;
8795 typedef v8::String::ExternalOneByteStringResource Resource;
8797 // The underlying resource.
8798 inline const Resource* resource();
8799 inline void set_resource(const Resource* buffer);
8801 // Update the pointer cache to the external character array.
8802 // The cached pointer is always valid, as the external character array does =
8803 // not move during lifetime. Deserialization is the only exception, after
8804 // which the pointer cache has to be refreshed.
8805 inline void update_data_cache();
8807 inline const uint8_t* GetChars();
8809 // Dispatched behavior.
8810 inline uint16_t ExternalOneByteStringGet(int index);
8812 DECLARE_CAST(ExternalOneByteString)
8814 // Garbage collection support.
8815 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8817 template <typename StaticVisitor>
8818 inline void ExternalOneByteStringIterateBody();
8821 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8825 // The ExternalTwoByteString class is an external string backed by a UTF-16
8827 class ExternalTwoByteString: public ExternalString {
8829 static const bool kHasOneByteEncoding = false;
8831 typedef v8::String::ExternalStringResource Resource;
8833 // The underlying string resource.
8834 inline const Resource* resource();
8835 inline void set_resource(const Resource* buffer);
8837 // Update the pointer cache to the external character array.
8838 // The cached pointer is always valid, as the external character array does =
8839 // not move during lifetime. Deserialization is the only exception, after
8840 // which the pointer cache has to be refreshed.
8841 inline void update_data_cache();
8843 inline const uint16_t* GetChars();
8845 // Dispatched behavior.
8846 inline uint16_t ExternalTwoByteStringGet(int index);
8849 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8851 DECLARE_CAST(ExternalTwoByteString)
8853 // Garbage collection support.
8854 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8856 template<typename StaticVisitor>
8857 inline void ExternalTwoByteStringIterateBody();
8860 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8864 // Utility superclass for stack-allocated objects that must be updated
8865 // on gc. It provides two ways for the gc to update instances, either
8866 // iterating or updating after gc.
8867 class Relocatable BASE_EMBEDDED {
8869 explicit inline Relocatable(Isolate* isolate);
8870 inline virtual ~Relocatable();
8871 virtual void IterateInstance(ObjectVisitor* v) { }
8872 virtual void PostGarbageCollection() { }
8874 static void PostGarbageCollectionProcessing(Isolate* isolate);
8875 static int ArchiveSpacePerThread();
8876 static char* ArchiveState(Isolate* isolate, char* to);
8877 static char* RestoreState(Isolate* isolate, char* from);
8878 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8879 static void Iterate(ObjectVisitor* v, Relocatable* top);
8880 static char* Iterate(ObjectVisitor* v, char* t);
8888 // A flat string reader provides random access to the contents of a
8889 // string independent of the character width of the string. The handle
8890 // must be valid as long as the reader is being used.
8891 class FlatStringReader : public Relocatable {
8893 FlatStringReader(Isolate* isolate, Handle<String> str);
8894 FlatStringReader(Isolate* isolate, Vector<const char> input);
8895 void PostGarbageCollection();
8896 inline uc32 Get(int index);
8897 template <typename Char>
8898 inline Char Get(int index);
8899 int length() { return length_; }
8908 // This maintains an off-stack representation of the stack frames required
8909 // to traverse a ConsString, allowing an entirely iterative and restartable
8910 // traversal of the entire string
8911 class ConsStringIterator {
8913 inline ConsStringIterator() {}
8914 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8915 Reset(cons_string, offset);
8917 inline void Reset(ConsString* cons_string, int offset = 0) {
8919 // Next will always return NULL.
8920 if (cons_string == NULL) return;
8921 Initialize(cons_string, offset);
8923 // Returns NULL when complete.
8924 inline String* Next(int* offset_out) {
8926 if (depth_ == 0) return NULL;
8927 return Continue(offset_out);
8931 static const int kStackSize = 32;
8932 // Use a mask instead of doing modulo operations for stack wrapping.
8933 static const int kDepthMask = kStackSize-1;
8934 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8935 static inline int OffsetForDepth(int depth);
8937 inline void PushLeft(ConsString* string);
8938 inline void PushRight(ConsString* string);
8939 inline void AdjustMaximumDepth();
8941 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8942 void Initialize(ConsString* cons_string, int offset);
8943 String* Continue(int* offset_out);
8944 String* NextLeaf(bool* blew_stack);
8945 String* Search(int* offset_out);
8947 // Stack must always contain only frames for which right traversal
8948 // has not yet been performed.
8949 ConsString* frames_[kStackSize];
8954 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8958 class StringCharacterStream {
8960 inline StringCharacterStream(String* string,
8962 inline uint16_t GetNext();
8963 inline bool HasMore();
8964 inline void Reset(String* string, int offset = 0);
8965 inline void VisitOneByteString(const uint8_t* chars, int length);
8966 inline void VisitTwoByteString(const uint16_t* chars, int length);
8969 ConsStringIterator iter_;
8972 const uint8_t* buffer8_;
8973 const uint16_t* buffer16_;
8975 const uint8_t* end_;
8976 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8980 template <typename T>
8981 class VectorIterator {
8983 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8984 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8985 T GetNext() { return data_[index_++]; }
8986 bool has_more() { return index_ < data_.length(); }
8988 Vector<const T> data_;
8993 // The Oddball describes objects null, undefined, true, and false.
8994 class Oddball: public HeapObject {
8996 // [to_string]: Cached to_string computed at startup.
8997 DECL_ACCESSORS(to_string, String)
8999 // [to_number]: Cached to_number computed at startup.
9000 DECL_ACCESSORS(to_number, Object)
9002 // [typeof]: Cached type_of computed at startup.
9003 DECL_ACCESSORS(type_of, String)
9005 inline byte kind() const;
9006 inline void set_kind(byte kind);
9008 DECLARE_CAST(Oddball)
9010 // Dispatched behavior.
9011 DECLARE_VERIFIER(Oddball)
9013 // Initialize the fields.
9014 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9015 const char* to_string, Handle<Object> to_number,
9016 const char* type_of, byte kind);
9018 // Layout description.
9019 static const int kToStringOffset = HeapObject::kHeaderSize;
9020 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9021 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9022 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9023 static const int kSize = kKindOffset + kPointerSize;
9025 static const byte kFalse = 0;
9026 static const byte kTrue = 1;
9027 static const byte kNotBooleanMask = ~1;
9028 static const byte kTheHole = 2;
9029 static const byte kNull = 3;
9030 static const byte kArgumentMarker = 4;
9031 static const byte kUndefined = 5;
9032 static const byte kUninitialized = 6;
9033 static const byte kOther = 7;
9034 static const byte kException = 8;
9036 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9037 kSize> BodyDescriptor;
9039 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9040 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9041 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9044 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9048 class Cell: public HeapObject {
9050 // [value]: value of the cell.
9051 DECL_ACCESSORS(value, Object)
9055 static inline Cell* FromValueAddress(Address value) {
9056 Object* result = FromAddress(value - kValueOffset);
9057 return static_cast<Cell*>(result);
9060 inline Address ValueAddress() {
9061 return address() + kValueOffset;
9064 // Dispatched behavior.
9065 DECLARE_PRINTER(Cell)
9066 DECLARE_VERIFIER(Cell)
9068 // Layout description.
9069 static const int kValueOffset = HeapObject::kHeaderSize;
9070 static const int kSize = kValueOffset + kPointerSize;
9072 typedef FixedBodyDescriptor<kValueOffset,
9073 kValueOffset + kPointerSize,
9074 kSize> BodyDescriptor;
9077 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9081 class PropertyCell : public HeapObject {
9083 // [property_details]: details of the global property.
9084 DECL_ACCESSORS(property_details_raw, Object)
9085 // [value]: value of the global property.
9086 DECL_ACCESSORS(value, Object)
9087 // [dependent_code]: dependent code that depends on the type of the global
9089 DECL_ACCESSORS(dependent_code, DependentCode)
9091 inline PropertyDetails property_details();
9092 inline void set_property_details(PropertyDetails details);
9094 PropertyCellConstantType GetConstantType();
9096 // Computes the new type of the cell's contents for the given value, but
9097 // without actually modifying the details.
9098 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9099 Handle<Object> value,
9100 PropertyDetails details);
9101 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9102 Handle<Object> value, PropertyDetails details);
9104 static Handle<PropertyCell> InvalidateEntry(
9105 Handle<GlobalDictionary> dictionary, int entry);
9107 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9108 Handle<Object> new_value);
9110 DECLARE_CAST(PropertyCell)
9112 // Dispatched behavior.
9113 DECLARE_PRINTER(PropertyCell)
9114 DECLARE_VERIFIER(PropertyCell)
9116 // Layout description.
9117 static const int kDetailsOffset = HeapObject::kHeaderSize;
9118 static const int kValueOffset = kDetailsOffset + kPointerSize;
9119 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9120 static const int kSize = kDependentCodeOffset + kPointerSize;
9122 static const int kPointerFieldsBeginOffset = kValueOffset;
9123 static const int kPointerFieldsEndOffset = kSize;
9125 typedef FixedBodyDescriptor<kValueOffset,
9127 kSize> BodyDescriptor;
9130 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9134 class WeakCell : public HeapObject {
9136 inline Object* value() const;
9138 // This should not be called by anyone except GC.
9139 inline void clear();
9141 // This should not be called by anyone except allocator.
9142 inline void initialize(HeapObject* value);
9144 inline bool cleared() const;
9146 DECL_ACCESSORS(next, Object)
9148 inline void clear_next(Heap* heap);
9150 inline bool next_cleared();
9152 DECLARE_CAST(WeakCell)
9154 DECLARE_PRINTER(WeakCell)
9155 DECLARE_VERIFIER(WeakCell)
9157 // Layout description.
9158 static const int kValueOffset = HeapObject::kHeaderSize;
9159 static const int kNextOffset = kValueOffset + kPointerSize;
9160 static const int kSize = kNextOffset + kPointerSize;
9162 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9165 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9169 // The JSProxy describes EcmaScript Harmony proxies
9170 class JSProxy: public JSReceiver {
9172 // [handler]: The handler property.
9173 DECL_ACCESSORS(handler, Object)
9175 // [hash]: The hash code property (undefined if not initialized yet).
9176 DECL_ACCESSORS(hash, Object)
9178 DECLARE_CAST(JSProxy)
9180 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9181 Handle<JSProxy> proxy,
9182 Handle<Object> receiver,
9185 // If the handler defines an accessor property with a setter, invoke it.
9186 // If it defines an accessor property without a setter, or a data property
9187 // that is read-only, throw. In all these cases set '*done' to true,
9188 // otherwise set it to false.
9190 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9191 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9192 Handle<Object> value, LanguageMode language_mode, bool* done);
9194 MUST_USE_RESULT static Maybe<PropertyAttributes>
9195 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9196 Handle<Object> receiver,
9198 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9199 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9200 Handle<Object> value, LanguageMode language_mode);
9202 // Turn the proxy into an (empty) JSObject.
9203 static void Fix(Handle<JSProxy> proxy);
9205 // Initializes the body after the handler slot.
9206 inline void InitializeBody(int object_size, Object* value);
9208 // Invoke a trap by name. If the trap does not exist on this's handler,
9209 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9210 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9211 Handle<JSProxy> proxy,
9213 Handle<Object> derived_trap,
9215 Handle<Object> args[]);
9217 // Dispatched behavior.
9218 DECLARE_PRINTER(JSProxy)
9219 DECLARE_VERIFIER(JSProxy)
9221 // Layout description. We add padding so that a proxy has the same
9222 // size as a virgin JSObject. This is essential for becoming a JSObject
9224 static const int kHandlerOffset = HeapObject::kHeaderSize;
9225 static const int kHashOffset = kHandlerOffset + kPointerSize;
9226 static const int kPaddingOffset = kHashOffset + kPointerSize;
9227 static const int kSize = JSObject::kHeaderSize;
9228 static const int kHeaderSize = kPaddingOffset;
9229 static const int kPaddingSize = kSize - kPaddingOffset;
9231 STATIC_ASSERT(kPaddingSize >= 0);
9233 typedef FixedBodyDescriptor<kHandlerOffset,
9235 kSize> BodyDescriptor;
9238 friend class JSReceiver;
9240 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9241 Handle<JSProxy> proxy, Handle<Name> name);
9243 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9244 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9246 MUST_USE_RESULT Object* GetIdentityHash();
9248 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9250 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9254 class JSFunctionProxy: public JSProxy {
9256 // [call_trap]: The call trap.
9257 DECL_ACCESSORS(call_trap, Object)
9259 // [construct_trap]: The construct trap.
9260 DECL_ACCESSORS(construct_trap, Object)
9262 DECLARE_CAST(JSFunctionProxy)
9264 // Dispatched behavior.
9265 DECLARE_PRINTER(JSFunctionProxy)
9266 DECLARE_VERIFIER(JSFunctionProxy)
9268 // Layout description.
9269 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9270 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9271 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9272 static const int kSize = JSFunction::kSize;
9273 static const int kPaddingSize = kSize - kPaddingOffset;
9275 STATIC_ASSERT(kPaddingSize >= 0);
9277 typedef FixedBodyDescriptor<kHandlerOffset,
9278 kConstructTrapOffset + kPointerSize,
9279 kSize> BodyDescriptor;
9282 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9286 class JSCollection : public JSObject {
9288 // [table]: the backing hash table
9289 DECL_ACCESSORS(table, Object)
9291 static const int kTableOffset = JSObject::kHeaderSize;
9292 static const int kSize = kTableOffset + kPointerSize;
9295 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9299 // The JSSet describes EcmaScript Harmony sets
9300 class JSSet : public JSCollection {
9304 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9305 static void Clear(Handle<JSSet> set);
9307 // Dispatched behavior.
9308 DECLARE_PRINTER(JSSet)
9309 DECLARE_VERIFIER(JSSet)
9312 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9316 // The JSMap describes EcmaScript Harmony maps
9317 class JSMap : public JSCollection {
9321 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9322 static void Clear(Handle<JSMap> map);
9324 // Dispatched behavior.
9325 DECLARE_PRINTER(JSMap)
9326 DECLARE_VERIFIER(JSMap)
9329 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9333 // OrderedHashTableIterator is an iterator that iterates over the keys and
9334 // values of an OrderedHashTable.
9336 // The iterator has a reference to the underlying OrderedHashTable data,
9337 // [table], as well as the current [index] the iterator is at.
9339 // When the OrderedHashTable is rehashed it adds a reference from the old table
9340 // to the new table as well as storing enough data about the changes so that the
9341 // iterator [index] can be adjusted accordingly.
9343 // When the [Next] result from the iterator is requested, the iterator checks if
9344 // there is a newer table that it needs to transition to.
9345 template<class Derived, class TableType>
9346 class OrderedHashTableIterator: public JSObject {
9348 // [table]: the backing hash table mapping keys to values.
9349 DECL_ACCESSORS(table, Object)
9351 // [index]: The index into the data table.
9352 DECL_ACCESSORS(index, Object)
9354 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9355 DECL_ACCESSORS(kind, Object)
9358 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9361 static const int kTableOffset = JSObject::kHeaderSize;
9362 static const int kIndexOffset = kTableOffset + kPointerSize;
9363 static const int kKindOffset = kIndexOffset + kPointerSize;
9364 static const int kSize = kKindOffset + kPointerSize;
9372 // Whether the iterator has more elements. This needs to be called before
9373 // calling |CurrentKey| and/or |CurrentValue|.
9376 // Move the index forward one.
9378 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9381 // Populates the array with the next key and value and then moves the iterator
9383 // This returns the |kind| or 0 if the iterator is already at the end.
9384 Smi* Next(JSArray* value_array);
9386 // Returns the current key of the iterator. This should only be called when
9387 // |HasMore| returns true.
9388 inline Object* CurrentKey();
9391 // Transitions the iterator to the non obsolete backing store. This is a NOP
9392 // if the [table] is not obsolete.
9395 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9399 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9402 // Dispatched behavior.
9403 DECLARE_PRINTER(JSSetIterator)
9404 DECLARE_VERIFIER(JSSetIterator)
9406 DECLARE_CAST(JSSetIterator)
9408 // Called by |Next| to populate the array. This allows the subclasses to
9409 // populate the array differently.
9410 inline void PopulateValueArray(FixedArray* array);
9413 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9417 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9420 // Dispatched behavior.
9421 DECLARE_PRINTER(JSMapIterator)
9422 DECLARE_VERIFIER(JSMapIterator)
9424 DECLARE_CAST(JSMapIterator)
9426 // Called by |Next| to populate the array. This allows the subclasses to
9427 // populate the array differently.
9428 inline void PopulateValueArray(FixedArray* array);
9431 // Returns the current value of the iterator. This should only be called when
9432 // |HasMore| returns true.
9433 inline Object* CurrentValue();
9435 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9439 // Base class for both JSWeakMap and JSWeakSet
9440 class JSWeakCollection: public JSObject {
9442 // [table]: the backing hash table mapping keys to values.
9443 DECL_ACCESSORS(table, Object)
9445 // [next]: linked list of encountered weak maps during GC.
9446 DECL_ACCESSORS(next, Object)
9448 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9449 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9450 Handle<Object> value, int32_t hash);
9451 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9454 static const int kTableOffset = JSObject::kHeaderSize;
9455 static const int kNextOffset = kTableOffset + kPointerSize;
9456 static const int kSize = kNextOffset + kPointerSize;
9459 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9463 // The JSWeakMap describes EcmaScript Harmony weak maps
9464 class JSWeakMap: public JSWeakCollection {
9466 DECLARE_CAST(JSWeakMap)
9468 // Dispatched behavior.
9469 DECLARE_PRINTER(JSWeakMap)
9470 DECLARE_VERIFIER(JSWeakMap)
9473 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9477 // The JSWeakSet describes EcmaScript Harmony weak sets
9478 class JSWeakSet: public JSWeakCollection {
9480 DECLARE_CAST(JSWeakSet)
9482 // Dispatched behavior.
9483 DECLARE_PRINTER(JSWeakSet)
9484 DECLARE_VERIFIER(JSWeakSet)
9487 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9491 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9492 enum class SharedFlag { kNotShared, kShared };
9495 class JSArrayBuffer: public JSObject {
9497 // [backing_store]: backing memory for this array
9498 DECL_ACCESSORS(backing_store, void)
9500 // [byte_length]: length in bytes
9501 DECL_ACCESSORS(byte_length, Object)
9503 inline uint32_t bit_field() const;
9504 inline void set_bit_field(uint32_t bits);
9506 inline bool is_external();
9507 inline void set_is_external(bool value);
9509 inline bool is_neuterable();
9510 inline void set_is_neuterable(bool value);
9512 inline bool was_neutered();
9513 inline void set_was_neutered(bool value);
9515 inline bool is_shared();
9516 inline void set_is_shared(bool value);
9518 DECLARE_CAST(JSArrayBuffer)
9522 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9523 bool is_external, void* data, size_t allocated_length,
9524 SharedFlag shared = SharedFlag::kNotShared);
9526 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9527 Isolate* isolate, size_t allocated_length,
9528 bool initialize = true,
9529 SharedFlag shared = SharedFlag::kNotShared);
9531 // Dispatched behavior.
9532 DECLARE_PRINTER(JSArrayBuffer)
9533 DECLARE_VERIFIER(JSArrayBuffer)
9535 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9536 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9537 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9538 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9539 static const int kBitFieldOffset = kBitFieldSlot;
9541 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9543 static const int kSize = kBitFieldSlot + kPointerSize;
9545 static const int kSizeWithInternalFields =
9546 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9548 class IsExternal : public BitField<bool, 1, 1> {};
9549 class IsNeuterable : public BitField<bool, 2, 1> {};
9550 class WasNeutered : public BitField<bool, 3, 1> {};
9551 class IsShared : public BitField<bool, 4, 1> {};
9554 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9558 class JSArrayBufferView: public JSObject {
9560 // [buffer]: ArrayBuffer that this typed array views.
9561 DECL_ACCESSORS(buffer, Object)
9563 // [byte_offset]: offset of typed array in bytes.
9564 DECL_ACCESSORS(byte_offset, Object)
9566 // [byte_length]: length of typed array in bytes.
9567 DECL_ACCESSORS(byte_length, Object)
9569 DECLARE_CAST(JSArrayBufferView)
9571 DECLARE_VERIFIER(JSArrayBufferView)
9573 inline bool WasNeutered() const;
9575 static const int kBufferOffset = JSObject::kHeaderSize;
9576 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9577 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9578 static const int kViewSize = kByteLengthOffset + kPointerSize;
9582 DECL_ACCESSORS(raw_byte_offset, Object)
9583 DECL_ACCESSORS(raw_byte_length, Object)
9586 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9590 class JSTypedArray: public JSArrayBufferView {
9592 // [length]: length of typed array in elements.
9593 DECL_ACCESSORS(length, Object)
9594 inline uint32_t length_value() const;
9596 DECLARE_CAST(JSTypedArray)
9598 ExternalArrayType type();
9599 size_t element_size();
9601 Handle<JSArrayBuffer> GetBuffer();
9603 // Dispatched behavior.
9604 DECLARE_PRINTER(JSTypedArray)
9605 DECLARE_VERIFIER(JSTypedArray)
9607 static const int kLengthOffset = kViewSize + kPointerSize;
9608 static const int kSize = kLengthOffset + kPointerSize;
9610 static const int kSizeWithInternalFields =
9611 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9614 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9615 Handle<JSTypedArray> typed_array);
9617 DECL_ACCESSORS(raw_length, Object)
9620 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9624 class JSDataView: public JSArrayBufferView {
9626 DECLARE_CAST(JSDataView)
9628 // Dispatched behavior.
9629 DECLARE_PRINTER(JSDataView)
9630 DECLARE_VERIFIER(JSDataView)
9632 static const int kSize = kViewSize;
9634 static const int kSizeWithInternalFields =
9635 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9638 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9642 // Foreign describes objects pointing from JavaScript to C structures.
9643 class Foreign: public HeapObject {
9645 // [address]: field containing the address.
9646 inline Address foreign_address();
9647 inline void set_foreign_address(Address value);
9649 DECLARE_CAST(Foreign)
9651 // Dispatched behavior.
9652 inline void ForeignIterateBody(ObjectVisitor* v);
9654 template<typename StaticVisitor>
9655 inline void ForeignIterateBody();
9657 // Dispatched behavior.
9658 DECLARE_PRINTER(Foreign)
9659 DECLARE_VERIFIER(Foreign)
9661 // Layout description.
9663 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9664 static const int kSize = kForeignAddressOffset + kPointerSize;
9666 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9669 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9673 // The JSArray describes JavaScript Arrays
9674 // Such an array can be in one of two modes:
9675 // - fast, backing storage is a FixedArray and length <= elements.length();
9676 // Please note: push and pop can be used to grow and shrink the array.
9677 // - slow, backing storage is a HashTable with numbers as keys.
9678 class JSArray: public JSObject {
9680 // [length]: The length property.
9681 DECL_ACCESSORS(length, Object)
9683 // Overload the length setter to skip write barrier when the length
9684 // is set to a smi. This matches the set function on FixedArray.
9685 inline void set_length(Smi* length);
9687 static bool HasReadOnlyLength(Handle<JSArray> array);
9688 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9689 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9691 // Initialize the array with the given capacity. The function may
9692 // fail due to out-of-memory situations, but only if the requested
9693 // capacity is non-zero.
9694 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9696 // If the JSArray has fast elements, and new_length would result in
9697 // normalization, returns true.
9698 bool SetLengthWouldNormalize(uint32_t new_length);
9699 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9701 // Initializes the array to a certain length.
9702 inline bool AllowsSetLength();
9704 static void SetLength(Handle<JSArray> array, uint32_t length);
9705 // Same as above but will also queue splice records if |array| is observed.
9706 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9709 // Set the content of the array to the content of storage.
9710 static inline void SetContent(Handle<JSArray> array,
9711 Handle<FixedArrayBase> storage);
9713 DECLARE_CAST(JSArray)
9715 // Dispatched behavior.
9716 DECLARE_PRINTER(JSArray)
9717 DECLARE_VERIFIER(JSArray)
9719 // Number of element slots to pre-allocate for an empty array.
9720 static const int kPreallocatedArrayElements = 4;
9722 // Layout description.
9723 static const int kLengthOffset = JSObject::kHeaderSize;
9724 static const int kSize = kLengthOffset + kPointerSize;
9727 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9731 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9732 Handle<Map> initial_map);
9735 // JSRegExpResult is just a JSArray with a specific initial map.
9736 // This initial map adds in-object properties for "index" and "input"
9737 // properties, as assigned by RegExp.prototype.exec, which allows
9738 // faster creation of RegExp exec results.
9739 // This class just holds constants used when creating the result.
9740 // After creation the result must be treated as a JSArray in all regards.
9741 class JSRegExpResult: public JSArray {
9743 // Offsets of object fields.
9744 static const int kIndexOffset = JSArray::kSize;
9745 static const int kInputOffset = kIndexOffset + kPointerSize;
9746 static const int kSize = kInputOffset + kPointerSize;
9747 // Indices of in-object properties.
9748 static const int kIndexIndex = 0;
9749 static const int kInputIndex = 1;
9751 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9755 class AccessorInfo: public Struct {
9757 DECL_ACCESSORS(name, Object)
9758 DECL_ACCESSORS(flag, Smi)
9759 DECL_ACCESSORS(expected_receiver_type, Object)
9761 inline bool all_can_read();
9762 inline void set_all_can_read(bool value);
9764 inline bool all_can_write();
9765 inline void set_all_can_write(bool value);
9767 inline bool is_special_data_property();
9768 inline void set_is_special_data_property(bool value);
9770 inline PropertyAttributes property_attributes();
9771 inline void set_property_attributes(PropertyAttributes attributes);
9773 // Checks whether the given receiver is compatible with this accessor.
9774 static bool IsCompatibleReceiverMap(Isolate* isolate,
9775 Handle<AccessorInfo> info,
9777 inline bool IsCompatibleReceiver(Object* receiver);
9779 DECLARE_CAST(AccessorInfo)
9781 // Dispatched behavior.
9782 DECLARE_VERIFIER(AccessorInfo)
9784 // Append all descriptors to the array that are not already there.
9785 // Return number added.
9786 static int AppendUnique(Handle<Object> descriptors,
9787 Handle<FixedArray> array,
9788 int valid_descriptors);
9790 static const int kNameOffset = HeapObject::kHeaderSize;
9791 static const int kFlagOffset = kNameOffset + kPointerSize;
9792 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9793 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9796 inline bool HasExpectedReceiverType();
9798 // Bit positions in flag.
9799 static const int kAllCanReadBit = 0;
9800 static const int kAllCanWriteBit = 1;
9801 static const int kSpecialDataProperty = 2;
9802 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9804 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9808 // An accessor must have a getter, but can have no setter.
9810 // When setting a property, V8 searches accessors in prototypes.
9811 // If an accessor was found and it does not have a setter,
9812 // the request is ignored.
9814 // If the accessor in the prototype has the READ_ONLY property attribute, then
9815 // a new value is added to the derived object when the property is set.
9816 // This shadows the accessor in the prototype.
9817 class ExecutableAccessorInfo: public AccessorInfo {
9819 DECL_ACCESSORS(getter, Object)
9820 DECL_ACCESSORS(setter, Object)
9821 DECL_ACCESSORS(data, Object)
9823 DECLARE_CAST(ExecutableAccessorInfo)
9825 // Dispatched behavior.
9826 DECLARE_PRINTER(ExecutableAccessorInfo)
9827 DECLARE_VERIFIER(ExecutableAccessorInfo)
9829 static const int kGetterOffset = AccessorInfo::kSize;
9830 static const int kSetterOffset = kGetterOffset + kPointerSize;
9831 static const int kDataOffset = kSetterOffset + kPointerSize;
9832 static const int kSize = kDataOffset + kPointerSize;
9834 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9837 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9841 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9842 // accessor can either be
9843 // * a pointer to a JavaScript function or proxy: a real accessor
9844 // * undefined: considered an accessor by the spec, too, strangely enough
9845 // * the hole: an accessor which has not been set
9846 // * a pointer to a map: a transition used to ensure map sharing
9847 class AccessorPair: public Struct {
9849 DECL_ACCESSORS(getter, Object)
9850 DECL_ACCESSORS(setter, Object)
9852 DECLARE_CAST(AccessorPair)
9854 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9856 inline Object* get(AccessorComponent component);
9857 inline void set(AccessorComponent component, Object* value);
9859 // Note: Returns undefined instead in case of a hole.
9860 Object* GetComponent(AccessorComponent component);
9862 // Set both components, skipping arguments which are a JavaScript null.
9863 inline void SetComponents(Object* getter, Object* setter);
9865 inline bool Equals(AccessorPair* pair);
9866 inline bool Equals(Object* getter_value, Object* setter_value);
9868 inline bool ContainsAccessor();
9870 // Dispatched behavior.
9871 DECLARE_PRINTER(AccessorPair)
9872 DECLARE_VERIFIER(AccessorPair)
9874 static const int kGetterOffset = HeapObject::kHeaderSize;
9875 static const int kSetterOffset = kGetterOffset + kPointerSize;
9876 static const int kSize = kSetterOffset + kPointerSize;
9879 // Strangely enough, in addition to functions and harmony proxies, the spec
9880 // requires us to consider undefined as a kind of accessor, too:
9882 // Object.defineProperty(obj, "foo", {get: undefined});
9883 // assertTrue("foo" in obj);
9884 inline bool IsJSAccessor(Object* obj);
9886 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9890 class AccessCheckInfo: public Struct {
9892 DECL_ACCESSORS(named_callback, Object)
9893 DECL_ACCESSORS(indexed_callback, Object)
9894 DECL_ACCESSORS(data, Object)
9896 DECLARE_CAST(AccessCheckInfo)
9898 // Dispatched behavior.
9899 DECLARE_PRINTER(AccessCheckInfo)
9900 DECLARE_VERIFIER(AccessCheckInfo)
9902 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9903 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9904 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9905 static const int kSize = kDataOffset + kPointerSize;
9908 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9912 class InterceptorInfo: public Struct {
9914 DECL_ACCESSORS(getter, Object)
9915 DECL_ACCESSORS(setter, Object)
9916 DECL_ACCESSORS(query, Object)
9917 DECL_ACCESSORS(deleter, Object)
9918 DECL_ACCESSORS(enumerator, Object)
9919 DECL_ACCESSORS(data, Object)
9920 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9921 DECL_BOOLEAN_ACCESSORS(all_can_read)
9922 DECL_BOOLEAN_ACCESSORS(non_masking)
9924 inline int flags() const;
9925 inline void set_flags(int flags);
9927 DECLARE_CAST(InterceptorInfo)
9929 // Dispatched behavior.
9930 DECLARE_PRINTER(InterceptorInfo)
9931 DECLARE_VERIFIER(InterceptorInfo)
9933 static const int kGetterOffset = HeapObject::kHeaderSize;
9934 static const int kSetterOffset = kGetterOffset + kPointerSize;
9935 static const int kQueryOffset = kSetterOffset + kPointerSize;
9936 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9937 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9938 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9939 static const int kFlagsOffset = kDataOffset + kPointerSize;
9940 static const int kSize = kFlagsOffset + kPointerSize;
9942 static const int kCanInterceptSymbolsBit = 0;
9943 static const int kAllCanReadBit = 1;
9944 static const int kNonMasking = 2;
9947 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9951 class CallHandlerInfo: public Struct {
9953 DECL_ACCESSORS(callback, Object)
9954 DECL_ACCESSORS(data, Object)
9956 DECLARE_CAST(CallHandlerInfo)
9958 // Dispatched behavior.
9959 DECLARE_PRINTER(CallHandlerInfo)
9960 DECLARE_VERIFIER(CallHandlerInfo)
9962 static const int kCallbackOffset = HeapObject::kHeaderSize;
9963 static const int kDataOffset = kCallbackOffset + kPointerSize;
9964 static const int kSize = kDataOffset + kPointerSize;
9967 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9971 class TemplateInfo: public Struct {
9973 DECL_ACCESSORS(tag, Object)
9974 inline int number_of_properties() const;
9975 inline void set_number_of_properties(int value);
9976 DECL_ACCESSORS(property_list, Object)
9977 DECL_ACCESSORS(property_accessors, Object)
9979 DECLARE_VERIFIER(TemplateInfo)
9981 static const int kTagOffset = HeapObject::kHeaderSize;
9982 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9983 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9984 static const int kPropertyAccessorsOffset =
9985 kPropertyListOffset + kPointerSize;
9986 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9989 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9993 class FunctionTemplateInfo: public TemplateInfo {
9995 DECL_ACCESSORS(serial_number, Object)
9996 DECL_ACCESSORS(call_code, Object)
9997 DECL_ACCESSORS(prototype_template, Object)
9998 DECL_ACCESSORS(parent_template, Object)
9999 DECL_ACCESSORS(named_property_handler, Object)
10000 DECL_ACCESSORS(indexed_property_handler, Object)
10001 DECL_ACCESSORS(instance_template, Object)
10002 DECL_ACCESSORS(class_name, Object)
10003 DECL_ACCESSORS(signature, Object)
10004 DECL_ACCESSORS(instance_call_handler, Object)
10005 DECL_ACCESSORS(access_check_info, Object)
10006 DECL_ACCESSORS(flag, Smi)
10008 inline int length() const;
10009 inline void set_length(int value);
10011 // Following properties use flag bits.
10012 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10013 DECL_BOOLEAN_ACCESSORS(undetectable)
10014 // If the bit is set, object instances created by this function
10015 // requires access check.
10016 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10017 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10018 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10019 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10020 DECL_BOOLEAN_ACCESSORS(instantiated)
10021 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10023 DECLARE_CAST(FunctionTemplateInfo)
10025 // Dispatched behavior.
10026 DECLARE_PRINTER(FunctionTemplateInfo)
10027 DECLARE_VERIFIER(FunctionTemplateInfo)
10029 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10030 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10031 static const int kPrototypeTemplateOffset =
10032 kCallCodeOffset + kPointerSize;
10033 static const int kParentTemplateOffset =
10034 kPrototypeTemplateOffset + kPointerSize;
10035 static const int kNamedPropertyHandlerOffset =
10036 kParentTemplateOffset + kPointerSize;
10037 static const int kIndexedPropertyHandlerOffset =
10038 kNamedPropertyHandlerOffset + kPointerSize;
10039 static const int kInstanceTemplateOffset =
10040 kIndexedPropertyHandlerOffset + kPointerSize;
10041 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10042 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10043 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10044 static const int kAccessCheckInfoOffset =
10045 kInstanceCallHandlerOffset + kPointerSize;
10046 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10047 static const int kLengthOffset = kFlagOffset + kPointerSize;
10048 static const int kSize = kLengthOffset + kPointerSize;
10050 // Returns true if |object| is an instance of this function template.
10051 bool IsTemplateFor(Object* object);
10052 bool IsTemplateFor(Map* map);
10054 // Returns the holder JSObject if the function can legally be called with this
10055 // receiver. Returns Heap::null_value() if the call is illegal.
10056 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10059 // Bit position in the flag, from least significant bit position.
10060 static const int kHiddenPrototypeBit = 0;
10061 static const int kUndetectableBit = 1;
10062 static const int kNeedsAccessCheckBit = 2;
10063 static const int kReadOnlyPrototypeBit = 3;
10064 static const int kRemovePrototypeBit = 4;
10065 static const int kDoNotCacheBit = 5;
10066 static const int kInstantiatedBit = 6;
10067 static const int kAcceptAnyReceiver = 7;
10069 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10073 class ObjectTemplateInfo: public TemplateInfo {
10075 DECL_ACCESSORS(constructor, Object)
10076 DECL_ACCESSORS(internal_field_count, Object)
10078 DECLARE_CAST(ObjectTemplateInfo)
10080 // Dispatched behavior.
10081 DECLARE_PRINTER(ObjectTemplateInfo)
10082 DECLARE_VERIFIER(ObjectTemplateInfo)
10084 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10085 static const int kInternalFieldCountOffset =
10086 kConstructorOffset + kPointerSize;
10087 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10091 class TypeSwitchInfo: public Struct {
10093 DECL_ACCESSORS(types, Object)
10095 DECLARE_CAST(TypeSwitchInfo)
10097 // Dispatched behavior.
10098 DECLARE_PRINTER(TypeSwitchInfo)
10099 DECLARE_VERIFIER(TypeSwitchInfo)
10101 static const int kTypesOffset = Struct::kHeaderSize;
10102 static const int kSize = kTypesOffset + kPointerSize;
10106 // The DebugInfo class holds additional information for a function being
10108 class DebugInfo: public Struct {
10110 // The shared function info for the source being debugged.
10111 DECL_ACCESSORS(shared, SharedFunctionInfo)
10112 // Code object for the patched code. This code object is the code object
10113 // currently active for the function.
10114 DECL_ACCESSORS(code, Code)
10115 // Fixed array holding status information for each active break point.
10116 DECL_ACCESSORS(break_points, FixedArray)
10118 // Check if there is a break point at a code position.
10119 bool HasBreakPoint(int code_position);
10120 // Get the break point info object for a code position.
10121 Object* GetBreakPointInfo(int code_position);
10122 // Clear a break point.
10123 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10125 Handle<Object> break_point_object);
10126 // Set a break point.
10127 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10128 int source_position, int statement_position,
10129 Handle<Object> break_point_object);
10130 // Get the break point objects for a code position.
10131 Handle<Object> GetBreakPointObjects(int code_position);
10132 // Find the break point info holding this break point object.
10133 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10134 Handle<Object> break_point_object);
10135 // Get the number of break points for this function.
10136 int GetBreakPointCount();
10138 DECLARE_CAST(DebugInfo)
10140 // Dispatched behavior.
10141 DECLARE_PRINTER(DebugInfo)
10142 DECLARE_VERIFIER(DebugInfo)
10144 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10145 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10146 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10147 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10149 static const int kEstimatedNofBreakPointsInFunction = 16;
10152 static const int kNoBreakPointInfo = -1;
10154 // Lookup the index in the break_points array for a code position.
10155 int GetBreakPointInfoIndex(int code_position);
10157 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10161 // The BreakPointInfo class holds information for break points set in a
10162 // function. The DebugInfo object holds a BreakPointInfo object for each code
10163 // position with one or more break points.
10164 class BreakPointInfo: public Struct {
10166 // The position in the code for the break point.
10167 DECL_ACCESSORS(code_position, Smi)
10168 // The position in the source for the break position.
10169 DECL_ACCESSORS(source_position, Smi)
10170 // The position in the source for the last statement before this break
10172 DECL_ACCESSORS(statement_position, Smi)
10173 // List of related JavaScript break points.
10174 DECL_ACCESSORS(break_point_objects, Object)
10176 // Removes a break point.
10177 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10178 Handle<Object> break_point_object);
10179 // Set a break point.
10180 static void SetBreakPoint(Handle<BreakPointInfo> info,
10181 Handle<Object> break_point_object);
10182 // Check if break point info has this break point object.
10183 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10184 Handle<Object> break_point_object);
10185 // Get the number of break points for this code position.
10186 int GetBreakPointCount();
10188 DECLARE_CAST(BreakPointInfo)
10190 // Dispatched behavior.
10191 DECLARE_PRINTER(BreakPointInfo)
10192 DECLARE_VERIFIER(BreakPointInfo)
10194 static const int kCodePositionIndex = Struct::kHeaderSize;
10195 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10196 static const int kStatementPositionIndex =
10197 kSourcePositionIndex + kPointerSize;
10198 static const int kBreakPointObjectsIndex =
10199 kStatementPositionIndex + kPointerSize;
10200 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10203 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10207 #undef DECL_BOOLEAN_ACCESSORS
10208 #undef DECL_ACCESSORS
10209 #undef DECLARE_CAST
10210 #undef DECLARE_VERIFIER
10212 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10213 V(kStringTable, "string_table", "(Internalized strings)") \
10214 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10215 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10216 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10217 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10218 V(kTop, "top", "(Isolate)") \
10219 V(kRelocatable, "relocatable", "(Relocatable)") \
10220 V(kDebug, "debug", "(Debugger)") \
10221 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10222 V(kHandleScope, "handlescope", "(Handle scope)") \
10223 V(kBuiltins, "builtins", "(Builtins)") \
10224 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10225 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10226 V(kThreadManager, "threadmanager", "(Thread manager)") \
10227 V(kStrongRoots, "strong roots", "(Strong roots)") \
10228 V(kExtensions, "Extensions", "(Extensions)")
10230 class VisitorSynchronization : public AllStatic {
10232 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10234 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10237 #undef DECLARE_ENUM
10239 static const char* const kTags[kNumberOfSyncTags];
10240 static const char* const kTagNames[kNumberOfSyncTags];
10243 // Abstract base class for visiting, and optionally modifying, the
10244 // pointers contained in Objects. Used in GC and serialization/deserialization.
10245 class ObjectVisitor BASE_EMBEDDED {
10247 virtual ~ObjectVisitor() {}
10249 // Visits a contiguous arrays of pointers in the half-open range
10250 // [start, end). Any or all of the values may be modified on return.
10251 virtual void VisitPointers(Object** start, Object** end) = 0;
10253 // Handy shorthand for visiting a single pointer.
10254 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10256 // Visit weak next_code_link in Code object.
10257 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10259 // To allow lazy clearing of inline caches the visitor has
10260 // a rich interface for iterating over Code objects..
10262 // Visits a code target in the instruction stream.
10263 virtual void VisitCodeTarget(RelocInfo* rinfo);
10265 // Visits a code entry in a JS function.
10266 virtual void VisitCodeEntry(Address entry_address);
10268 // Visits a global property cell reference in the instruction stream.
10269 virtual void VisitCell(RelocInfo* rinfo);
10271 // Visits a runtime entry in the instruction stream.
10272 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10274 // Visits the resource of an one-byte or two-byte string.
10275 virtual void VisitExternalOneByteString(
10276 v8::String::ExternalOneByteStringResource** resource) {}
10277 virtual void VisitExternalTwoByteString(
10278 v8::String::ExternalStringResource** resource) {}
10280 // Visits a debug call target in the instruction stream.
10281 virtual void VisitDebugTarget(RelocInfo* rinfo);
10283 // Visits the byte sequence in a function's prologue that contains information
10284 // about the code's age.
10285 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10287 // Visit pointer embedded into a code object.
10288 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10290 // Visits an external reference embedded into a code object.
10291 virtual void VisitExternalReference(RelocInfo* rinfo);
10293 // Visits an external reference.
10294 virtual void VisitExternalReference(Address* p) {}
10296 // Visits an (encoded) internal reference.
10297 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10299 // Visits a handle that has an embedder-assigned class ID.
10300 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10302 // Intended for serialization/deserialization checking: insert, or
10303 // check for the presence of, a tag at this position in the stream.
10304 // Also used for marking up GC roots in heap snapshots.
10305 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10309 class StructBodyDescriptor : public
10310 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10312 static inline int SizeOf(Map* map, HeapObject* object);
10316 // BooleanBit is a helper class for setting and getting a bit in an
10318 class BooleanBit : public AllStatic {
10320 static inline bool get(Smi* smi, int bit_position) {
10321 return get(smi->value(), bit_position);
10324 static inline bool get(int value, int bit_position) {
10325 return (value & (1 << bit_position)) != 0;
10328 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10329 return Smi::FromInt(set(smi->value(), bit_position, v));
10332 static inline int set(int value, int bit_position, bool v) {
10334 value |= (1 << bit_position);
10336 value &= ~(1 << bit_position);
10342 } } // namespace v8::internal
10344 #endif // V8_OBJECTS_H_