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 // Valid hints for the abstract operation ToPrimitive,
172 // implemented according to ES6, section 7.1.1.
173 enum class ToPrimitiveHint { kDefault, kNumber, kString };
176 // Valid hints for the abstract operation OrdinaryToPrimitive,
177 // implemented according to ES6, section 7.1.1.
178 enum class OrdinaryToPrimitiveHint { kNumber, kString };
181 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
190 enum ExternalArrayType {
191 kExternalInt8Array = 1,
194 kExternalUint16Array,
196 kExternalUint32Array,
197 kExternalFloat32Array,
198 kExternalFloat64Array,
199 kExternalUint8ClampedArray,
203 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
204 return store_mode == STORE_TRANSITION_TO_OBJECT ||
205 store_mode == STORE_TRANSITION_TO_DOUBLE ||
206 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
207 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
211 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
212 KeyedAccessStoreMode store_mode) {
213 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
216 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
217 return STORE_AND_GROW_NO_TRANSITION;
219 return STANDARD_STORE;
223 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
224 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
225 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
229 enum IcCheckType { ELEMENT, PROPERTY };
232 // SKIP_WRITE_BARRIER skips the write barrier.
233 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
234 // only performs the generational part.
235 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
236 enum WriteBarrierMode {
238 UPDATE_WEAK_WRITE_BARRIER,
243 // Indicates whether a value can be loaded as a constant.
244 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
247 // PropertyNormalizationMode is used to specify whether to keep
248 // inobject properties when normalizing properties of a JSObject.
249 enum PropertyNormalizationMode {
250 CLEAR_INOBJECT_PROPERTIES,
251 KEEP_INOBJECT_PROPERTIES
255 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
256 // will give the fastest result by tailoring the map to the prototype, but that
257 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
258 // (at least for now) when dynamically modifying the prototype chain of an
259 // object using __proto__ or Object.setPrototypeOf.
260 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
263 // Indicates whether transitions can be added to a source map or not.
264 enum TransitionFlag {
270 // Indicates whether the transition is simple: the target map of the transition
271 // either extends the current map with a new property, or it modifies the
272 // property that was added last to the current map.
273 enum SimpleTransitionFlag {
274 SIMPLE_PROPERTY_TRANSITION,
280 // Indicates whether we are only interested in the descriptors of a particular
281 // map, or in all descriptors in the descriptor array.
282 enum DescriptorFlag {
287 // The GC maintains a bit of information, the MarkingParity, which toggles
288 // from odd to even and back every time marking is completed. Incremental
289 // marking can visit an object twice during a marking phase, so algorithms that
290 // that piggy-back on marking can use the parity to ensure that they only
291 // perform an operation on an object once per marking phase: they record the
292 // MarkingParity when they visit an object, and only re-visit the object when it
293 // is marked again and the MarkingParity changes.
300 // ICs store extra state in a Code object. The default extra state is
302 typedef int ExtraICState;
303 static const ExtraICState kNoExtraICState = 0;
305 // Instance size sentinel for objects of variable size.
306 const int kVariableSizeSentinel = 0;
308 // We may store the unsigned bit field as signed Smi value and do not
310 const int kStubMajorKeyBits = 7;
311 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
313 // All Maps have a field instance_type containing a InstanceType.
314 // It describes the type of the instances.
316 // As an example, a JavaScript object is a heap object and its map
317 // instance_type is JS_OBJECT_TYPE.
319 // The names of the string instance types are intended to systematically
320 // mirror their encoding in the instance_type field of the map. The default
321 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
322 // encoding is mentioned explicitly in the name. Likewise, the default
323 // representation is considered sequential. It is not mentioned in the
324 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
325 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
326 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
328 // NOTE: The following things are some that depend on the string types having
329 // instance_types that are less than those of all other types:
330 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
333 // NOTE: Everything following JS_VALUE_TYPE is considered a
334 // JSObject for GC purposes. The first four entries here have typeof
335 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
336 #define INSTANCE_TYPE_LIST(V) \
338 V(ONE_BYTE_STRING_TYPE) \
339 V(CONS_STRING_TYPE) \
340 V(CONS_ONE_BYTE_STRING_TYPE) \
341 V(SLICED_STRING_TYPE) \
342 V(SLICED_ONE_BYTE_STRING_TYPE) \
343 V(EXTERNAL_STRING_TYPE) \
344 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
345 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
346 V(SHORT_EXTERNAL_STRING_TYPE) \
347 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
348 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(INTERNALIZED_STRING_TYPE) \
351 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
352 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
360 V(SIMD128_VALUE_TYPE) \
366 V(PROPERTY_CELL_TYPE) \
368 V(HEAP_NUMBER_TYPE) \
369 V(MUTABLE_HEAP_NUMBER_TYPE) \
372 V(BYTECODE_ARRAY_TYPE) \
375 V(FIXED_INT8_ARRAY_TYPE) \
376 V(FIXED_UINT8_ARRAY_TYPE) \
377 V(FIXED_INT16_ARRAY_TYPE) \
378 V(FIXED_UINT16_ARRAY_TYPE) \
379 V(FIXED_INT32_ARRAY_TYPE) \
380 V(FIXED_UINT32_ARRAY_TYPE) \
381 V(FIXED_FLOAT32_ARRAY_TYPE) \
382 V(FIXED_FLOAT64_ARRAY_TYPE) \
383 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
387 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
388 V(DECLARED_ACCESSOR_INFO_TYPE) \
389 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
390 V(ACCESSOR_PAIR_TYPE) \
391 V(ACCESS_CHECK_INFO_TYPE) \
392 V(INTERCEPTOR_INFO_TYPE) \
393 V(CALL_HANDLER_INFO_TYPE) \
394 V(FUNCTION_TEMPLATE_INFO_TYPE) \
395 V(OBJECT_TEMPLATE_INFO_TYPE) \
396 V(SIGNATURE_INFO_TYPE) \
397 V(TYPE_SWITCH_INFO_TYPE) \
398 V(ALLOCATION_MEMENTO_TYPE) \
399 V(ALLOCATION_SITE_TYPE) \
402 V(POLYMORPHIC_CODE_CACHE_TYPE) \
403 V(TYPE_FEEDBACK_INFO_TYPE) \
404 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
406 V(PROTOTYPE_INFO_TYPE) \
407 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
409 V(FIXED_ARRAY_TYPE) \
410 V(FIXED_DOUBLE_ARRAY_TYPE) \
411 V(SHARED_FUNCTION_INFO_TYPE) \
414 V(JS_MESSAGE_OBJECT_TYPE) \
419 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
420 V(JS_GENERATOR_OBJECT_TYPE) \
422 V(JS_GLOBAL_OBJECT_TYPE) \
423 V(JS_BUILTINS_OBJECT_TYPE) \
424 V(JS_GLOBAL_PROXY_TYPE) \
426 V(JS_ARRAY_BUFFER_TYPE) \
427 V(JS_TYPED_ARRAY_TYPE) \
428 V(JS_DATA_VIEW_TYPE) \
432 V(JS_SET_ITERATOR_TYPE) \
433 V(JS_MAP_ITERATOR_TYPE) \
434 V(JS_ITERATOR_RESULT_TYPE) \
435 V(JS_WEAK_MAP_TYPE) \
436 V(JS_WEAK_SET_TYPE) \
439 V(JS_FUNCTION_TYPE) \
440 V(JS_FUNCTION_PROXY_TYPE) \
442 V(BREAK_POINT_INFO_TYPE)
445 // Since string types are not consecutive, this macro is used to
446 // iterate over them.
447 #define STRING_TYPE_LIST(V) \
448 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
449 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
451 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
452 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
454 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
455 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
456 SlicedOneByteString) \
457 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
459 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
460 external_one_byte_string, ExternalOneByteString) \
461 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
462 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
463 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
464 short_external_string, ShortExternalString) \
465 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
466 short_external_one_byte_string, ShortExternalOneByteString) \
467 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
468 ExternalTwoByteString::kShortSize, \
469 short_external_string_with_one_byte_data, \
470 ShortExternalStringWithOneByteData) \
472 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
473 InternalizedString) \
474 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
475 one_byte_internalized_string, OneByteInternalizedString) \
476 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
477 external_internalized_string, ExternalInternalizedString) \
478 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
479 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
480 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
481 ExternalTwoByteString::kSize, \
482 external_internalized_string_with_one_byte_data, \
483 ExternalInternalizedStringWithOneByteData) \
484 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
485 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
486 ShortExternalInternalizedString) \
487 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
488 ExternalOneByteString::kShortSize, \
489 short_external_one_byte_internalized_string, \
490 ShortExternalOneByteInternalizedString) \
491 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
492 ExternalTwoByteString::kShortSize, \
493 short_external_internalized_string_with_one_byte_data, \
494 ShortExternalInternalizedStringWithOneByteData)
496 // A struct is a simple object a set of object-valued fields. Including an
497 // object type in this causes the compiler to generate most of the boilerplate
498 // code for the class including allocation and garbage collection routines,
499 // casts and predicates. All you need to define is the class, methods and
500 // object verification routines. Easy, no?
502 // Note that for subtle reasons related to the ordering or numerical values of
503 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
505 #define STRUCT_LIST(V) \
507 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
508 executable_accessor_info) \
509 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
510 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
511 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
512 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
513 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
514 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
515 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
516 V(SCRIPT, Script, script) \
517 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
518 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
519 V(CODE_CACHE, CodeCache, code_cache) \
520 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
521 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
522 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
523 V(DEBUG_INFO, DebugInfo, debug_info) \
524 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
525 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
526 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
527 SloppyBlockWithEvalContextExtension, \
528 sloppy_block_with_eval_context_extension)
530 // We use the full 8 bits of the instance_type field to encode heap object
531 // instance types. The high-order bit (bit 7) is set if the object is not a
532 // string, and cleared if it is a string.
533 const uint32_t kIsNotStringMask = 0x80;
534 const uint32_t kStringTag = 0x0;
535 const uint32_t kNotStringTag = 0x80;
537 // Bit 6 indicates that the object is an internalized string (if set) or not.
538 // Bit 7 has to be clear as well.
539 const uint32_t kIsNotInternalizedMask = 0x40;
540 const uint32_t kNotInternalizedTag = 0x40;
541 const uint32_t kInternalizedTag = 0x0;
543 // If bit 7 is clear then bit 2 indicates whether the string consists of
544 // two-byte characters or one-byte characters.
545 const uint32_t kStringEncodingMask = 0x4;
546 const uint32_t kTwoByteStringTag = 0x0;
547 const uint32_t kOneByteStringTag = 0x4;
549 // If bit 7 is clear, the low-order 2 bits indicate the representation
551 const uint32_t kStringRepresentationMask = 0x03;
552 enum StringRepresentationTag {
554 kConsStringTag = 0x1,
555 kExternalStringTag = 0x2,
556 kSlicedStringTag = 0x3
558 const uint32_t kIsIndirectStringMask = 0x1;
559 const uint32_t kIsIndirectStringTag = 0x1;
560 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
561 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
562 STATIC_ASSERT((kConsStringTag &
563 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
564 STATIC_ASSERT((kSlicedStringTag &
565 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
567 // Use this mask to distinguish between cons and slice only after making
568 // sure that the string is one of the two (an indirect string).
569 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
570 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
572 // If bit 7 is clear, then bit 3 indicates whether this two-byte
573 // string actually contains one byte data.
574 const uint32_t kOneByteDataHintMask = 0x08;
575 const uint32_t kOneByteDataHintTag = 0x08;
577 // If bit 7 is clear and string representation indicates an external string,
578 // then bit 4 indicates whether the data pointer is cached.
579 const uint32_t kShortExternalStringMask = 0x10;
580 const uint32_t kShortExternalStringTag = 0x10;
583 // A ConsString with an empty string as the right side is a candidate
584 // for being shortcut by the garbage collector. We don't allocate any
585 // non-flat internalized strings, so we do not shortcut them thereby
586 // avoiding turning internalized strings into strings. The bit-masks
587 // below contain the internalized bit as additional safety.
588 // See heap.cc, mark-compact.cc and objects-visiting.cc.
589 const uint32_t kShortcutTypeMask =
591 kIsNotInternalizedMask |
592 kStringRepresentationMask;
593 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
595 static inline bool IsShortcutCandidate(int type) {
596 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
602 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
603 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
604 ONE_BYTE_INTERNALIZED_STRING_TYPE =
605 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
606 EXTERNAL_INTERNALIZED_STRING_TYPE =
607 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
608 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
609 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
610 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
611 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
613 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
614 kShortExternalStringTag |
616 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
617 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
619 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
620 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
621 kShortExternalStringTag | kInternalizedTag,
622 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 ONE_BYTE_STRING_TYPE =
624 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
626 CONS_ONE_BYTE_STRING_TYPE =
627 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
629 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
630 SLICED_ONE_BYTE_STRING_TYPE =
631 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
632 EXTERNAL_STRING_TYPE =
633 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
634 EXTERNAL_ONE_BYTE_STRING_TYPE =
635 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
636 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
637 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
639 SHORT_EXTERNAL_STRING_TYPE =
640 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
642 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
643 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
644 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
648 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
650 // Other primitives (cannot contain non-map-word pointers to heap objects).
653 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
655 // Objects allocated in their own spaces (never in new space).
659 // "Data", objects that cannot contain non-map-word pointers to heap
661 MUTABLE_HEAP_NUMBER_TYPE,
666 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
667 FIXED_UINT8_ARRAY_TYPE,
668 FIXED_INT16_ARRAY_TYPE,
669 FIXED_UINT16_ARRAY_TYPE,
670 FIXED_INT32_ARRAY_TYPE,
671 FIXED_UINT32_ARRAY_TYPE,
672 FIXED_FLOAT32_ARRAY_TYPE,
673 FIXED_FLOAT64_ARRAY_TYPE,
674 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
675 FIXED_DOUBLE_ARRAY_TYPE,
676 FILLER_TYPE, // LAST_DATA_TYPE
679 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
680 DECLARED_ACCESSOR_INFO_TYPE,
681 EXECUTABLE_ACCESSOR_INFO_TYPE,
683 ACCESS_CHECK_INFO_TYPE,
684 INTERCEPTOR_INFO_TYPE,
685 CALL_HANDLER_INFO_TYPE,
686 FUNCTION_TEMPLATE_INFO_TYPE,
687 OBJECT_TEMPLATE_INFO_TYPE,
689 TYPE_SWITCH_INFO_TYPE,
690 ALLOCATION_SITE_TYPE,
691 ALLOCATION_MEMENTO_TYPE,
694 POLYMORPHIC_CODE_CACHE_TYPE,
695 TYPE_FEEDBACK_INFO_TYPE,
696 ALIASED_ARGUMENTS_ENTRY_TYPE,
699 BREAK_POINT_INFO_TYPE,
701 SHARED_FUNCTION_INFO_TYPE,
706 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
708 // All the following types are subtypes of JSReceiver, which corresponds to
709 // objects in the JS sense. The first and the last type in this range are
710 // the two forms of function. This organization enables using the same
711 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
712 // NONCALLABLE_JS_OBJECT range.
713 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
714 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
715 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
716 JS_MESSAGE_OBJECT_TYPE,
719 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
720 JS_GENERATOR_OBJECT_TYPE,
722 JS_GLOBAL_OBJECT_TYPE,
723 JS_BUILTINS_OBJECT_TYPE,
724 JS_GLOBAL_PROXY_TYPE,
726 JS_ARRAY_BUFFER_TYPE,
731 JS_SET_ITERATOR_TYPE,
732 JS_MAP_ITERATOR_TYPE,
733 JS_ITERATOR_RESULT_TYPE,
737 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
741 LAST_TYPE = JS_FUNCTION_TYPE,
742 FIRST_NAME_TYPE = FIRST_TYPE,
743 LAST_NAME_TYPE = SYMBOL_TYPE,
744 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
745 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
746 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
747 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
748 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
749 // Boundaries for testing for a fixed typed array.
750 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
751 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
752 // Boundary for promotion to old space.
753 LAST_DATA_TYPE = FILLER_TYPE,
754 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
755 // Note that there is no range for JSObject or JSProxy, since their subtypes
756 // are not continuous in this enum! The enum ranges instead reflect the
757 // external class names, where proxies are treated as either ordinary objects,
759 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
760 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
761 // Boundaries for testing the types represented as JSObject
762 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
763 LAST_JS_OBJECT_TYPE = LAST_TYPE,
764 // Boundaries for testing the types represented as JSProxy
765 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
766 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
767 // Boundaries for testing whether the type is a JavaScript object.
768 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
769 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
770 // Boundaries for testing the types for which typeof is "object".
771 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
772 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
773 // Note that the types for which typeof is "function" are not continuous.
774 // Define this so that we can put assertions on discrete checks.
775 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
778 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
779 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
780 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
781 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
784 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
785 V(FAST_ELEMENTS_SUB_TYPE) \
786 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
787 V(FAST_PROPERTIES_SUB_TYPE) \
788 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
789 V(MAP_CODE_CACHE_SUB_TYPE) \
790 V(SCOPE_INFO_SUB_TYPE) \
791 V(STRING_TABLE_SUB_TYPE) \
792 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
793 V(TRANSITION_ARRAY_SUB_TYPE)
795 enum FixedArraySubInstanceType {
796 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
797 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
798 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
799 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
803 // TODO(bmeurer): Remove this in favor of the ComparisonResult below.
813 // Result of an abstract relational comparison of x and y, implemented according
814 // to ES6 section 7.2.11 Abstract Relational Comparison.
815 enum class ComparisonResult {
818 kGreaterThan, // x > x
819 kUndefined // at least one of x or y was undefined or NaN
823 #define DECL_BOOLEAN_ACCESSORS(name) \
824 inline bool name() const; \
825 inline void set_##name(bool value); \
828 #define DECL_ACCESSORS(name, type) \
829 inline type* name() const; \
830 inline void set_##name(type* value, \
831 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
834 #define DECLARE_CAST(type) \
835 INLINE(static type* cast(Object* object)); \
836 INLINE(static const type* cast(const Object* object));
840 class AllocationSite;
841 class AllocationSiteCreationContext;
842 class AllocationSiteUsageContext;
845 class ElementsAccessor;
846 class FixedArrayBase;
847 class FunctionLiteral;
849 class JSBuiltinsObject;
850 class LayoutDescriptor;
851 class LookupIterator;
852 class ObjectHashTable;
855 class SafepointEntry;
856 class SharedFunctionInfo;
858 class TypeFeedbackInfo;
859 class TypeFeedbackVector;
862 // We cannot just say "class HeapType;" if it is created from a template... =8-?
863 template<class> class TypeImpl;
864 struct HeapTypeConfig;
865 typedef TypeImpl<HeapTypeConfig> HeapType;
868 // A template-ized version of the IsXXX functions.
869 template <class C> inline bool Is(Object* obj);
872 #define DECLARE_VERIFIER(Name) void Name##Verify();
874 #define DECLARE_VERIFIER(Name)
878 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
880 #define DECLARE_PRINTER(Name)
884 #define OBJECT_TYPE_LIST(V) \
889 #define HEAP_OBJECT_TYPE_LIST(V) \
891 V(MutableHeapNumber) \
910 V(ExternalTwoByteString) \
911 V(ExternalOneByteString) \
912 V(SeqTwoByteString) \
913 V(SeqOneByteString) \
914 V(InternalizedString) \
917 V(FixedTypedArrayBase) \
920 V(FixedUint16Array) \
922 V(FixedUint32Array) \
924 V(FixedFloat32Array) \
925 V(FixedFloat64Array) \
926 V(FixedUint8ClampedArray) \
932 V(JSContextExtensionObject) \
933 V(JSGeneratorObject) \
935 V(LayoutDescriptor) \
939 V(TypeFeedbackVector) \
940 V(DeoptimizationInputData) \
941 V(DeoptimizationOutputData) \
945 V(FixedDoubleArray) \
949 V(ScriptContextTable) \
955 V(SharedFunctionInfo) \
964 V(JSArrayBufferView) \
973 V(JSIteratorResult) \
974 V(JSWeakCollection) \
981 V(NormalizedMapCache) \
982 V(CompilationCacheTable) \
983 V(CodeCacheHashTable) \
984 V(PolymorphicCodeCacheHashTable) \
989 V(JSBuiltinsObject) \
991 V(UndetectableObject) \
992 V(AccessCheckNeeded) \
1000 // Object is the abstract superclass for all classes in the
1001 // object hierarchy.
1002 // Object does not use any virtual functions to avoid the
1003 // allocation of the C++ vtable.
1004 // Since both Smi and HeapObject are subclasses of Object no
1005 // data members can be present in Object.
1009 bool IsObject() const { return true; }
1011 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1012 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1013 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1014 #undef IS_TYPE_FUNCTION_DECL
1016 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1017 // a keyed store is of the form a[expression] = foo.
1018 enum StoreFromKeyed {
1019 MAY_BE_STORE_FROM_KEYED,
1020 CERTAINLY_NOT_STORE_FROM_KEYED
1023 INLINE(bool IsFixedArrayBase() const);
1024 INLINE(bool IsExternal() const);
1025 INLINE(bool IsAccessorInfo() const);
1027 INLINE(bool IsStruct() const);
1028 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1029 INLINE(bool Is##Name() const);
1030 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1031 #undef DECLARE_STRUCT_PREDICATE
1033 // ES6, section 7.2.3 IsCallable.
1034 INLINE(bool IsCallable() const);
1036 // ES6, section 7.2.4 IsConstructor.
1037 INLINE(bool IsConstructor() const);
1039 INLINE(bool IsSpecObject()) const;
1040 INLINE(bool IsTemplateInfo()) const;
1041 INLINE(bool IsNameDictionary() const);
1042 INLINE(bool IsGlobalDictionary() const);
1043 INLINE(bool IsSeededNumberDictionary() const);
1044 INLINE(bool IsUnseededNumberDictionary() const);
1045 INLINE(bool IsOrderedHashSet() const);
1046 INLINE(bool IsOrderedHashMap() const);
1047 static bool IsPromise(Handle<Object> object);
1050 INLINE(bool IsUndefined() const);
1051 INLINE(bool IsNull() const);
1052 INLINE(bool IsTheHole() const);
1053 INLINE(bool IsException() const);
1054 INLINE(bool IsUninitialized() const);
1055 INLINE(bool IsTrue() const);
1056 INLINE(bool IsFalse() const);
1057 INLINE(bool IsArgumentsMarker() const);
1059 // Filler objects (fillers and free space objects).
1060 INLINE(bool IsFiller() const);
1062 // Extract the number.
1063 inline double Number() const;
1064 INLINE(bool IsNaN() const);
1065 INLINE(bool IsMinusZero() const);
1066 bool ToInt32(int32_t* value);
1067 bool ToUint32(uint32_t* value);
1069 inline Representation OptimalRepresentation();
1071 inline ElementsKind OptimalElementsKind();
1073 inline bool FitsRepresentation(Representation representation);
1075 // Checks whether two valid primitive encodings of a property name resolve to
1076 // the same logical property. E.g., the smi 1, the string "1" and the double
1077 // 1 all refer to the same property, so this helper will return true.
1078 inline bool KeyEquals(Object* other);
1080 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1082 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1083 Handle<Object> object,
1084 Representation representation);
1086 inline static Handle<Object> WrapForRead(Isolate* isolate,
1087 Handle<Object> object,
1088 Representation representation);
1090 // Returns true if the object is of the correct type to be used as a
1091 // implementation of a JSObject's elements.
1092 inline bool HasValidElements();
1094 inline bool HasSpecificClassOf(String* name);
1096 bool BooleanValue(); // ECMA-262 9.2.
1098 // ES6 section 7.2.11 Abstract Relational Comparison
1099 MUST_USE_RESULT static Maybe<ComparisonResult> Compare(
1100 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1102 // ES6 section 7.2.12 Abstract Equality Comparison
1103 MUST_USE_RESULT static Maybe<bool> Equals(Handle<Object> x, Handle<Object> y);
1105 // ES6 section 7.2.13 Strict Equality Comparison
1106 bool StrictEquals(Object* that);
1108 // Convert to a JSObject if needed.
1109 // native_context is used when creating wrapper object.
1110 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1111 Handle<Object> object);
1112 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1113 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1115 // ES6 section 7.1.14 ToPropertyKey
1116 MUST_USE_RESULT static MaybeHandle<Name> ToName(Isolate* isolate,
1117 Handle<Object> input);
1119 // ES6 section 7.1.1 ToPrimitive
1120 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1121 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1123 // ES6 section 7.1.3 ToNumber
1124 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1126 // ES6 section 7.1.12 ToString
1127 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1128 Handle<Object> input);
1130 // ES6 section 7.3.9 GetMethod
1131 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1132 Handle<JSReceiver> receiver, Handle<Name> name);
1134 // ES6 section 12.5.6 The typeof Operator
1135 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1137 // ES6 section 12.6 Multiplicative Operators
1138 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1139 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1140 Strength strength = Strength::WEAK);
1141 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1142 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1143 Strength strength = Strength::WEAK);
1144 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1145 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1146 Strength strength = Strength::WEAK);
1148 // ES6 section 12.7 Additive Operators
1149 MUST_USE_RESULT static MaybeHandle<Object> Add(
1150 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1151 Strength strength = Strength::WEAK);
1152 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1153 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1154 Strength strength = Strength::WEAK);
1156 // ES6 section 12.8 Bitwise Shift Operators
1157 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1158 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1159 Strength strength = Strength::WEAK);
1160 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1161 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1162 Strength strength = Strength::WEAK);
1163 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1164 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1165 Strength strength = Strength::WEAK);
1167 // ES6 section 12.9 Relational Operators
1168 MUST_USE_RESULT static inline Maybe<bool> GreaterThan(
1169 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1170 MUST_USE_RESULT static inline Maybe<bool> GreaterThanOrEqual(
1171 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1172 MUST_USE_RESULT static inline Maybe<bool> LessThan(
1173 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1174 MUST_USE_RESULT static inline Maybe<bool> LessThanOrEqual(
1175 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1177 // ES6 section 12.11 Binary Bitwise Operators
1178 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1179 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1180 Strength strength = Strength::WEAK);
1181 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1182 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1183 Strength strength = Strength::WEAK);
1184 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1185 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1186 Strength strength = Strength::WEAK);
1188 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1189 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1191 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1192 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1193 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1194 LanguageMode language_mode,
1195 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1197 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1198 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1199 StoreFromKeyed store_mode);
1201 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1202 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1203 StoreFromKeyed store_mode);
1205 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1206 LookupIterator* it, LanguageMode language_mode);
1207 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1208 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1209 LanguageMode language_mode);
1210 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1211 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1212 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1213 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1214 Handle<Object> value, LanguageMode language_mode);
1215 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1216 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1217 LanguageMode language_mode);
1218 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1219 LookupIterator* it, Handle<Object> value);
1220 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1221 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1222 LanguageMode language_mode, StoreFromKeyed store_mode);
1223 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1224 Handle<Object> object, Handle<Name> name,
1225 LanguageMode language_mode = SLOPPY);
1226 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1227 Isolate* isolate, Handle<Object> object, const char* key,
1228 LanguageMode language_mode = SLOPPY);
1229 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1230 Handle<Object> object, Handle<Name> name,
1231 LanguageMode language_mode = SLOPPY);
1233 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1234 LookupIterator* it, LanguageMode language_mode);
1235 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1236 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1238 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1239 Handle<Object> receiver,
1240 Handle<JSReceiver> getter);
1241 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1242 Handle<Object> receiver,
1243 Handle<JSReceiver> setter,
1244 Handle<Object> value);
1246 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1247 Isolate* isolate, Handle<Object> object, uint32_t index,
1248 LanguageMode language_mode = SLOPPY);
1250 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1251 Isolate* isolate, Handle<Object> object, uint32_t index,
1252 Handle<Object> value, LanguageMode language_mode);
1254 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1255 Isolate* isolate, Handle<Object> receiver);
1257 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1259 // Returns the permanent hash code associated with this object. May return
1260 // undefined if not yet created.
1263 // Returns undefined for JSObjects, but returns the hash code for simple
1264 // objects. This avoids a double lookup in the cases where we know we will
1265 // add the hash to the JSObject if it does not already exist.
1266 Object* GetSimpleHash();
1268 // Returns the permanent hash code associated with this object depending on
1269 // the actual object type. May create and store a hash code if needed and none
1271 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1273 // Checks whether this object has the same value as the given one. This
1274 // function is implemented according to ES5, section 9.12 and can be used
1275 // to implement the Harmony "egal" function.
1276 bool SameValue(Object* other);
1278 // Checks whether this object has the same value as the given one.
1279 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1280 // This function is implemented according to ES6, section 7.2.4 and is used
1281 // by ES6 Map and Set.
1282 bool SameValueZero(Object* other);
1284 // Tries to convert an object to an array length. Returns true and sets the
1285 // output parameter if it succeeds.
1286 inline bool ToArrayLength(uint32_t* index);
1288 // Tries to convert an object to an array index. Returns true and sets the
1289 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1290 // allow kMaxUInt32.
1291 inline bool ToArrayIndex(uint32_t* index);
1293 // Returns true if this is a JSValue containing a string and the index is
1294 // < the length of the string. Used to implement [] on strings.
1295 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1297 DECLARE_VERIFIER(Object)
1299 // Verify a pointer is a valid object pointer.
1300 static void VerifyPointer(Object* p);
1303 inline void VerifyApiCallResultType();
1305 // Prints this object without details.
1306 void ShortPrint(FILE* out = stdout);
1308 // Prints this object without details to a message accumulator.
1309 void ShortPrint(StringStream* accumulator);
1311 void ShortPrint(std::ostream& os); // NOLINT
1313 DECLARE_CAST(Object)
1315 // Layout description.
1316 static const int kHeaderSize = 0; // Object does not take up any space.
1319 // For our gdb macros, we should perhaps change these in the future.
1322 // Prints this object with details.
1323 void Print(std::ostream& os); // NOLINT
1325 void Print() { ShortPrint(); }
1326 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1330 friend class LookupIterator;
1331 friend class PrototypeIterator;
1333 // Return the map of the root of object's prototype chain.
1334 Map* GetRootMap(Isolate* isolate);
1336 // Helper for SetProperty and SetSuperProperty.
1337 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1338 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1339 StoreFromKeyed store_mode, bool* found);
1341 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1345 // In objects.h to be usable without objects-inl.h inclusion.
1346 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1347 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1351 explicit Brief(const Object* const v) : value(v) {}
1352 const Object* value;
1356 std::ostream& operator<<(std::ostream& os, const Brief& v);
1359 // Smi represents integer Numbers that can be stored in 31 bits.
1360 // Smis are immediate which means they are NOT allocated in the heap.
1361 // The this pointer has the following format: [31 bit signed int] 0
1362 // For long smis it has the following format:
1363 // [32 bit signed int] [31 bits zero padding] 0
1364 // Smi stands for small integer.
1365 class Smi: public Object {
1367 // Returns the integer value.
1368 inline int value() const { return Internals::SmiValue(this); }
1370 // Convert a value to a Smi object.
1371 static inline Smi* FromInt(int value) {
1372 DCHECK(Smi::IsValid(value));
1373 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1376 static inline Smi* FromIntptr(intptr_t value) {
1377 DCHECK(Smi::IsValid(value));
1378 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1379 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1382 // Returns whether value can be represented in a Smi.
1383 static inline bool IsValid(intptr_t value) {
1384 bool result = Internals::IsValidSmi(value);
1385 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1391 // Dispatched behavior.
1392 void SmiPrint(std::ostream& os) const; // NOLINT
1393 DECLARE_VERIFIER(Smi)
1395 static const int kMinValue =
1396 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1397 static const int kMaxValue = -(kMinValue + 1);
1400 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1404 // Heap objects typically have a map pointer in their first word. However,
1405 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1406 // encoded in the first word. The class MapWord is an abstraction of the
1407 // value in a heap object's first word.
1408 class MapWord BASE_EMBEDDED {
1410 // Normal state: the map word contains a map pointer.
1412 // Create a map word from a map pointer.
1413 static inline MapWord FromMap(const Map* map);
1415 // View this map word as a map pointer.
1416 inline Map* ToMap();
1419 // Scavenge collection: the map word of live objects in the from space
1420 // contains a forwarding address (a heap object pointer in the to space).
1422 // True if this map word is a forwarding address for a scavenge
1423 // collection. Only valid during a scavenge collection (specifically,
1424 // when all map words are heap object pointers, i.e. not during a full GC).
1425 inline bool IsForwardingAddress();
1427 // Create a map word from a forwarding address.
1428 static inline MapWord FromForwardingAddress(HeapObject* object);
1430 // View this map word as a forwarding address.
1431 inline HeapObject* ToForwardingAddress();
1433 static inline MapWord FromRawValue(uintptr_t value) {
1434 return MapWord(value);
1437 inline uintptr_t ToRawValue() {
1442 // HeapObject calls the private constructor and directly reads the value.
1443 friend class HeapObject;
1445 explicit MapWord(uintptr_t value) : value_(value) {}
1451 // The content of an heap object (except for the map pointer). kTaggedValues
1452 // objects can contain both heap pointers and Smis, kMixedValues can contain
1453 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1454 // objects can contain raw values and Smis.
1455 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1458 // HeapObject is the superclass for all classes describing heap allocated
1460 class HeapObject: public Object {
1462 // [map]: Contains a map which contains the object's reflective
1464 inline Map* map() const;
1465 inline void set_map(Map* value);
1466 // The no-write-barrier version. This is OK if the object is white and in
1467 // new space, or if the value is an immortal immutable object, like the maps
1468 // of primitive (non-JS) objects like strings, heap numbers etc.
1469 inline void set_map_no_write_barrier(Map* value);
1471 // Get the map using acquire load.
1472 inline Map* synchronized_map();
1473 inline MapWord synchronized_map_word() const;
1475 // Set the map using release store
1476 inline void synchronized_set_map(Map* value);
1477 inline void synchronized_set_map_no_write_barrier(Map* value);
1478 inline void synchronized_set_map_word(MapWord map_word);
1480 // During garbage collection, the map word of a heap object does not
1481 // necessarily contain a map pointer.
1482 inline MapWord map_word() const;
1483 inline void set_map_word(MapWord map_word);
1485 // The Heap the object was allocated in. Used also to access Isolate.
1486 inline Heap* GetHeap() const;
1488 // Convenience method to get current isolate.
1489 inline Isolate* GetIsolate() const;
1491 // Converts an address to a HeapObject pointer.
1492 static inline HeapObject* FromAddress(Address address) {
1493 DCHECK_TAG_ALIGNED(address);
1494 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1497 // Returns the address of this HeapObject.
1498 inline Address address() {
1499 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1502 // Iterates over pointers contained in the object (including the Map)
1503 void Iterate(ObjectVisitor* v);
1505 // Iterates over all pointers contained in the object except the
1506 // first map pointer. The object type is given in the first
1507 // parameter. This function does not access the map pointer in the
1508 // object, and so is safe to call while the map pointer is modified.
1509 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1511 // Returns the heap object's size in bytes
1514 // Indicates what type of values this heap object may contain.
1515 inline HeapObjectContents ContentType();
1517 // Given a heap object's map pointer, returns the heap size in bytes
1518 // Useful when the map pointer field is used for other purposes.
1520 inline int SizeFromMap(Map* map);
1522 // Returns the field at offset in obj, as a read/write Object* reference.
1523 // Does no checking, and is safe to use during GC, while maps are invalid.
1524 // Does not invoke write barrier, so should only be assigned to
1525 // during marking GC.
1526 static inline Object** RawField(HeapObject* obj, int offset);
1528 // Adds the |code| object related to |name| to the code cache of this map. If
1529 // this map is a dictionary map that is shared, the map copied and installed
1531 static void UpdateMapCodeCache(Handle<HeapObject> object,
1535 DECLARE_CAST(HeapObject)
1537 // Return the write barrier mode for this. Callers of this function
1538 // must be able to present a reference to an DisallowHeapAllocation
1539 // object as a sign that they are not going to use this function
1540 // from code that allocates and thus invalidates the returned write
1542 inline WriteBarrierMode GetWriteBarrierMode(
1543 const DisallowHeapAllocation& promise);
1545 // Dispatched behavior.
1546 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1548 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1550 DECLARE_PRINTER(HeapObject)
1551 DECLARE_VERIFIER(HeapObject)
1553 inline void VerifyObjectField(int offset);
1554 inline void VerifySmiField(int offset);
1556 // Verify a pointer is a valid HeapObject pointer that points to object
1557 // areas in the heap.
1558 static void VerifyHeapPointer(Object* p);
1561 inline AllocationAlignment RequiredAlignment();
1563 // Layout description.
1564 // First field in a heap object is map.
1565 static const int kMapOffset = Object::kHeaderSize;
1566 static const int kHeaderSize = kMapOffset + kPointerSize;
1568 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1571 // helpers for calling an ObjectVisitor to iterate over pointers in the
1572 // half-open range [start, end) specified as integer offsets
1573 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1574 // as above, for the single element at "offset"
1575 inline void IteratePointer(ObjectVisitor* v, int offset);
1576 // as above, for the next code link of a code object.
1577 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1580 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1584 // This class describes a body of an object of a fixed size
1585 // in which all pointer fields are located in the [start_offset, end_offset)
1587 template<int start_offset, int end_offset, int size>
1588 class FixedBodyDescriptor {
1590 static const int kStartOffset = start_offset;
1591 static const int kEndOffset = end_offset;
1592 static const int kSize = size;
1594 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1596 template<typename StaticVisitor>
1597 static inline void IterateBody(HeapObject* obj) {
1598 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1599 HeapObject::RawField(obj, end_offset));
1604 // This class describes a body of an object of a variable size
1605 // in which all pointer fields are located in the [start_offset, object_size)
1607 template<int start_offset>
1608 class FlexibleBodyDescriptor {
1610 static const int kStartOffset = start_offset;
1612 static inline void IterateBody(HeapObject* obj,
1616 template<typename StaticVisitor>
1617 static inline void IterateBody(HeapObject* obj, int object_size) {
1618 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1619 HeapObject::RawField(obj, object_size));
1624 // The HeapNumber class describes heap allocated numbers that cannot be
1625 // represented in a Smi (small integer)
1626 class HeapNumber: public HeapObject {
1628 // [value]: number value.
1629 inline double value() const;
1630 inline void set_value(double value);
1632 DECLARE_CAST(HeapNumber)
1634 // Dispatched behavior.
1635 bool HeapNumberBooleanValue();
1637 void HeapNumberPrint(std::ostream& os); // NOLINT
1638 DECLARE_VERIFIER(HeapNumber)
1640 inline int get_exponent();
1641 inline int get_sign();
1643 // Layout description.
1644 static const int kValueOffset = HeapObject::kHeaderSize;
1645 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1646 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1647 // words within double numbers are endian dependent and they are set
1649 #if defined(V8_TARGET_LITTLE_ENDIAN)
1650 static const int kMantissaOffset = kValueOffset;
1651 static const int kExponentOffset = kValueOffset + 4;
1652 #elif defined(V8_TARGET_BIG_ENDIAN)
1653 static const int kMantissaOffset = kValueOffset + 4;
1654 static const int kExponentOffset = kValueOffset;
1656 #error Unknown byte ordering
1659 static const int kSize = kValueOffset + kDoubleSize;
1660 static const uint32_t kSignMask = 0x80000000u;
1661 static const uint32_t kExponentMask = 0x7ff00000u;
1662 static const uint32_t kMantissaMask = 0xfffffu;
1663 static const int kMantissaBits = 52;
1664 static const int kExponentBits = 11;
1665 static const int kExponentBias = 1023;
1666 static const int kExponentShift = 20;
1667 static const int kInfinityOrNanExponent =
1668 (kExponentMask >> kExponentShift) - kExponentBias;
1669 static const int kMantissaBitsInTopWord = 20;
1670 static const int kNonMantissaBitsInTopWord = 12;
1673 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1677 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1678 class Simd128Value : public HeapObject {
1680 DECLARE_CAST(Simd128Value)
1682 DECLARE_PRINTER(Simd128Value)
1683 DECLARE_VERIFIER(Simd128Value)
1685 static Handle<String> ToString(Handle<Simd128Value> input);
1687 // Equality operations.
1688 inline bool Equals(Simd128Value* that);
1689 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1691 // Checks that another instance is bit-wise equal.
1692 bool BitwiseEquals(const Simd128Value* other) const;
1693 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1694 uint32_t Hash() const;
1695 // Copies the 16 bytes of SIMD data to the destination address.
1696 void CopyBits(void* destination) const;
1698 // Layout description.
1699 static const int kValueOffset = HeapObject::kHeaderSize;
1700 static const int kSize = kValueOffset + kSimd128Size;
1703 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1707 // V has parameters (TYPE, Type, type, lane count, lane type)
1708 #define SIMD128_TYPES(V) \
1709 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1710 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1711 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1712 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1713 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1714 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1715 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1716 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1717 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1718 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1720 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1721 class Type final : public Simd128Value { \
1723 inline lane_type get_lane(int lane) const; \
1724 inline void set_lane(int lane, lane_type value); \
1726 DECLARE_CAST(Type) \
1728 DECLARE_PRINTER(Type) \
1730 static Handle<String> ToString(Handle<Type> input); \
1732 inline bool Equals(Type* that); \
1735 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1737 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1738 #undef SIMD128_VALUE_CLASS
1741 enum EnsureElementsMode {
1742 DONT_ALLOW_DOUBLE_ELEMENTS,
1743 ALLOW_COPIED_DOUBLE_ELEMENTS,
1744 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1748 // Indicator for one component of an AccessorPair.
1749 enum AccessorComponent {
1755 // JSReceiver includes types on which properties can be defined, i.e.,
1756 // JSObject and JSProxy.
1757 class JSReceiver: public HeapObject {
1759 DECLARE_CAST(JSReceiver)
1761 // ES6 section 7.1.1 ToPrimitive
1762 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1763 Handle<JSReceiver> receiver,
1764 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1765 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1766 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1768 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1769 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1770 Handle<JSReceiver> object, Handle<Name> name);
1771 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1773 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1774 Handle<JSReceiver> object, uint32_t index);
1775 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1776 Handle<JSReceiver> object, uint32_t index);
1778 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1779 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1780 Handle<JSReceiver> object, Handle<Name> name,
1781 LanguageMode language_mode = SLOPPY);
1782 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1783 Handle<JSReceiver> object, Handle<Name> name,
1784 LanguageMode language_mode = SLOPPY);
1785 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1786 LookupIterator* it, LanguageMode language_mode);
1787 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1788 Handle<JSReceiver> object, uint32_t index,
1789 LanguageMode language_mode = SLOPPY);
1791 // Tests for the fast common case for property enumeration.
1792 bool IsSimpleEnum();
1794 // Returns the class name ([[Class]] property in the specification).
1795 String* class_name();
1797 // Returns the constructor name (the name (possibly, inferred name) of the
1798 // function that was used to instantiate the object).
1799 String* constructor_name();
1801 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1802 Handle<JSReceiver> object, Handle<Name> name);
1803 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1804 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1806 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1807 Handle<JSReceiver> object, uint32_t index);
1808 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1809 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1811 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1812 LookupIterator* it);
1815 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1817 static Handle<Object> GetDataProperty(LookupIterator* it);
1820 // Retrieves a permanent object identity hash code. The undefined value might
1821 // be returned in case no hash was created yet.
1822 inline Object* GetIdentityHash();
1824 // Retrieves a permanent object identity hash code. May create and store a
1825 // hash code if needed and none exists.
1826 inline static Handle<Smi> GetOrCreateIdentityHash(
1827 Handle<JSReceiver> object);
1829 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1831 // Computes the enumerable keys for a JSObject. Used for implementing
1832 // "for (n in object) { }".
1833 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1834 Handle<JSReceiver> object,
1835 KeyCollectionType type);
1838 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1842 // The JSObject describes real heap allocated JavaScript objects with
1844 // Note that the map of JSObject changes during execution to enable inline
1846 class JSObject: public JSReceiver {
1848 // [properties]: Backing storage for properties.
1849 // properties is a FixedArray in the fast case and a Dictionary in the
1851 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1852 inline void initialize_properties();
1853 inline bool HasFastProperties();
1854 // Gets slow properties for non-global objects.
1855 inline NameDictionary* property_dictionary();
1856 // Gets global object properties.
1857 inline GlobalDictionary* global_dictionary();
1859 // [elements]: The elements (properties with names that are integers).
1861 // Elements can be in two general modes: fast and slow. Each mode
1862 // corrensponds to a set of object representations of elements that
1863 // have something in common.
1865 // In the fast mode elements is a FixedArray and so each element can
1866 // be quickly accessed. This fact is used in the generated code. The
1867 // elements array can have one of three maps in this mode:
1868 // fixed_array_map, sloppy_arguments_elements_map or
1869 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1870 // the elements array may be shared by a few objects and so before
1871 // writing to any element the array must be copied. Use
1872 // EnsureWritableFastElements in this case.
1874 // In the slow mode the elements is either a NumberDictionary, a
1875 // FixedArray parameter map for a (sloppy) arguments object.
1876 DECL_ACCESSORS(elements, FixedArrayBase)
1877 inline void initialize_elements();
1878 static void ResetElements(Handle<JSObject> object);
1879 static inline void SetMapAndElements(Handle<JSObject> object,
1881 Handle<FixedArrayBase> elements);
1882 inline ElementsKind GetElementsKind();
1883 ElementsAccessor* GetElementsAccessor();
1884 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1885 inline bool HasFastSmiElements();
1886 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1887 inline bool HasFastObjectElements();
1888 // Returns true if an object has elements of FAST_ELEMENTS or
1889 // FAST_SMI_ONLY_ELEMENTS.
1890 inline bool HasFastSmiOrObjectElements();
1891 // Returns true if an object has any of the fast elements kinds.
1892 inline bool HasFastElements();
1893 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1895 inline bool HasFastDoubleElements();
1896 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1898 inline bool HasFastHoleyElements();
1899 inline bool HasSloppyArgumentsElements();
1900 inline bool HasDictionaryElements();
1902 inline bool HasFixedTypedArrayElements();
1904 inline bool HasFixedUint8ClampedElements();
1905 inline bool HasFixedArrayElements();
1906 inline bool HasFixedInt8Elements();
1907 inline bool HasFixedUint8Elements();
1908 inline bool HasFixedInt16Elements();
1909 inline bool HasFixedUint16Elements();
1910 inline bool HasFixedInt32Elements();
1911 inline bool HasFixedUint32Elements();
1912 inline bool HasFixedFloat32Elements();
1913 inline bool HasFixedFloat64Elements();
1915 inline bool HasFastArgumentsElements();
1916 inline bool HasSlowArgumentsElements();
1917 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1919 // Requires: HasFastElements().
1920 static Handle<FixedArray> EnsureWritableFastElements(
1921 Handle<JSObject> object);
1923 // Collects elements starting at index 0.
1924 // Undefined values are placed after non-undefined values.
1925 // Returns the number of non-undefined values.
1926 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1928 // As PrepareElementsForSort, but only on objects where elements is
1929 // a dictionary, and it will stay a dictionary. Collates undefined and
1930 // unexisting elements below limit from position zero of the elements.
1931 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1934 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1935 LookupIterator* it, Handle<Object> value);
1937 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1938 // grant an exemption to ExecutableAccessor callbacks in some cases.
1939 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1941 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1942 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1943 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1945 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1946 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1947 PropertyAttributes attributes,
1948 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1950 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1951 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1952 PropertyAttributes attributes,
1953 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1955 // Equivalent to one of the above depending on whether |name| can be converted
1956 // to an array index.
1957 MUST_USE_RESULT static MaybeHandle<Object>
1958 DefinePropertyOrElementIgnoreAttributes(
1959 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1960 PropertyAttributes attributes = NONE,
1961 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1963 // Adds or reconfigures a property to attributes NONE. It will fail when it
1965 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1966 Handle<Object> value);
1968 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1969 Handle<Object> value, PropertyAttributes attributes);
1971 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1972 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1973 PropertyAttributes attributes);
1975 // Extend the receiver with a single fast property appeared first in the
1976 // passed map. This also extends the property backing store if necessary.
1977 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1979 // Migrates the given object to a map whose field representations are the
1980 // lowest upper bound of all known representations for that field.
1981 static void MigrateInstance(Handle<JSObject> instance);
1983 // Migrates the given object only if the target map is already available,
1984 // or returns false if such a map is not yet available.
1985 static bool TryMigrateInstance(Handle<JSObject> instance);
1987 // Sets the property value in a normalized object given (key, value, details).
1988 // Handles the special representation of JS global objects.
1989 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1990 Handle<Object> value,
1991 PropertyDetails details);
1992 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1993 Handle<Object> value,
1994 PropertyAttributes attributes);
1995 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1997 Handle<Object> value,
1998 PropertyAttributes attributes);
2000 static void OptimizeAsPrototype(Handle<JSObject> object,
2001 PrototypeOptimizationMode mode);
2002 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2003 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2004 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2005 static void InvalidatePrototypeChains(Map* map);
2007 // Alternative implementation of WeakFixedArray::NullCallback.
2008 class PrototypeRegistryCompactionCallback {
2010 static void Callback(Object* value, int old_index, int new_index);
2013 // Retrieve interceptors.
2014 InterceptorInfo* GetNamedInterceptor();
2015 InterceptorInfo* GetIndexedInterceptor();
2017 // Used from JSReceiver.
2018 MUST_USE_RESULT static Maybe<PropertyAttributes>
2019 GetPropertyAttributesWithInterceptor(LookupIterator* it);
2020 MUST_USE_RESULT static Maybe<PropertyAttributes>
2021 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2023 // Retrieves an AccessorPair property from the given object. Might return
2024 // undefined if the property doesn't exist or is of a different kind.
2025 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2026 Handle<JSObject> object,
2028 AccessorComponent component);
2030 // Defines an AccessorPair property on the given object.
2031 // TODO(mstarzinger): Rename to SetAccessor().
2032 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2034 Handle<Object> getter,
2035 Handle<Object> setter,
2036 PropertyAttributes attributes);
2038 // Defines an AccessorInfo property on the given object.
2039 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2040 Handle<JSObject> object,
2041 Handle<AccessorInfo> info);
2043 // The result must be checked first for exceptions. If there's no exception,
2044 // the output parameter |done| indicates whether the interceptor has a result
2046 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2047 LookupIterator* it, bool* done);
2049 // Accessors for hidden properties object.
2051 // Hidden properties are not own properties of the object itself.
2052 // Instead they are stored in an auxiliary structure kept as an own
2053 // property with a special name Heap::hidden_string(). But if the
2054 // receiver is a JSGlobalProxy then the auxiliary object is a property
2055 // of its prototype, and if it's a detached proxy, then you can't have
2056 // hidden properties.
2058 // Sets a hidden property on this object. Returns this object if successful,
2059 // undefined if called on a detached proxy.
2060 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2062 Handle<Object> value);
2063 // Gets the value of a hidden property with the given key. Returns the hole
2064 // if the property doesn't exist (or if called on a detached proxy),
2065 // otherwise returns the value set for the key.
2066 Object* GetHiddenProperty(Handle<Name> key);
2067 // Deletes a hidden property. Deleting a non-existing property is
2068 // considered successful.
2069 static void DeleteHiddenProperty(Handle<JSObject> object,
2071 // Returns true if the object has a property with the hidden string as name.
2072 static bool HasHiddenProperties(Handle<JSObject> object);
2074 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2076 static void ValidateElements(Handle<JSObject> object);
2078 // Makes sure that this object can contain HeapObject as elements.
2079 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2081 // Makes sure that this object can contain the specified elements.
2082 static inline void EnsureCanContainElements(
2083 Handle<JSObject> object,
2086 EnsureElementsMode mode);
2087 static inline void EnsureCanContainElements(
2088 Handle<JSObject> object,
2089 Handle<FixedArrayBase> elements,
2091 EnsureElementsMode mode);
2092 static void EnsureCanContainElements(
2093 Handle<JSObject> object,
2094 Arguments* arguments,
2097 EnsureElementsMode mode);
2099 // Would we convert a fast elements array to dictionary mode given
2100 // an access at key?
2101 bool WouldConvertToSlowElements(uint32_t index);
2103 // Computes the new capacity when expanding the elements of a JSObject.
2104 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2105 // (old_capacity + 50%) + 16
2106 return old_capacity + (old_capacity >> 1) + 16;
2109 // These methods do not perform access checks!
2110 static void UpdateAllocationSite(Handle<JSObject> object,
2111 ElementsKind to_kind);
2113 // Lookup interceptors are used for handling properties controlled by host
2115 inline bool HasNamedInterceptor();
2116 inline bool HasIndexedInterceptor();
2118 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2119 // by JSReceiver::GetKeys.
2120 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2121 Handle<JSObject> object,
2122 Handle<JSReceiver> receiver);
2123 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2124 Handle<JSObject> object,
2125 Handle<JSReceiver> receiver);
2127 // Support functions for v8 api (needed for correct interceptor behavior).
2128 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2129 Handle<JSObject> object, Handle<Name> name);
2130 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2131 Handle<JSObject> object, uint32_t index);
2132 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2133 Handle<JSObject> object, Handle<Name> name);
2135 // Get the header size for a JSObject. Used to compute the index of
2136 // internal fields as well as the number of internal fields.
2137 inline int GetHeaderSize();
2139 inline int GetInternalFieldCount();
2140 inline int GetInternalFieldOffset(int index);
2141 inline Object* GetInternalField(int index);
2142 inline void SetInternalField(int index, Object* value);
2143 inline void SetInternalField(int index, Smi* value);
2145 // Returns the number of properties on this object filtering out properties
2146 // with the specified attributes (ignoring interceptors).
2147 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2148 // Fill in details for properties into storage starting at the specified
2149 // index. Returns the number of properties added.
2150 int GetOwnPropertyNames(FixedArray* storage, int index,
2151 PropertyAttributes filter = NONE);
2153 // Returns the number of properties on this object filtering out properties
2154 // with the specified attributes (ignoring interceptors).
2155 int NumberOfOwnElements(PropertyAttributes filter);
2156 // Returns the number of enumerable elements (ignoring interceptors).
2157 int NumberOfEnumElements();
2158 // Returns the number of elements on this object filtering out elements
2159 // with the specified attributes (ignoring interceptors).
2160 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2161 // Count and fill in the enumerable elements into storage.
2162 // (storage->length() == NumberOfEnumElements()).
2163 // If storage is NULL, will count the elements without adding
2164 // them to any storage.
2165 // Returns the number of enumerable elements.
2166 int GetEnumElementKeys(FixedArray* storage);
2168 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2171 // Returns a new map with all transitions dropped from the object's current
2172 // map and the ElementsKind set.
2173 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2174 ElementsKind to_kind);
2175 static void TransitionElementsKind(Handle<JSObject> object,
2176 ElementsKind to_kind);
2178 // Always use this to migrate an object to a new map.
2179 // |expected_additional_properties| is only used for fast-to-slow transitions
2180 // and ignored otherwise.
2181 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2182 int expected_additional_properties = 0);
2184 // Convert the object to use the canonical dictionary
2185 // representation. If the object is expected to have additional properties
2186 // added this number can be indicated to have the backing store allocated to
2187 // an initial capacity for holding these properties.
2188 static void NormalizeProperties(Handle<JSObject> object,
2189 PropertyNormalizationMode mode,
2190 int expected_additional_properties,
2191 const char* reason);
2193 // Convert and update the elements backing store to be a
2194 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2195 static Handle<SeededNumberDictionary> NormalizeElements(
2196 Handle<JSObject> object);
2198 void RequireSlowElements(SeededNumberDictionary* dictionary);
2200 // Transform slow named properties to fast variants.
2201 static void MigrateSlowToFast(Handle<JSObject> object,
2202 int unused_property_fields, const char* reason);
2204 inline bool IsUnboxedDoubleField(FieldIndex index);
2206 // Access fast-case object properties at index.
2207 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2208 Representation representation,
2210 inline Object* RawFastPropertyAt(FieldIndex index);
2211 inline double RawFastDoublePropertyAt(FieldIndex index);
2213 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2214 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2215 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2216 inline void WriteToField(int descriptor, Object* value);
2218 // Access to in object properties.
2219 inline int GetInObjectPropertyOffset(int index);
2220 inline Object* InObjectPropertyAt(int index);
2221 inline Object* InObjectPropertyAtPut(int index,
2223 WriteBarrierMode mode
2224 = UPDATE_WRITE_BARRIER);
2226 // Set the object's prototype (only JSReceiver and null are allowed values).
2227 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2228 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2230 // Initializes the body after properties slot, properties slot is
2231 // initialized by set_properties. Fill the pre-allocated fields with
2232 // pre_allocated_value and the rest with filler_value.
2233 // Note: this call does not update write barrier, the caller is responsible
2234 // to ensure that |filler_value| can be collected without WB here.
2235 inline void InitializeBody(Map* map,
2236 Object* pre_allocated_value,
2237 Object* filler_value);
2239 // Check whether this object references another object
2240 bool ReferencesObject(Object* obj);
2242 // Disalow further properties to be added to the oject.
2243 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2244 Handle<JSObject> object);
2246 bool IsExtensible();
2249 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2251 // ES5 Object.freeze
2252 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2254 // Called the first time an object is observed with ES7 Object.observe.
2255 static void SetObserved(Handle<JSObject> object);
2258 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2260 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2261 Handle<JSObject> object,
2262 AllocationSiteUsageContext* site_context,
2263 DeepCopyHints hints = kNoHints);
2264 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2265 Handle<JSObject> object,
2266 AllocationSiteCreationContext* site_context);
2268 DECLARE_CAST(JSObject)
2270 // Dispatched behavior.
2271 void JSObjectShortPrint(StringStream* accumulator);
2272 DECLARE_PRINTER(JSObject)
2273 DECLARE_VERIFIER(JSObject)
2275 void PrintProperties(std::ostream& os); // NOLINT
2276 void PrintElements(std::ostream& os); // NOLINT
2278 #if defined(DEBUG) || defined(OBJECT_PRINT)
2279 void PrintTransitions(std::ostream& os); // NOLINT
2282 static void PrintElementsTransition(
2283 FILE* file, Handle<JSObject> object,
2284 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2285 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2287 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2290 // Structure for collecting spill information about JSObjects.
2291 class SpillInformation {
2295 int number_of_objects_;
2296 int number_of_objects_with_fast_properties_;
2297 int number_of_objects_with_fast_elements_;
2298 int number_of_fast_used_fields_;
2299 int number_of_fast_unused_fields_;
2300 int number_of_slow_used_properties_;
2301 int number_of_slow_unused_properties_;
2302 int number_of_fast_used_elements_;
2303 int number_of_fast_unused_elements_;
2304 int number_of_slow_used_elements_;
2305 int number_of_slow_unused_elements_;
2308 void IncrementSpillStatistics(SpillInformation* info);
2312 // If a GC was caused while constructing this object, the elements pointer
2313 // may point to a one pointer filler map. The object won't be rooted, but
2314 // our heap verification code could stumble across it.
2315 bool ElementsAreSafeToExamine();
2318 Object* SlowReverseLookup(Object* value);
2320 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2321 // Also maximal value of JSArray's length property.
2322 static const uint32_t kMaxElementCount = 0xffffffffu;
2324 // Constants for heuristics controlling conversion of fast elements
2325 // to slow elements.
2327 // Maximal gap that can be introduced by adding an element beyond
2328 // the current elements length.
2329 static const uint32_t kMaxGap = 1024;
2331 // Maximal length of fast elements array that won't be checked for
2332 // being dense enough on expansion.
2333 static const int kMaxUncheckedFastElementsLength = 5000;
2335 // Same as above but for old arrays. This limit is more strict. We
2336 // don't want to be wasteful with long lived objects.
2337 static const int kMaxUncheckedOldFastElementsLength = 500;
2339 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2340 // permissible values (see the DCHECK in heap.cc).
2341 static const int kInitialMaxFastElementArray = 100000;
2343 // This constant applies only to the initial map of "global.Object" and
2344 // not to arbitrary other JSObject maps.
2345 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2347 static const int kMaxInstanceSize = 255 * kPointerSize;
2348 // When extending the backing storage for property values, we increase
2349 // its size by more than the 1 entry necessary, so sequentially adding fields
2350 // to the same object requires fewer allocations and copies.
2351 static const int kFieldsAdded = 3;
2353 // Layout description.
2354 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2355 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2356 static const int kHeaderSize = kElementsOffset + kPointerSize;
2358 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2360 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2362 static inline int SizeOf(Map* map, HeapObject* object);
2365 Context* GetCreationContext();
2367 // Enqueue change record for Object.observe. May cause GC.
2368 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2369 Handle<JSObject> object, const char* type, Handle<Name> name,
2370 Handle<Object> old_value);
2372 // Gets the number of currently used elements.
2373 int GetFastElementsUsage();
2375 // Deletes an existing named property in a normalized object.
2376 static void DeleteNormalizedProperty(Handle<JSObject> object,
2377 Handle<Name> name, int entry);
2379 static bool AllCanRead(LookupIterator* it);
2380 static bool AllCanWrite(LookupIterator* it);
2383 friend class JSReceiver;
2384 friend class Object;
2386 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2387 static void MigrateFastToSlow(Handle<JSObject> object,
2388 Handle<Map> new_map,
2389 int expected_additional_properties);
2391 // Used from Object::GetProperty().
2392 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2393 LookupIterator* it);
2395 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2396 LookupIterator* it, Handle<Object> value);
2398 // Add a property to a slow-case object.
2399 static void AddSlowProperty(Handle<JSObject> object,
2401 Handle<Object> value,
2402 PropertyAttributes attributes);
2404 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2405 LookupIterator* it);
2407 bool ReferencesObjectFromElements(FixedArray* elements,
2411 // Return the hash table backing store or the inline stored identity hash,
2412 // whatever is found.
2413 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2415 // Return the hash table backing store for hidden properties. If there is no
2416 // backing store, allocate one.
2417 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2418 Handle<JSObject> object);
2420 // Set the hidden property backing store to either a hash table or
2421 // the inline-stored identity hash.
2422 static Handle<Object> SetHiddenPropertiesHashTable(
2423 Handle<JSObject> object,
2424 Handle<Object> value);
2426 MUST_USE_RESULT Object* GetIdentityHash();
2428 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2430 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2431 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2433 // Helper for fast versions of preventExtensions, seal, and freeze.
2434 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2435 template <PropertyAttributes attrs>
2436 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2437 Handle<JSObject> object);
2439 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2443 // Common superclass for FixedArrays that allow implementations to share
2444 // common accessors and some code paths.
2445 class FixedArrayBase: public HeapObject {
2447 // [length]: length of the array.
2448 inline int length() const;
2449 inline void set_length(int value);
2451 // Get and set the length using acquire loads and release stores.
2452 inline int synchronized_length() const;
2453 inline void synchronized_set_length(int value);
2455 DECLARE_CAST(FixedArrayBase)
2457 // Layout description.
2458 // Length is smi tagged when it is stored.
2459 static const int kLengthOffset = HeapObject::kHeaderSize;
2460 static const int kHeaderSize = kLengthOffset + kPointerSize;
2464 class FixedDoubleArray;
2465 class IncrementalMarking;
2468 // FixedArray describes fixed-sized arrays with element type Object*.
2469 class FixedArray: public FixedArrayBase {
2471 // Setter and getter for elements.
2472 inline Object* get(int index) const;
2473 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2474 // Setter that uses write barrier.
2475 inline void set(int index, Object* value);
2476 inline bool is_the_hole(int index);
2478 // Setter that doesn't need write barrier.
2479 inline void set(int index, Smi* value);
2480 // Setter with explicit barrier mode.
2481 inline void set(int index, Object* value, WriteBarrierMode mode);
2483 // Setters for frequently used oddballs located in old space.
2484 inline void set_undefined(int index);
2485 inline void set_null(int index);
2486 inline void set_the_hole(int index);
2488 inline Object** GetFirstElementAddress();
2489 inline bool ContainsOnlySmisOrHoles();
2491 // Gives access to raw memory which stores the array's data.
2492 inline Object** data_start();
2494 inline void FillWithHoles(int from, int to);
2496 // Shrink length and insert filler objects.
2497 void Shrink(int length);
2499 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2501 // Copy a sub array from the receiver to dest.
2502 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2504 // Garbage collection support.
2505 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2507 // Code Generation support.
2508 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2510 // Garbage collection support.
2511 inline Object** RawFieldOfElementAt(int index);
2513 DECLARE_CAST(FixedArray)
2515 // Maximal allowed size, in bytes, of a single FixedArray.
2516 // Prevents overflowing size computations, as well as extreme memory
2518 static const int kMaxSize = 128 * MB * kPointerSize;
2519 // Maximally allowed length of a FixedArray.
2520 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2522 // Dispatched behavior.
2523 DECLARE_PRINTER(FixedArray)
2524 DECLARE_VERIFIER(FixedArray)
2526 // Checks if two FixedArrays have identical contents.
2527 bool IsEqualTo(FixedArray* other);
2530 // Swap two elements in a pair of arrays. If this array and the
2531 // numbers array are the same object, the elements are only swapped
2533 void SwapPairs(FixedArray* numbers, int i, int j);
2535 // Sort prefix of this array and the numbers array as pairs wrt. the
2536 // numbers. If the numbers array and the this array are the same
2537 // object, the prefix of this array is sorted.
2538 void SortPairs(FixedArray* numbers, uint32_t len);
2540 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2542 static inline int SizeOf(Map* map, HeapObject* object);
2546 // Set operation on FixedArray without using write barriers. Can
2547 // only be used for storing old space objects or smis.
2548 static inline void NoWriteBarrierSet(FixedArray* array,
2552 // Set operation on FixedArray without incremental write barrier. Can
2553 // only be used if the object is guaranteed to be white (whiteness witness
2555 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2560 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2562 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2566 // FixedDoubleArray describes fixed-sized arrays with element type double.
2567 class FixedDoubleArray: public FixedArrayBase {
2569 // Setter and getter for elements.
2570 inline double get_scalar(int index);
2571 inline uint64_t get_representation(int index);
2572 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2573 inline void set(int index, double value);
2574 inline void set_the_hole(int index);
2576 // Checking for the hole.
2577 inline bool is_the_hole(int index);
2579 // Garbage collection support.
2580 inline static int SizeFor(int length) {
2581 return kHeaderSize + length * kDoubleSize;
2584 // Gives access to raw memory which stores the array's data.
2585 inline double* data_start();
2587 inline void FillWithHoles(int from, int to);
2589 // Code Generation support.
2590 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2592 DECLARE_CAST(FixedDoubleArray)
2594 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2595 // Prevents overflowing size computations, as well as extreme memory
2597 static const int kMaxSize = 512 * MB;
2598 // Maximally allowed length of a FixedArray.
2599 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2601 // Dispatched behavior.
2602 DECLARE_PRINTER(FixedDoubleArray)
2603 DECLARE_VERIFIER(FixedDoubleArray)
2606 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2610 class WeakFixedArray : public FixedArray {
2612 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2613 // This function does not check if the value exists already, callers must
2614 // ensure this themselves if necessary.
2615 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2616 Handle<HeapObject> value,
2617 int* assigned_index = NULL);
2619 // Returns true if an entry was found and removed.
2620 bool Remove(Handle<HeapObject> value);
2622 class NullCallback {
2624 static void Callback(Object* value, int old_index, int new_index) {}
2627 template <class CompactionCallback>
2630 inline Object* Get(int index) const;
2631 inline void Clear(int index);
2632 inline int Length() const;
2634 inline bool IsEmptySlot(int index) const;
2635 static Object* Empty() { return Smi::FromInt(0); }
2639 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2640 void Reset(Object* maybe_array);
2647 WeakFixedArray* list_;
2649 int last_used_index_;
2650 DisallowHeapAllocation no_gc_;
2652 DISALLOW_COPY_AND_ASSIGN(Iterator);
2655 DECLARE_CAST(WeakFixedArray)
2658 static const int kLastUsedIndexIndex = 0;
2659 static const int kFirstIndex = 1;
2661 static Handle<WeakFixedArray> Allocate(
2662 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2664 static void Set(Handle<WeakFixedArray> array, int index,
2665 Handle<HeapObject> value);
2666 inline void clear(int index);
2668 inline int last_used_index() const;
2669 inline void set_last_used_index(int index);
2671 // Disallow inherited setters.
2672 void set(int index, Smi* value);
2673 void set(int index, Object* value);
2674 void set(int index, Object* value, WriteBarrierMode mode);
2675 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2679 // Generic array grows dynamically with O(1) amortized insertion.
2680 class ArrayList : public FixedArray {
2684 // Use this if GC can delete elements from the array.
2685 kReloadLengthAfterAllocation,
2687 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2688 AddMode mode = kNone);
2689 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2690 Handle<Object> obj2, AddMode = kNone);
2691 inline int Length();
2692 inline void SetLength(int length);
2693 inline Object* Get(int index);
2694 inline Object** Slot(int index);
2695 inline void Set(int index, Object* obj);
2696 inline void Clear(int index, Object* undefined);
2697 DECLARE_CAST(ArrayList)
2700 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2701 static const int kLengthIndex = 0;
2702 static const int kFirstIndex = 1;
2703 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2707 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2708 // The format of the these objects is:
2709 // [0]: Number of descriptors
2710 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2711 // [0]: pointer to fixed array with enum cache
2712 // [1]: either Smi(0) or pointer to fixed array with indices
2714 // [2 + number of descriptors * kDescriptorSize]: start of slack
2715 class DescriptorArray: public FixedArray {
2717 // Returns true for both shared empty_descriptor_array and for smis, which the
2718 // map uses to encode additional bit fields when the descriptor array is not
2720 inline bool IsEmpty();
2722 // Returns the number of descriptors in the array.
2723 inline int number_of_descriptors();
2725 inline int number_of_descriptors_storage();
2727 inline int NumberOfSlackDescriptors();
2729 inline void SetNumberOfDescriptors(int number_of_descriptors);
2730 inline int number_of_entries();
2732 inline bool HasEnumCache();
2734 inline void CopyEnumCacheFrom(DescriptorArray* array);
2736 inline FixedArray* GetEnumCache();
2738 inline bool HasEnumIndicesCache();
2740 inline FixedArray* GetEnumIndicesCache();
2742 inline Object** GetEnumCacheSlot();
2744 void ClearEnumCache();
2746 // Initialize or change the enum cache,
2747 // using the supplied storage for the small "bridge".
2748 void SetEnumCache(FixedArray* bridge_storage,
2749 FixedArray* new_cache,
2750 Object* new_index_cache);
2752 bool CanHoldValue(int descriptor, Object* value);
2754 // Accessors for fetching instance descriptor at descriptor number.
2755 inline Name* GetKey(int descriptor_number);
2756 inline Object** GetKeySlot(int descriptor_number);
2757 inline Object* GetValue(int descriptor_number);
2758 inline void SetValue(int descriptor_number, Object* value);
2759 inline Object** GetValueSlot(int descriptor_number);
2760 static inline int GetValueOffset(int descriptor_number);
2761 inline Object** GetDescriptorStartSlot(int descriptor_number);
2762 inline Object** GetDescriptorEndSlot(int descriptor_number);
2763 inline PropertyDetails GetDetails(int descriptor_number);
2764 inline PropertyType GetType(int descriptor_number);
2765 inline int GetFieldIndex(int descriptor_number);
2766 inline HeapType* GetFieldType(int descriptor_number);
2767 inline Object* GetConstant(int descriptor_number);
2768 inline Object* GetCallbacksObject(int descriptor_number);
2769 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2771 inline Name* GetSortedKey(int descriptor_number);
2772 inline int GetSortedKeyIndex(int descriptor_number);
2773 inline void SetSortedKey(int pointer, int descriptor_number);
2774 inline void SetRepresentation(int descriptor_number,
2775 Representation representation);
2777 // Accessor for complete descriptor.
2778 inline void Get(int descriptor_number, Descriptor* desc);
2779 inline void Set(int descriptor_number, Descriptor* desc);
2780 void Replace(int descriptor_number, Descriptor* descriptor);
2782 // Append automatically sets the enumeration index. This should only be used
2783 // to add descriptors in bulk at the end, followed by sorting the descriptor
2785 inline void Append(Descriptor* desc);
2787 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2788 int enumeration_index,
2791 static Handle<DescriptorArray> CopyUpToAddAttributes(
2792 Handle<DescriptorArray> desc,
2793 int enumeration_index,
2794 PropertyAttributes attributes,
2797 // Sort the instance descriptors by the hash codes of their keys.
2800 // Search the instance descriptors for given name.
2801 INLINE(int Search(Name* name, int number_of_own_descriptors));
2803 // As the above, but uses DescriptorLookupCache and updates it when
2805 INLINE(int SearchWithCache(Name* name, Map* map));
2807 // Allocates a DescriptorArray, but returns the singleton
2808 // empty descriptor array object if number_of_descriptors is 0.
2809 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2810 int number_of_descriptors,
2813 DECLARE_CAST(DescriptorArray)
2815 // Constant for denoting key was not found.
2816 static const int kNotFound = -1;
2818 static const int kDescriptorLengthIndex = 0;
2819 static const int kEnumCacheIndex = 1;
2820 static const int kFirstIndex = 2;
2822 // The length of the "bridge" to the enum cache.
2823 static const int kEnumCacheBridgeLength = 2;
2824 static const int kEnumCacheBridgeCacheIndex = 0;
2825 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2827 // Layout description.
2828 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2829 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2830 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2832 // Layout description for the bridge array.
2833 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2835 // Layout of descriptor.
2836 static const int kDescriptorKey = 0;
2837 static const int kDescriptorDetails = 1;
2838 static const int kDescriptorValue = 2;
2839 static const int kDescriptorSize = 3;
2841 #if defined(DEBUG) || defined(OBJECT_PRINT)
2842 // For our gdb macros, we should perhaps change these in the future.
2845 // Print all the descriptors.
2846 void PrintDescriptors(std::ostream& os); // NOLINT
2850 // Is the descriptor array sorted and without duplicates?
2851 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2853 // Is the descriptor array consistent with the back pointers in targets?
2854 bool IsConsistentWithBackPointers(Map* current_map);
2856 // Are two DescriptorArrays equal?
2857 bool IsEqualTo(DescriptorArray* other);
2860 // Returns the fixed array length required to hold number_of_descriptors
2862 static int LengthFor(int number_of_descriptors) {
2863 return ToKeyIndex(number_of_descriptors);
2867 // WhitenessWitness is used to prove that a descriptor array is white
2868 // (unmarked), so incremental write barriers can be skipped because the
2869 // marking invariant cannot be broken and slots pointing into evacuation
2870 // candidates will be discovered when the object is scanned. A witness is
2871 // always stack-allocated right after creating an array. By allocating a
2872 // witness, incremental marking is globally disabled. The witness is then
2873 // passed along wherever needed to statically prove that the array is known to
2875 class WhitenessWitness {
2877 inline explicit WhitenessWitness(DescriptorArray* array);
2878 inline ~WhitenessWitness();
2881 IncrementalMarking* marking_;
2884 // An entry in a DescriptorArray, represented as an (array, index) pair.
2887 inline explicit Entry(DescriptorArray* descs, int index) :
2888 descs_(descs), index_(index) { }
2890 inline PropertyType type();
2891 inline Object* GetCallbackObject();
2894 DescriptorArray* descs_;
2898 // Conversion from descriptor number to array indices.
2899 static int ToKeyIndex(int descriptor_number) {
2900 return kFirstIndex +
2901 (descriptor_number * kDescriptorSize) +
2905 static int ToDetailsIndex(int descriptor_number) {
2906 return kFirstIndex +
2907 (descriptor_number * kDescriptorSize) +
2911 static int ToValueIndex(int descriptor_number) {
2912 return kFirstIndex +
2913 (descriptor_number * kDescriptorSize) +
2917 // Transfer a complete descriptor from the src descriptor array to this
2918 // descriptor array.
2919 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2921 inline void Set(int descriptor_number,
2923 const WhitenessWitness&);
2925 // Swap first and second descriptor.
2926 inline void SwapSortedKeys(int first, int second);
2928 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2932 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2934 template <SearchMode search_mode, typename T>
2935 inline int Search(T* array, Name* name, int valid_entries = 0,
2936 int* out_insertion_index = NULL);
2939 // HashTable is a subclass of FixedArray that implements a hash table
2940 // that uses open addressing and quadratic probing.
2942 // In order for the quadratic probing to work, elements that have not
2943 // yet been used and elements that have been deleted are
2944 // distinguished. Probing continues when deleted elements are
2945 // encountered and stops when unused elements are encountered.
2947 // - Elements with key == undefined have not been used yet.
2948 // - Elements with key == the_hole have been deleted.
2950 // The hash table class is parameterized with a Shape and a Key.
2951 // Shape must be a class with the following interface:
2952 // class ExampleShape {
2954 // // Tells whether key matches other.
2955 // static bool IsMatch(Key key, Object* other);
2956 // // Returns the hash value for key.
2957 // static uint32_t Hash(Key key);
2958 // // Returns the hash value for object.
2959 // static uint32_t HashForObject(Key key, Object* object);
2960 // // Convert key to an object.
2961 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2962 // // The prefix size indicates number of elements in the beginning
2963 // // of the backing storage.
2964 // static const int kPrefixSize = ..;
2965 // // The Element size indicates number of elements per entry.
2966 // static const int kEntrySize = ..;
2968 // The prefix size indicates an amount of memory in the
2969 // beginning of the backing storage that can be used for non-element
2970 // information by subclasses.
2972 template<typename Key>
2975 static const bool UsesSeed = false;
2976 static uint32_t Hash(Key key) { return 0; }
2977 static uint32_t SeededHash(Key key, uint32_t seed) {
2981 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2982 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2984 return HashForObject(key, object);
2989 class HashTableBase : public FixedArray {
2991 // Returns the number of elements in the hash table.
2992 inline int NumberOfElements();
2994 // Returns the number of deleted elements in the hash table.
2995 inline int NumberOfDeletedElements();
2997 // Returns the capacity of the hash table.
2998 inline int Capacity();
3000 // ElementAdded should be called whenever an element is added to a
3002 inline void ElementAdded();
3004 // ElementRemoved should be called whenever an element is removed from
3006 inline void ElementRemoved();
3007 inline void ElementsRemoved(int n);
3009 // Computes the required capacity for a table holding the given
3010 // number of elements. May be more than HashTable::kMaxCapacity.
3011 static inline int ComputeCapacity(int at_least_space_for);
3013 // Tells whether k is a real key. The hole and undefined are not allowed
3014 // as keys and can be used to indicate missing or deleted elements.
3015 inline bool IsKey(Object* k);
3017 // Compute the probe offset (quadratic probing).
3018 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3019 return (n + n * n) >> 1;
3022 static const int kNumberOfElementsIndex = 0;
3023 static const int kNumberOfDeletedElementsIndex = 1;
3024 static const int kCapacityIndex = 2;
3025 static const int kPrefixStartIndex = 3;
3027 // Constant used for denoting a absent entry.
3028 static const int kNotFound = -1;
3031 // Update the number of elements in the hash table.
3032 inline void SetNumberOfElements(int nof);
3034 // Update the number of deleted elements in the hash table.
3035 inline void SetNumberOfDeletedElements(int nod);
3037 // Returns probe entry.
3038 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3039 DCHECK(base::bits::IsPowerOfTwo32(size));
3040 return (hash + GetProbeOffset(number)) & (size - 1);
3043 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3044 return hash & (size - 1);
3047 inline static uint32_t NextProbe(
3048 uint32_t last, uint32_t number, uint32_t size) {
3049 return (last + number) & (size - 1);
3054 template <typename Derived, typename Shape, typename Key>
3055 class HashTable : public HashTableBase {
3058 inline uint32_t Hash(Key key) {
3059 if (Shape::UsesSeed) {
3060 return Shape::SeededHash(key, GetHeap()->HashSeed());
3062 return Shape::Hash(key);
3066 inline uint32_t HashForObject(Key key, Object* object) {
3067 if (Shape::UsesSeed) {
3068 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3070 return Shape::HashForObject(key, object);
3074 // Returns a new HashTable object.
3075 MUST_USE_RESULT static Handle<Derived> New(
3076 Isolate* isolate, int at_least_space_for,
3077 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3078 PretenureFlag pretenure = NOT_TENURED);
3080 DECLARE_CAST(HashTable)
3082 // Garbage collection support.
3083 void IteratePrefix(ObjectVisitor* visitor);
3084 void IterateElements(ObjectVisitor* visitor);
3086 // Find entry for key otherwise return kNotFound.
3087 inline int FindEntry(Key key);
3088 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3089 int FindEntry(Isolate* isolate, Key key);
3091 // Rehashes the table in-place.
3092 void Rehash(Key key);
3094 // Returns the key at entry.
3095 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3097 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3098 static const int kEntrySize = Shape::kEntrySize;
3099 static const int kElementsStartOffset =
3100 kHeaderSize + kElementsStartIndex * kPointerSize;
3101 static const int kCapacityOffset =
3102 kHeaderSize + kCapacityIndex * kPointerSize;
3104 // Returns the index for an entry (of the key)
3105 static inline int EntryToIndex(int entry) {
3106 return (entry * kEntrySize) + kElementsStartIndex;
3110 friend class ObjectHashTable;
3112 // Find the entry at which to insert element with the given key that
3113 // has the given hash value.
3114 uint32_t FindInsertionEntry(uint32_t hash);
3116 // Attempt to shrink hash table after removal of key.
3117 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3119 // Ensure enough space for n additional elements.
3120 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3121 Handle<Derived> table,
3124 PretenureFlag pretenure = NOT_TENURED);
3126 // Sets the capacity of the hash table.
3127 void SetCapacity(int capacity) {
3128 // To scale a computed hash code to fit within the hash table, we
3129 // use bit-wise AND with a mask, so the capacity must be positive
3131 DCHECK(capacity > 0);
3132 DCHECK(capacity <= kMaxCapacity);
3133 set(kCapacityIndex, Smi::FromInt(capacity));
3136 // Maximal capacity of HashTable. Based on maximal length of underlying
3137 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3139 static const int kMaxCapacity =
3140 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3143 // Returns _expected_ if one of entries given by the first _probe_ probes is
3144 // equal to _expected_. Otherwise, returns the entry given by the probe
3146 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3148 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3150 // Rehashes this hash-table into the new table.
3151 void Rehash(Handle<Derived> new_table, Key key);
3155 // HashTableKey is an abstract superclass for virtual key behavior.
3156 class HashTableKey {
3158 // Returns whether the other object matches this key.
3159 virtual bool IsMatch(Object* other) = 0;
3160 // Returns the hash value for this key.
3161 virtual uint32_t Hash() = 0;
3162 // Returns the hash value for object.
3163 virtual uint32_t HashForObject(Object* key) = 0;
3164 // Returns the key object for storing into the hash table.
3165 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3167 virtual ~HashTableKey() {}
3171 class StringTableShape : public BaseShape<HashTableKey*> {
3173 static inline bool IsMatch(HashTableKey* key, Object* value) {
3174 return key->IsMatch(value);
3177 static inline uint32_t Hash(HashTableKey* key) {
3181 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3182 return key->HashForObject(object);
3185 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3187 static const int kPrefixSize = 0;
3188 static const int kEntrySize = 1;
3191 class SeqOneByteString;
3195 // No special elements in the prefix and the element size is 1
3196 // because only the string itself (the key) needs to be stored.
3197 class StringTable: public HashTable<StringTable,
3201 // Find string in the string table. If it is not there yet, it is
3202 // added. The return value is the string found.
3203 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3204 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3205 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3207 // Tries to internalize given string and returns string handle on success
3208 // or an empty handle otherwise.
3209 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3211 Handle<String> string);
3213 // Looks up a string that is equal to the given string and returns
3214 // string handle if it is found, or an empty handle otherwise.
3215 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3217 Handle<String> str);
3218 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3223 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3225 DECLARE_CAST(StringTable)
3228 template <bool seq_one_byte>
3229 friend class JsonParser;
3231 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3235 template <typename Derived, typename Shape, typename Key>
3236 class Dictionary: public HashTable<Derived, Shape, Key> {
3237 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3240 // Returns the value at entry.
3241 Object* ValueAt(int entry) {
3242 return this->get(Derived::EntryToIndex(entry) + 1);
3245 // Set the value for entry.
3246 void ValueAtPut(int entry, Object* value) {
3247 this->set(Derived::EntryToIndex(entry) + 1, value);
3250 // Returns the property details for the property at entry.
3251 PropertyDetails DetailsAt(int entry) {
3252 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3255 // Set the details for entry.
3256 void DetailsAtPut(int entry, PropertyDetails value) {
3257 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3260 // Returns true if property at given entry is deleted.
3261 bool IsDeleted(int entry) {
3262 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3265 // Delete a property from the dictionary.
3266 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3268 // Attempt to shrink the dictionary after deletion of key.
3269 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3270 Handle<Derived> dictionary,
3272 return DerivedHashTable::Shrink(dictionary, key);
3276 // TODO(dcarney): templatize or move to SeededNumberDictionary
3277 void CopyValuesTo(FixedArray* elements);
3279 // Returns the number of elements in the dictionary filtering out properties
3280 // with the specified attributes.
3281 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3283 // Returns the number of enumerable elements in the dictionary.
3284 int NumberOfEnumElements() {
3285 return NumberOfElementsFilterAttributes(
3286 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3289 // Returns true if the dictionary contains any elements that are non-writable,
3290 // non-configurable, non-enumerable, or have getters/setters.
3291 bool HasComplexElements();
3293 enum SortMode { UNSORTED, SORTED };
3295 // Fill in details for properties into storage.
3296 // Returns the number of properties added.
3297 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3298 SortMode sort_mode);
3300 // Copies enumerable keys to preallocated fixed array.
3301 void CopyEnumKeysTo(FixedArray* storage);
3303 // Accessors for next enumeration index.
3304 void SetNextEnumerationIndex(int index) {
3306 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3309 int NextEnumerationIndex() {
3310 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3313 // Creates a new dictionary.
3314 MUST_USE_RESULT static Handle<Derived> New(
3316 int at_least_space_for,
3317 PretenureFlag pretenure = NOT_TENURED);
3319 // Ensure enough space for n additional elements.
3320 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3323 void Print(std::ostream& os); // NOLINT
3325 // Returns the key (slow).
3326 Object* SlowReverseLookup(Object* value);
3328 // Sets the entry to (key, value) pair.
3329 inline void SetEntry(int entry,
3331 Handle<Object> value);
3332 inline void SetEntry(int entry,
3334 Handle<Object> value,
3335 PropertyDetails details);
3337 MUST_USE_RESULT static Handle<Derived> Add(
3338 Handle<Derived> dictionary,
3340 Handle<Object> value,
3341 PropertyDetails details);
3343 // Returns iteration indices array for the |dictionary|.
3344 // Values are direct indices in the |HashTable| array.
3345 static Handle<FixedArray> BuildIterationIndicesArray(
3346 Handle<Derived> dictionary);
3349 // Generic at put operation.
3350 MUST_USE_RESULT static Handle<Derived> AtPut(
3351 Handle<Derived> dictionary,
3353 Handle<Object> value);
3355 // Add entry to dictionary.
3356 static void AddEntry(
3357 Handle<Derived> dictionary,
3359 Handle<Object> value,
3360 PropertyDetails details,
3363 // Generate new enumeration indices to avoid enumeration index overflow.
3364 // Returns iteration indices array for the |dictionary|.
3365 static Handle<FixedArray> GenerateNewEnumerationIndices(
3366 Handle<Derived> dictionary);
3367 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3368 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3372 template <typename Derived, typename Shape>
3373 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3374 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3377 // Find entry for key, otherwise return kNotFound. Optimized version of
3378 // HashTable::FindEntry.
3379 int FindEntry(Handle<Name> key);
3383 template <typename Key>
3384 class BaseDictionaryShape : public BaseShape<Key> {
3386 template <typename Dictionary>
3387 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3388 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3389 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3390 return PropertyDetails(
3391 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3394 template <typename Dictionary>
3395 static inline void DetailsAtPut(Dictionary* dict, int entry,
3396 PropertyDetails value) {
3397 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3398 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3401 template <typename Dictionary>
3402 static bool IsDeleted(Dictionary* dict, int entry) {
3406 template <typename Dictionary>
3407 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3408 Handle<Object> value, PropertyDetails details);
3412 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3414 static inline bool IsMatch(Handle<Name> key, Object* other);
3415 static inline uint32_t Hash(Handle<Name> key);
3416 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3417 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3418 static const int kPrefixSize = 2;
3419 static const int kEntrySize = 3;
3420 static const bool kIsEnumerable = true;
3424 class NameDictionary
3425 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3426 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3430 DECLARE_CAST(NameDictionary)
3432 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3433 Handle<NameDictionary> dictionary);
3437 class GlobalDictionaryShape : public NameDictionaryShape {
3439 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3441 template <typename Dictionary>
3442 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3444 template <typename Dictionary>
3445 static inline void DetailsAtPut(Dictionary* dict, int entry,
3446 PropertyDetails value);
3448 template <typename Dictionary>
3449 static bool IsDeleted(Dictionary* dict, int entry);
3451 template <typename Dictionary>
3452 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3453 Handle<Object> value, PropertyDetails details);
3457 class GlobalDictionary
3458 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3460 DECLARE_CAST(GlobalDictionary)
3464 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3466 static inline bool IsMatch(uint32_t key, Object* other);
3467 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3468 static const int kEntrySize = 3;
3469 static const bool kIsEnumerable = false;
3473 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3475 static const bool UsesSeed = true;
3476 static const int kPrefixSize = 2;
3478 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3479 static inline uint32_t SeededHashForObject(uint32_t key,
3485 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3487 static const int kPrefixSize = 0;
3489 static inline uint32_t Hash(uint32_t key);
3490 static inline uint32_t HashForObject(uint32_t key, Object* object);
3494 class SeededNumberDictionary
3495 : public Dictionary<SeededNumberDictionary,
3496 SeededNumberDictionaryShape,
3499 DECLARE_CAST(SeededNumberDictionary)
3501 // Type specific at put (default NONE attributes is used when adding).
3502 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3503 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3504 Handle<Object> value, bool used_as_prototype);
3505 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3506 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3507 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3509 // Set an existing entry or add a new one if needed.
3510 // Return the updated dictionary.
3511 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3512 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3513 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3515 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3517 // If slow elements are required we will never go back to fast-case
3518 // for the elements kept in this dictionary. We require slow
3519 // elements if an element has been added at an index larger than
3520 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3521 // when defining a getter or setter with a number key.
3522 inline bool requires_slow_elements();
3523 inline void set_requires_slow_elements();
3525 // Get the value of the max number key that has been added to this
3526 // dictionary. max_number_key can only be called if
3527 // requires_slow_elements returns false.
3528 inline uint32_t max_number_key();
3531 static const int kRequiresSlowElementsMask = 1;
3532 static const int kRequiresSlowElementsTagSize = 1;
3533 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3537 class UnseededNumberDictionary
3538 : public Dictionary<UnseededNumberDictionary,
3539 UnseededNumberDictionaryShape,
3542 DECLARE_CAST(UnseededNumberDictionary)
3544 // Type specific at put (default NONE attributes is used when adding).
3545 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3546 Handle<UnseededNumberDictionary> dictionary,
3548 Handle<Object> value);
3549 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3550 Handle<UnseededNumberDictionary> dictionary,
3552 Handle<Object> value);
3554 // Set an existing entry or add a new one if needed.
3555 // Return the updated dictionary.
3556 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3557 Handle<UnseededNumberDictionary> dictionary,
3559 Handle<Object> value);
3563 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3565 static inline bool IsMatch(Handle<Object> key, Object* other);
3566 static inline uint32_t Hash(Handle<Object> key);
3567 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3568 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3569 static const int kPrefixSize = 0;
3570 static const int kEntrySize = 2;
3574 // ObjectHashTable maps keys that are arbitrary objects to object values by
3575 // using the identity hash of the key for hashing purposes.
3576 class ObjectHashTable: public HashTable<ObjectHashTable,
3577 ObjectHashTableShape,
3580 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3582 DECLARE_CAST(ObjectHashTable)
3584 // Attempt to shrink hash table after removal of key.
3585 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3586 Handle<ObjectHashTable> table,
3587 Handle<Object> key);
3589 // Looks up the value associated with the given key. The hole value is
3590 // returned in case the key is not present.
3591 Object* Lookup(Handle<Object> key);
3592 Object* Lookup(Handle<Object> key, int32_t hash);
3593 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3595 // Adds (or overwrites) the value associated with the given key.
3596 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3598 Handle<Object> value);
3599 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3600 Handle<Object> key, Handle<Object> value,
3603 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3604 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3607 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3608 Handle<Object> key, bool* was_present,
3612 friend class MarkCompactCollector;
3614 void AddEntry(int entry, Object* key, Object* value);
3615 void RemoveEntry(int entry);
3617 // Returns the index to the value of an entry.
3618 static inline int EntryToValueIndex(int entry) {
3619 return EntryToIndex(entry) + 1;
3624 // OrderedHashTable is a HashTable with Object keys that preserves
3625 // insertion order. There are Map and Set interfaces (OrderedHashMap
3626 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3628 // Only Object* keys are supported, with Object::SameValueZero() used as the
3629 // equality operator and Object::GetHash() for the hash function.
3631 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3632 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3633 // Originally attributed to Tyler Close.
3636 // [0]: bucket count
3637 // [1]: element count
3638 // [2]: deleted element count
3639 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3640 // offset into the data table (see below) where the
3641 // first item in this bucket is stored.
3642 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3643 // Capacity() * kEntrySize, where the first entrysize
3644 // items are handled by the derived class and the
3645 // item at kChainOffset is another entry into the
3646 // data table indicating the next entry in this hash
3649 // When we transition the table to a new version we obsolete it and reuse parts
3650 // of the memory to store information how to transition an iterator to the new
3653 // Memory layout for obsolete table:
3654 // [0]: bucket count
3655 // [1]: Next newer table
3656 // [2]: Number of removed holes or -1 when the table was cleared.
3657 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3658 // [3 + NumberOfRemovedHoles()..length]: Not used
3660 template<class Derived, class Iterator, int entrysize>
3661 class OrderedHashTable: public FixedArray {
3663 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3664 static Handle<Derived> Allocate(
3665 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3667 // Returns an OrderedHashTable (possibly |table|) with enough space
3668 // to add at least one new element.
3669 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3671 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3673 static Handle<Derived> Shrink(Handle<Derived> table);
3675 // Returns a new empty OrderedHashTable and records the clearing so that
3676 // exisiting iterators can be updated.
3677 static Handle<Derived> Clear(Handle<Derived> table);
3679 // Returns a true if the OrderedHashTable contains the key
3680 static bool HasKey(Handle<Derived> table, Handle<Object> key);
3682 int NumberOfElements() {
3683 return Smi::cast(get(kNumberOfElementsIndex))->value();
3686 int NumberOfDeletedElements() {
3687 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3690 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3692 int NumberOfBuckets() {
3693 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3696 // Returns an index into |this| for the given entry.
3697 int EntryToIndex(int entry) {
3698 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3701 int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }
3703 int HashToEntry(int hash) {
3704 int bucket = HashToBucket(hash);
3705 Object* entry = this->get(kHashTableStartIndex + bucket);
3706 return Smi::cast(entry)->value();
3709 int KeyToFirstEntry(Object* key) {
3710 Object* hash = key->GetHash();
3711 // If the object does not have an identity hash, it was never used as a key
3712 if (hash->IsUndefined()) return kNotFound;
3713 return HashToEntry(Smi::cast(hash)->value());
3716 int NextChainEntry(int entry) {
3717 Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
3718 return Smi::cast(next_entry)->value();
3721 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3724 return !get(kNextTableIndex)->IsSmi();
3727 // The next newer table. This is only valid if the table is obsolete.
3728 Derived* NextTable() {
3729 return Derived::cast(get(kNextTableIndex));
3732 // When the table is obsolete we store the indexes of the removed holes.
3733 int RemovedIndexAt(int index) {
3734 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3737 static const int kNotFound = -1;
3738 static const int kMinCapacity = 4;
3740 static const int kNumberOfBucketsIndex = 0;
3741 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3742 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3743 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3744 static const int kNextTableIndex = kNumberOfElementsIndex;
3746 static const int kNumberOfBucketsOffset =
3747 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3748 static const int kNumberOfElementsOffset =
3749 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3750 static const int kNumberOfDeletedElementsOffset =
3751 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3752 static const int kHashTableStartOffset =
3753 kHeaderSize + kHashTableStartIndex * kPointerSize;
3754 static const int kNextTableOffset =
3755 kHeaderSize + kNextTableIndex * kPointerSize;
3757 static const int kEntrySize = entrysize + 1;
3758 static const int kChainOffset = entrysize;
3760 static const int kLoadFactor = 2;
3762 // NumberOfDeletedElements is set to kClearedTableSentinel when
3763 // the table is cleared, which allows iterator transitions to
3764 // optimize that case.
3765 static const int kClearedTableSentinel = -1;
3768 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3770 void SetNumberOfBuckets(int num) {
3771 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3774 void SetNumberOfElements(int num) {
3775 set(kNumberOfElementsIndex, Smi::FromInt(num));
3778 void SetNumberOfDeletedElements(int num) {
3779 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3783 return NumberOfBuckets() * kLoadFactor;
3786 void SetNextTable(Derived* next_table) {
3787 set(kNextTableIndex, next_table);
3790 void SetRemovedIndexAt(int index, int removed_index) {
3791 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3794 static const int kRemovedHolesIndex = kHashTableStartIndex;
3796 static const int kMaxCapacity =
3797 (FixedArray::kMaxLength - kHashTableStartIndex)
3798 / (1 + (kEntrySize * kLoadFactor));
3802 class JSSetIterator;
3805 class OrderedHashSet: public OrderedHashTable<
3806 OrderedHashSet, JSSetIterator, 1> {
3808 DECLARE_CAST(OrderedHashSet)
3810 static Handle<OrderedHashSet> Add(Handle<OrderedHashSet> table,
3811 Handle<Object> value);
3815 class JSMapIterator;
3818 class OrderedHashMap
3819 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3821 DECLARE_CAST(OrderedHashMap)
3823 inline Object* ValueAt(int entry);
3825 static const int kValueOffset = 1;
3829 template <int entrysize>
3830 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3832 static inline bool IsMatch(Handle<Object> key, Object* other);
3833 static inline uint32_t Hash(Handle<Object> key);
3834 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3835 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3836 static const int kPrefixSize = 0;
3837 static const int kEntrySize = entrysize;
3841 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3842 // values. The table wraps the keys in weak cells and store values directly.
3843 // Thus it references keys weakly and values strongly.
3844 class WeakHashTable: public HashTable<WeakHashTable,
3845 WeakHashTableShape<2>,
3848 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3850 DECLARE_CAST(WeakHashTable)
3852 // Looks up the value associated with the given key. The hole value is
3853 // returned in case the key is not present.
3854 Object* Lookup(Handle<HeapObject> key);
3856 // Adds (or overwrites) the value associated with the given key. Mapping a
3857 // key to the hole value causes removal of the whole entry.
3858 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3859 Handle<HeapObject> key,
3860 Handle<HeapObject> value);
3862 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3865 friend class MarkCompactCollector;
3867 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3869 // Returns the index to the value of an entry.
3870 static inline int EntryToValueIndex(int entry) {
3871 return EntryToIndex(entry) + 1;
3876 // ScopeInfo represents information about different scopes of a source
3877 // program and the allocation of the scope's variables. Scope information
3878 // is stored in a compressed form in ScopeInfo objects and is used
3879 // at runtime (stack dumps, deoptimization, etc.).
3881 // This object provides quick access to scope info details for runtime
3883 class ScopeInfo : public FixedArray {
3885 DECLARE_CAST(ScopeInfo)
3887 // Return the type of this scope.
3888 ScopeType scope_type();
3890 // Does this scope call eval?
3893 // Return the language mode of this scope.
3894 LanguageMode language_mode();
3896 // True if this scope is a (var) declaration scope.
3897 bool is_declaration_scope();
3899 // Does this scope make a sloppy eval call?
3900 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3902 // Return the total number of locals allocated on the stack and in the
3903 // context. This includes the parameters that are allocated in the context.
3906 // Return the number of stack slots for code. This number consists of two
3908 // 1. One stack slot per stack allocated local.
3909 // 2. One stack slot for the function name if it is stack allocated.
3910 int StackSlotCount();
3912 // Return the number of context slots for code if a context is allocated. This
3913 // number consists of three parts:
3914 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3915 // 2. One context slot per context allocated local.
3916 // 3. One context slot for the function name if it is context allocated.
3917 // Parameters allocated in the context count as context allocated locals. If
3918 // no contexts are allocated for this scope ContextLength returns 0.
3919 int ContextLength();
3921 // Does this scope declare a "this" binding?
3924 // Does this scope declare a "this" binding, and the "this" binding is stack-
3925 // or context-allocated?
3926 bool HasAllocatedReceiver();
3928 // Is this scope the scope of a named function expression?
3929 bool HasFunctionName();
3931 // Return if this has context allocated locals.
3932 bool HasHeapAllocatedLocals();
3934 // Return if contexts are allocated for this scope.
3937 // Return if this is a function scope with "use asm".
3938 inline bool IsAsmModule();
3940 // Return if this is a nested function within an asm module scope.
3941 inline bool IsAsmFunction();
3943 inline bool HasSimpleParameters();
3945 // Return the function_name if present.
3946 String* FunctionName();
3948 // Return the name of the given parameter.
3949 String* ParameterName(int var);
3951 // Return the name of the given local.
3952 String* LocalName(int var);
3954 // Return the name of the given stack local.
3955 String* StackLocalName(int var);
3957 // Return the name of the given stack local.
3958 int StackLocalIndex(int var);
3960 // Return the name of the given context local.
3961 String* ContextLocalName(int var);
3963 // Return the mode of the given context local.
3964 VariableMode ContextLocalMode(int var);
3966 // Return the initialization flag of the given context local.
3967 InitializationFlag ContextLocalInitFlag(int var);
3969 // Return the initialization flag of the given context local.
3970 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3972 // Return true if this local was introduced by the compiler, and should not be
3973 // exposed to the user in a debugger.
3974 bool LocalIsSynthetic(int var);
3976 String* StrongModeFreeVariableName(int var);
3977 int StrongModeFreeVariableStartPosition(int var);
3978 int StrongModeFreeVariableEndPosition(int var);
3980 // Lookup support for serialized scope info. Returns the
3981 // the stack slot index for a given slot name if the slot is
3982 // present; otherwise returns a value < 0. The name must be an internalized
3984 int StackSlotIndex(String* name);
3986 // Lookup support for serialized scope info. Returns the local context slot
3987 // index for a given slot name if the slot is present; otherwise
3988 // returns a value < 0. The name must be an internalized string.
3989 // If the slot is present and mode != NULL, sets *mode to the corresponding
3990 // mode for that variable.
3991 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3992 VariableMode* mode, InitializationFlag* init_flag,
3993 MaybeAssignedFlag* maybe_assigned_flag);
3995 // Similar to ContextSlotIndex() but this method searches only among
3996 // global slots of the serialized scope info. Returns the context slot index
3997 // for a given slot name if the slot is present; otherwise returns a
3998 // value < 0. The name must be an internalized string. If the slot is present
3999 // and mode != NULL, sets *mode to the corresponding mode for that variable.
4000 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
4001 Handle<String> name, VariableMode* mode,
4002 InitializationFlag* init_flag,
4003 MaybeAssignedFlag* maybe_assigned_flag);
4005 // Lookup the name of a certain context slot by its index.
4006 String* ContextSlotName(int slot_index);
4008 // Lookup support for serialized scope info. Returns the
4009 // parameter index for a given parameter name if the parameter is present;
4010 // otherwise returns a value < 0. The name must be an internalized string.
4011 int ParameterIndex(String* name);
4013 // Lookup support for serialized scope info. Returns the function context
4014 // slot index if the function name is present and context-allocated (named
4015 // function expressions, only), otherwise returns a value < 0. The name
4016 // must be an internalized string.
4017 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4019 // Lookup support for serialized scope info. Returns the receiver context
4020 // slot index if scope has a "this" binding, and the binding is
4021 // context-allocated. Otherwise returns a value < 0.
4022 int ReceiverContextSlotIndex();
4024 FunctionKind function_kind();
4026 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4027 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4029 // Serializes empty scope info.
4030 static ScopeInfo* Empty(Isolate* isolate);
4036 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4037 // numeric and occupies one array slot.
4038 // 1. A set of properties of the scope
4039 // 2. The number of parameters. This only applies to function scopes. For
4040 // non-function scopes this is 0.
4041 // 3. The number of non-parameter variables allocated on the stack.
4042 // 4. The number of non-parameter and parameter variables allocated in the
4044 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4047 V(StackLocalCount) \
4048 V(ContextLocalCount) \
4049 V(ContextGlobalCount) \
4050 V(StrongModeFreeVariableCount)
4052 #define FIELD_ACCESSORS(name) \
4053 inline void Set##name(int value); \
4055 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4056 #undef FIELD_ACCESSORS
4059 #define DECL_INDEX(name) k##name,
4060 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4066 // The layout of the variable part of a ScopeInfo is as follows:
4067 // 1. ParameterEntries:
4068 // This part stores the names of the parameters for function scopes. One
4069 // slot is used per parameter, so in total this part occupies
4070 // ParameterCount() slots in the array. For other scopes than function
4071 // scopes ParameterCount() is 0.
4072 // 2. StackLocalFirstSlot:
4073 // Index of a first stack slot for stack local. Stack locals belonging to
4074 // this scope are located on a stack at slots starting from this index.
4075 // 3. StackLocalEntries:
4076 // Contains the names of local variables that are allocated on the stack,
4077 // in increasing order of the stack slot index. First local variable has
4078 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4079 // One slot is used per stack local, so in total this part occupies
4080 // StackLocalCount() slots in the array.
4081 // 4. ContextLocalNameEntries:
4082 // Contains the names of local variables and parameters that are allocated
4083 // in the context. They are stored in increasing order of the context slot
4084 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4085 // context local, so in total this part occupies ContextLocalCount() slots
4087 // 5. ContextLocalInfoEntries:
4088 // Contains the variable modes and initialization flags corresponding to
4089 // the context locals in ContextLocalNameEntries. One slot is used per
4090 // context local, so in total this part occupies ContextLocalCount()
4091 // slots in the array.
4092 // 6. StrongModeFreeVariableNameEntries:
4093 // Stores the names of strong mode free variables.
4094 // 7. StrongModeFreeVariablePositionEntries:
4095 // Stores the locations (start and end position) of strong mode free
4097 // 8. RecieverEntryIndex:
4098 // If the scope binds a "this" value, one slot is reserved to hold the
4099 // context or stack slot index for the variable.
4100 // 9. FunctionNameEntryIndex:
4101 // If the scope belongs to a named function expression this part contains
4102 // information about the function variable. It always occupies two array
4103 // slots: a. The name of the function variable.
4104 // b. The context or stack slot index for the variable.
4105 int ParameterEntriesIndex();
4106 int StackLocalFirstSlotIndex();
4107 int StackLocalEntriesIndex();
4108 int ContextLocalNameEntriesIndex();
4109 int ContextGlobalNameEntriesIndex();
4110 int ContextLocalInfoEntriesIndex();
4111 int ContextGlobalInfoEntriesIndex();
4112 int StrongModeFreeVariableNameEntriesIndex();
4113 int StrongModeFreeVariablePositionEntriesIndex();
4114 int ReceiverEntryIndex();
4115 int FunctionNameEntryIndex();
4117 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4118 VariableLocation* location, InitializationFlag* init_flag,
4119 MaybeAssignedFlag* maybe_assigned_flag);
4121 // Used for the function name variable for named function expressions, and for
4123 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4125 // Properties of scopes.
4126 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4127 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4128 STATIC_ASSERT(LANGUAGE_END == 3);
4129 class LanguageModeField
4130 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4131 class DeclarationScopeField
4132 : public BitField<bool, LanguageModeField::kNext, 1> {};
4133 class ReceiverVariableField
4134 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4136 class FunctionVariableField
4137 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4139 class FunctionVariableMode
4140 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4141 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4143 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4144 class HasSimpleParametersField
4145 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4146 class FunctionKindField
4147 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4149 // BitFields representing the encoded information for context locals in the
4150 // ContextLocalInfoEntries part.
4151 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4152 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4153 class ContextLocalMaybeAssignedFlag
4154 : public BitField<MaybeAssignedFlag, 4, 1> {};
4156 friend class ScopeIterator;
4160 // The cache for maps used by normalized (dictionary mode) objects.
4161 // Such maps do not have property descriptors, so a typical program
4162 // needs very limited number of distinct normalized maps.
4163 class NormalizedMapCache: public FixedArray {
4165 static Handle<NormalizedMapCache> New(Isolate* isolate);
4167 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4168 PropertyNormalizationMode mode);
4169 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4173 DECLARE_CAST(NormalizedMapCache)
4175 static inline bool IsNormalizedMapCache(const Object* obj);
4177 DECLARE_VERIFIER(NormalizedMapCache)
4179 static const int kEntries = 64;
4181 static inline int GetIndex(Handle<Map> map);
4183 // The following declarations hide base class methods.
4184 Object* get(int index);
4185 void set(int index, Object* value);
4189 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4190 // that is attached to code objects.
4191 class ByteArray: public FixedArrayBase {
4195 // Setter and getter.
4196 inline byte get(int index);
4197 inline void set(int index, byte value);
4199 // Treat contents as an int array.
4200 inline int get_int(int index);
4202 static int SizeFor(int length) {
4203 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4205 // We use byte arrays for free blocks in the heap. Given a desired size in
4206 // bytes that is a multiple of the word size and big enough to hold a byte
4207 // array, this function returns the number of elements a byte array should
4209 static int LengthFor(int size_in_bytes) {
4210 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4211 DCHECK(size_in_bytes >= kHeaderSize);
4212 return size_in_bytes - kHeaderSize;
4215 // Returns data start address.
4216 inline Address GetDataStartAddress();
4218 // Returns a pointer to the ByteArray object for a given data start address.
4219 static inline ByteArray* FromDataStartAddress(Address address);
4221 DECLARE_CAST(ByteArray)
4223 // Dispatched behavior.
4224 inline int ByteArraySize();
4225 DECLARE_PRINTER(ByteArray)
4226 DECLARE_VERIFIER(ByteArray)
4228 // Layout description.
4229 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4231 // Maximal memory consumption for a single ByteArray.
4232 static const int kMaxSize = 512 * MB;
4233 // Maximal length of a single ByteArray.
4234 static const int kMaxLength = kMaxSize - kHeaderSize;
4237 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4241 // BytecodeArray represents a sequence of interpreter bytecodes.
4242 class BytecodeArray : public FixedArrayBase {
4244 static int SizeFor(int length) {
4245 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4248 // Setter and getter
4249 inline byte get(int index);
4250 inline void set(int index, byte value);
4252 // Returns data start address.
4253 inline Address GetFirstBytecodeAddress();
4255 // Accessors for frame size.
4256 inline int frame_size() const;
4257 inline void set_frame_size(int frame_size);
4259 // Accessor for register count (derived from frame_size).
4260 inline int register_count() const;
4262 // Accessors for parameter count (including implicit 'this' receiver).
4263 inline int parameter_count() const;
4264 inline void set_parameter_count(int number_of_parameters);
4266 // Accessors for the constant pool.
4267 DECL_ACCESSORS(constant_pool, FixedArray)
4269 DECLARE_CAST(BytecodeArray)
4271 // Dispatched behavior.
4272 inline int BytecodeArraySize();
4273 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4275 DECLARE_PRINTER(BytecodeArray)
4276 DECLARE_VERIFIER(BytecodeArray)
4278 void Disassemble(std::ostream& os);
4280 // Layout description.
4281 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4282 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4283 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4284 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4286 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4288 // Maximal memory consumption for a single BytecodeArray.
4289 static const int kMaxSize = 512 * MB;
4290 // Maximal length of a single BytecodeArray.
4291 static const int kMaxLength = kMaxSize - kHeaderSize;
4294 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4298 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4299 // They look like heap objects (are heap object tagged and have a map) so that
4300 // the heap remains iterable. They have a size and a next pointer.
4301 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4302 // in the free list.
4303 class FreeSpace: public HeapObject {
4305 // [size]: size of the free space including the header.
4306 inline int size() const;
4307 inline void set_size(int value);
4309 inline int nobarrier_size() const;
4310 inline void nobarrier_set_size(int value);
4314 // Accessors for the next field.
4315 inline FreeSpace* next();
4316 inline FreeSpace** next_address();
4317 inline void set_next(FreeSpace* next);
4319 inline static FreeSpace* cast(HeapObject* obj);
4321 // Dispatched behavior.
4322 DECLARE_PRINTER(FreeSpace)
4323 DECLARE_VERIFIER(FreeSpace)
4325 // Layout description.
4326 // Size is smi tagged when it is stored.
4327 static const int kSizeOffset = HeapObject::kHeaderSize;
4328 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4331 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4335 // V has parameters (Type, type, TYPE, C type, element_size)
4336 #define TYPED_ARRAYS(V) \
4337 V(Uint8, uint8, UINT8, uint8_t, 1) \
4338 V(Int8, int8, INT8, int8_t, 1) \
4339 V(Uint16, uint16, UINT16, uint16_t, 2) \
4340 V(Int16, int16, INT16, int16_t, 2) \
4341 V(Uint32, uint32, UINT32, uint32_t, 4) \
4342 V(Int32, int32, INT32, int32_t, 4) \
4343 V(Float32, float32, FLOAT32, float, 4) \
4344 V(Float64, float64, FLOAT64, double, 8) \
4345 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4348 class FixedTypedArrayBase: public FixedArrayBase {
4350 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4351 DECL_ACCESSORS(base_pointer, Object)
4353 // [external_pointer]: Contains the offset between base_pointer and the start
4354 // of the data. If the base_pointer is a nullptr, the external_pointer
4355 // therefore points to the actual backing store.
4356 DECL_ACCESSORS(external_pointer, void)
4358 // Dispatched behavior.
4359 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4361 template <typename StaticVisitor>
4362 inline void FixedTypedArrayBaseIterateBody();
4364 DECLARE_CAST(FixedTypedArrayBase)
4366 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4367 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4368 static const int kHeaderSize =
4369 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4371 static const int kDataOffset = kHeaderSize;
4375 static inline int TypedArraySize(InstanceType type, int length);
4376 inline int TypedArraySize(InstanceType type);
4378 // Use with care: returns raw pointer into heap.
4379 inline void* DataPtr();
4381 inline int DataSize();
4384 static inline int ElementSize(InstanceType type);
4386 inline int DataSize(InstanceType type);
4388 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4392 template <class Traits>
4393 class FixedTypedArray: public FixedTypedArrayBase {
4395 typedef typename Traits::ElementType ElementType;
4396 static const InstanceType kInstanceType = Traits::kInstanceType;
4398 DECLARE_CAST(FixedTypedArray<Traits>)
4400 inline ElementType get_scalar(int index);
4401 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4402 inline void set(int index, ElementType value);
4404 static inline ElementType from_int(int value);
4405 static inline ElementType from_double(double value);
4407 // This accessor applies the correct conversion from Smi, HeapNumber
4409 inline void SetValue(uint32_t index, Object* value);
4411 DECLARE_PRINTER(FixedTypedArray)
4412 DECLARE_VERIFIER(FixedTypedArray)
4415 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4418 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4419 class Type##ArrayTraits { \
4420 public: /* NOLINT */ \
4421 typedef elementType ElementType; \
4422 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4423 static const char* Designator() { return #type " array"; } \
4424 static inline Handle<Object> ToHandle(Isolate* isolate, \
4425 elementType scalar); \
4426 static inline elementType defaultValue(); \
4429 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4431 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4433 #undef FIXED_TYPED_ARRAY_TRAITS
4436 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4437 // data for code generated by the Hydrogen/Lithium compiler. It also
4438 // contains information about functions that were inlined. If N different
4439 // functions were inlined then first N elements of the literal array will
4440 // contain these functions.
4443 class DeoptimizationInputData: public FixedArray {
4445 // Layout description. Indices in the array.
4446 static const int kTranslationByteArrayIndex = 0;
4447 static const int kInlinedFunctionCountIndex = 1;
4448 static const int kLiteralArrayIndex = 2;
4449 static const int kOsrAstIdIndex = 3;
4450 static const int kOsrPcOffsetIndex = 4;
4451 static const int kOptimizationIdIndex = 5;
4452 static const int kSharedFunctionInfoIndex = 6;
4453 static const int kWeakCellCacheIndex = 7;
4454 static const int kFirstDeoptEntryIndex = 8;
4456 // Offsets of deopt entry elements relative to the start of the entry.
4457 static const int kAstIdRawOffset = 0;
4458 static const int kTranslationIndexOffset = 1;
4459 static const int kArgumentsStackHeightOffset = 2;
4460 static const int kPcOffset = 3;
4461 static const int kDeoptEntrySize = 4;
4463 // Simple element accessors.
4464 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4465 inline type* name(); \
4466 inline void Set##name(type* value);
4468 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4469 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4470 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4471 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4472 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4473 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4474 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4475 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4477 #undef DECLARE_ELEMENT_ACCESSORS
4479 // Accessors for elements of the ith deoptimization entry.
4480 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4481 inline type* name(int i); \
4482 inline void Set##name(int i, type* value);
4484 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4485 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4486 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4487 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4489 #undef DECLARE_ENTRY_ACCESSORS
4491 inline BailoutId AstId(int i);
4493 inline void SetAstId(int i, BailoutId value);
4495 inline int DeoptCount();
4497 // Allocates a DeoptimizationInputData.
4498 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4499 int deopt_entry_count,
4500 PretenureFlag pretenure);
4502 DECLARE_CAST(DeoptimizationInputData)
4504 #ifdef ENABLE_DISASSEMBLER
4505 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4509 static int IndexForEntry(int i) {
4510 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4514 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4518 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4519 // data for code generated by the full compiler.
4520 // The format of the these objects is
4521 // [i * 2]: Ast ID for ith deoptimization.
4522 // [i * 2 + 1]: PC and state of ith deoptimization
4523 class DeoptimizationOutputData: public FixedArray {
4525 inline int DeoptPoints();
4527 inline BailoutId AstId(int index);
4529 inline void SetAstId(int index, BailoutId id);
4531 inline Smi* PcAndState(int index);
4532 inline void SetPcAndState(int index, Smi* offset);
4534 static int LengthOfFixedArray(int deopt_points) {
4535 return deopt_points * 2;
4538 // Allocates a DeoptimizationOutputData.
4539 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4540 int number_of_deopt_points,
4541 PretenureFlag pretenure);
4543 DECLARE_CAST(DeoptimizationOutputData)
4545 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4546 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4551 // HandlerTable is a fixed array containing entries for exception handlers in
4552 // the code object it is associated with. The tables comes in two flavors:
4553 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4554 // exception handler and a range representing the try-block covered by that
4555 // handler. Layout looks as follows:
4556 // [ range-start , range-end , handler-offset , stack-depth ]
4557 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4558 // per call-site that could throw an exception. Layout looks as follows:
4559 // [ return-address-offset , handler-offset ]
4560 class HandlerTable : public FixedArray {
4562 // Conservative prediction whether a given handler will locally catch an
4563 // exception or cause a re-throw to outside the code boundary. Since this is
4564 // undecidable it is merely an approximation (e.g. useful for debugger).
4565 enum CatchPrediction { UNCAUGHT, CAUGHT };
4567 // Accessors for handler table based on ranges.
4568 inline void SetRangeStart(int index, int value);
4569 inline void SetRangeEnd(int index, int value);
4570 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4571 inline void SetRangeDepth(int index, int value);
4573 // Accessors for handler table based on return addresses.
4574 inline void SetReturnOffset(int index, int value);
4575 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4577 // Lookup handler in a table based on ranges.
4578 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4580 // Lookup handler in a table based on return addresses.
4581 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4583 // Returns the required length of the underlying fixed array.
4584 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4585 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4587 DECLARE_CAST(HandlerTable)
4589 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4590 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4591 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4595 // Layout description for handler table based on ranges.
4596 static const int kRangeStartIndex = 0;
4597 static const int kRangeEndIndex = 1;
4598 static const int kRangeHandlerIndex = 2;
4599 static const int kRangeDepthIndex = 3;
4600 static const int kRangeEntrySize = 4;
4602 // Layout description for handler table based on return addresses.
4603 static const int kReturnOffsetIndex = 0;
4604 static const int kReturnHandlerIndex = 1;
4605 static const int kReturnEntrySize = 2;
4607 // Encoding of the {handler} field.
4608 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4609 class HandlerOffsetField : public BitField<int, 1, 30> {};
4613 // Code describes objects with on-the-fly generated machine code.
4614 class Code: public HeapObject {
4616 // Opaque data type for encapsulating code flags like kind, inline
4617 // cache state, and arguments count.
4618 typedef uint32_t Flags;
4620 #define NON_IC_KIND_LIST(V) \
4622 V(OPTIMIZED_FUNCTION) \
4629 #define IC_KIND_LIST(V) \
4640 #define CODE_KIND_LIST(V) \
4641 NON_IC_KIND_LIST(V) \
4645 #define DEFINE_CODE_KIND_ENUM(name) name,
4646 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4647 #undef DEFINE_CODE_KIND_ENUM
4651 // No more than 16 kinds. The value is currently encoded in four bits in
4653 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4655 static const char* Kind2String(Kind kind);
4663 static const int kPrologueOffsetNotSet = -1;
4665 #ifdef ENABLE_DISASSEMBLER
4667 static const char* ICState2String(InlineCacheState state);
4668 static const char* StubType2String(StubType type);
4669 static void PrintExtraICState(std::ostream& os, // NOLINT
4670 Kind kind, ExtraICState extra);
4671 void Disassemble(const char* name, std::ostream& os); // NOLINT
4672 #endif // ENABLE_DISASSEMBLER
4674 // [instruction_size]: Size of the native instructions
4675 inline int instruction_size() const;
4676 inline void set_instruction_size(int value);
4678 // [relocation_info]: Code relocation information
4679 DECL_ACCESSORS(relocation_info, ByteArray)
4680 void InvalidateRelocation();
4681 void InvalidateEmbeddedObjects();
4683 // [handler_table]: Fixed array containing offsets of exception handlers.
4684 DECL_ACCESSORS(handler_table, FixedArray)
4686 // [deoptimization_data]: Array containing data for deopt.
4687 DECL_ACCESSORS(deoptimization_data, FixedArray)
4689 // [raw_type_feedback_info]: This field stores various things, depending on
4690 // the kind of the code object.
4691 // FUNCTION => type feedback information.
4692 // STUB and ICs => major/minor key as Smi.
4693 DECL_ACCESSORS(raw_type_feedback_info, Object)
4694 inline Object* type_feedback_info();
4695 inline void set_type_feedback_info(
4696 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4697 inline uint32_t stub_key();
4698 inline void set_stub_key(uint32_t key);
4700 // [next_code_link]: Link for lists of optimized or deoptimized code.
4701 // Note that storage for this field is overlapped with typefeedback_info.
4702 DECL_ACCESSORS(next_code_link, Object)
4704 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4705 // field does not have to be traced during garbage collection since
4706 // it is only used by the garbage collector itself.
4707 DECL_ACCESSORS(gc_metadata, Object)
4709 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4710 // at the moment when this object was created.
4711 inline void set_ic_age(int count);
4712 inline int ic_age() const;
4714 // [prologue_offset]: Offset of the function prologue, used for aging
4715 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4716 inline int prologue_offset() const;
4717 inline void set_prologue_offset(int offset);
4719 // [constant_pool offset]: Offset of the constant pool.
4720 // Valid for FLAG_enable_embedded_constant_pool only
4721 inline int constant_pool_offset() const;
4722 inline void set_constant_pool_offset(int offset);
4724 // Unchecked accessors to be used during GC.
4725 inline ByteArray* unchecked_relocation_info();
4727 inline int relocation_size();
4729 // [flags]: Various code flags.
4730 inline Flags flags();
4731 inline void set_flags(Flags flags);
4733 // [flags]: Access to specific code flags.
4735 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4736 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4738 inline StubType type(); // Only valid for monomorphic IC stubs.
4740 // Testers for IC stub kinds.
4741 inline bool is_inline_cache_stub();
4742 inline bool is_debug_stub();
4743 inline bool is_handler();
4744 inline bool is_load_stub();
4745 inline bool is_keyed_load_stub();
4746 inline bool is_store_stub();
4747 inline bool is_keyed_store_stub();
4748 inline bool is_call_stub();
4749 inline bool is_binary_op_stub();
4750 inline bool is_compare_ic_stub();
4751 inline bool is_compare_nil_ic_stub();
4752 inline bool is_to_boolean_ic_stub();
4753 inline bool is_keyed_stub();
4754 inline bool is_optimized_code();
4755 inline bool embeds_maps_weakly();
4757 inline bool IsCodeStubOrIC();
4758 inline bool IsJavaScriptCode();
4760 inline void set_raw_kind_specific_flags1(int value);
4761 inline void set_raw_kind_specific_flags2(int value);
4763 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4764 // object was generated by either the hydrogen or the TurboFan optimizing
4765 // compiler (but it may not be an optimized function).
4766 inline bool is_crankshafted();
4767 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4768 inline void set_is_crankshafted(bool value);
4770 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4771 // code object was generated by the TurboFan optimizing compiler.
4772 inline bool is_turbofanned();
4773 inline void set_is_turbofanned(bool value);
4775 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4776 // embedded objects in code should be treated weakly.
4777 inline bool can_have_weak_objects();
4778 inline void set_can_have_weak_objects(bool value);
4780 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4781 // deoptimization support.
4782 inline bool has_deoptimization_support();
4783 inline void set_has_deoptimization_support(bool value);
4785 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4786 // been compiled with debug break slots.
4787 inline bool has_debug_break_slots();
4788 inline void set_has_debug_break_slots(bool value);
4790 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4791 // reloc info includes runtime and external references to support
4792 // serialization/deserialization.
4793 inline bool has_reloc_info_for_serialization();
4794 inline void set_has_reloc_info_for_serialization(bool value);
4796 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4797 // how long the function has been marked for OSR and therefore which
4798 // level of loop nesting we are willing to do on-stack replacement
4800 inline void set_allow_osr_at_loop_nesting_level(int level);
4801 inline int allow_osr_at_loop_nesting_level();
4803 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4804 // the code object was seen on the stack with no IC patching going on.
4805 inline int profiler_ticks();
4806 inline void set_profiler_ticks(int ticks);
4808 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4809 // For builtins, tells which builtin index it has.
4810 // Note that builtins can have a code kind other than BUILTIN, which means
4811 // that for arbitrary code objects, this index value may be random garbage.
4812 // To verify in that case, compare the code object to the indexed builtin.
4813 inline int builtin_index();
4814 inline void set_builtin_index(int id);
4816 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4817 // reserved in the code prologue.
4818 inline unsigned stack_slots();
4819 inline void set_stack_slots(unsigned slots);
4821 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4822 // the instruction stream where the safepoint table starts.
4823 inline unsigned safepoint_table_offset();
4824 inline void set_safepoint_table_offset(unsigned offset);
4826 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4827 // instruction stream where the back edge table starts.
4828 inline unsigned back_edge_table_offset();
4829 inline void set_back_edge_table_offset(unsigned offset);
4831 inline bool back_edges_patched_for_osr();
4833 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4834 inline uint16_t to_boolean_state();
4836 // [has_function_cache]: For kind STUB tells whether there is a function
4837 // cache is passed to the stub.
4838 inline bool has_function_cache();
4839 inline void set_has_function_cache(bool flag);
4842 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4843 // the code is going to be deoptimized because of dead embedded maps.
4844 inline bool marked_for_deoptimization();
4845 inline void set_marked_for_deoptimization(bool flag);
4847 // [constant_pool]: The constant pool for this function.
4848 inline Address constant_pool();
4850 // Get the safepoint entry for the given pc.
4851 SafepointEntry GetSafepointEntry(Address pc);
4853 // Find an object in a stub with a specified map
4854 Object* FindNthObject(int n, Map* match_map);
4856 // Find the first allocation site in an IC stub.
4857 AllocationSite* FindFirstAllocationSite();
4859 // Find the first map in an IC stub.
4860 Map* FindFirstMap();
4861 void FindAllMaps(MapHandleList* maps);
4863 // Find the first handler in an IC stub.
4864 Code* FindFirstHandler();
4866 // Find |length| handlers and put them into |code_list|. Returns false if not
4867 // enough handlers can be found.
4868 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4870 // Find the handler for |map|.
4871 MaybeHandle<Code> FindHandlerForMap(Map* map);
4873 // Find the first name in an IC stub.
4874 Name* FindFirstName();
4876 class FindAndReplacePattern;
4877 // For each (map-to-find, object-to-replace) pair in the pattern, this
4878 // function replaces the corresponding placeholder in the code with the
4879 // object-to-replace. The function assumes that pairs in the pattern come in
4880 // the same order as the placeholders in the code.
4881 // If the placeholder is a weak cell, then the value of weak cell is matched
4882 // against the map-to-find.
4883 void FindAndReplace(const FindAndReplacePattern& pattern);
4885 // The entire code object including its header is copied verbatim to the
4886 // snapshot so that it can be written in one, fast, memcpy during
4887 // deserialization. The deserializer will overwrite some pointers, rather
4888 // like a runtime linker, but the random allocation addresses used in the
4889 // mksnapshot process would still be present in the unlinked snapshot data,
4890 // which would make snapshot production non-reproducible. This method wipes
4891 // out the to-be-overwritten header data for reproducible snapshots.
4892 inline void WipeOutHeader();
4894 // Flags operations.
4895 static inline Flags ComputeFlags(
4896 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4897 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4898 CacheHolderFlag holder = kCacheOnReceiver);
4900 static inline Flags ComputeMonomorphicFlags(
4901 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4902 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4904 static inline Flags ComputeHandlerFlags(
4905 Kind handler_kind, StubType type = NORMAL,
4906 CacheHolderFlag holder = kCacheOnReceiver);
4908 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4909 static inline StubType ExtractTypeFromFlags(Flags flags);
4910 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4911 static inline Kind ExtractKindFromFlags(Flags flags);
4912 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4914 static inline Flags RemoveTypeFromFlags(Flags flags);
4915 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4917 // Convert a target address into a code object.
4918 static inline Code* GetCodeFromTargetAddress(Address address);
4920 // Convert an entry address into an object.
4921 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4923 // Returns the address of the first instruction.
4924 inline byte* instruction_start();
4926 // Returns the address right after the last instruction.
4927 inline byte* instruction_end();
4929 // Returns the size of the instructions, padding, and relocation information.
4930 inline int body_size();
4932 // Returns the address of the first relocation info (read backwards!).
4933 inline byte* relocation_start();
4935 // Code entry point.
4936 inline byte* entry();
4938 // Returns true if pc is inside this object's instructions.
4939 inline bool contains(byte* pc);
4941 // Relocate the code by delta bytes. Called to signal that this code
4942 // object has been moved by delta bytes.
4943 void Relocate(intptr_t delta);
4945 // Migrate code described by desc.
4946 void CopyFrom(const CodeDesc& desc);
4948 // Returns the object size for a given body (used for allocation).
4949 static int SizeFor(int body_size) {
4950 DCHECK_SIZE_TAG_ALIGNED(body_size);
4951 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4954 // Calculate the size of the code object to report for log events. This takes
4955 // the layout of the code object into account.
4956 inline int ExecutableSize();
4958 // Locating source position.
4959 int SourcePosition(Address pc);
4960 int SourceStatementPosition(Address pc);
4964 // Dispatched behavior.
4965 inline int CodeSize();
4966 inline void CodeIterateBody(ObjectVisitor* v);
4968 template<typename StaticVisitor>
4969 inline void CodeIterateBody(Heap* heap);
4971 DECLARE_PRINTER(Code)
4972 DECLARE_VERIFIER(Code)
4974 void ClearInlineCaches();
4975 void ClearInlineCaches(Kind kind);
4977 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4978 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4980 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4982 kToBeExecutedOnceCodeAge = -3,
4983 kNotExecutedCodeAge = -2,
4984 kExecutedOnceCodeAge = -1,
4986 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4988 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4989 kLastCodeAge = kAfterLastCodeAge - 1,
4990 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4991 kIsOldCodeAge = kSexagenarianCodeAge,
4992 kPreAgedCodeAge = kIsOldCodeAge - 1
4994 #undef DECLARE_CODE_AGE_ENUM
4996 // Code aging. Indicates how many full GCs this code has survived without
4997 // being entered through the prologue. Used to determine when it is
4998 // relatively safe to flush this code object and replace it with the lazy
4999 // compilation stub.
5000 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5001 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5002 void MakeYoung(Isolate* isolate);
5003 void MarkToBeExecutedOnce(Isolate* isolate);
5004 void MakeOlder(MarkingParity);
5005 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5008 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5009 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5012 void PrintDeoptLocation(FILE* out, Address pc);
5013 bool CanDeoptAt(Address pc);
5016 void VerifyEmbeddedObjectsDependency();
5020 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5021 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5022 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5025 inline bool CanContainWeakObjects();
5027 inline bool IsWeakObject(Object* object);
5029 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5031 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5032 WeakCell* CachedWeakCell();
5034 // Max loop nesting marker used to postpose OSR. We don't take loop
5035 // nesting that is deeper than 5 levels into account.
5036 static const int kMaxLoopNestingMarker = 6;
5038 static const int kConstantPoolSize =
5039 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5041 // Layout description.
5042 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5043 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5044 static const int kDeoptimizationDataOffset =
5045 kHandlerTableOffset + kPointerSize;
5046 // For FUNCTION kind, we store the type feedback info here.
5047 static const int kTypeFeedbackInfoOffset =
5048 kDeoptimizationDataOffset + kPointerSize;
5049 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5050 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5051 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5052 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5053 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5054 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5055 static const int kKindSpecificFlags2Offset =
5056 kKindSpecificFlags1Offset + kIntSize;
5057 // Note: We might be able to squeeze this into the flags above.
5058 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5059 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5060 static const int kHeaderPaddingStart =
5061 kConstantPoolOffset + kConstantPoolSize;
5063 // Add padding to align the instruction start following right after
5064 // the Code object header.
5065 static const int kHeaderSize =
5066 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5068 // Byte offsets within kKindSpecificFlags1Offset.
5069 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5070 class FullCodeFlagsHasDeoptimizationSupportField:
5071 public BitField<bool, 0, 1> {}; // NOLINT
5072 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5073 class FullCodeFlagsHasRelocInfoForSerialization
5074 : public BitField<bool, 2, 1> {};
5075 // Bit 3 in this bitfield is unused.
5076 class ProfilerTicksField : public BitField<int, 4, 28> {};
5078 // Flags layout. BitField<type, shift, size>.
5079 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5080 class TypeField : public BitField<StubType, 4, 1> {};
5081 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5082 class KindField : public BitField<Kind, 7, 4> {};
5083 class ExtraICStateField: public BitField<ExtraICState, 11,
5084 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5086 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5087 static const int kStackSlotsFirstBit = 0;
5088 static const int kStackSlotsBitCount = 24;
5089 static const int kHasFunctionCacheBit =
5090 kStackSlotsFirstBit + kStackSlotsBitCount;
5091 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5092 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5093 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5095 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5096 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5098 class StackSlotsField: public BitField<int,
5099 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5100 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5102 class MarkedForDeoptimizationField
5103 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5104 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5106 class CanHaveWeakObjectsField
5107 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5109 // KindSpecificFlags2 layout (ALL)
5110 static const int kIsCrankshaftedBit = 0;
5111 class IsCrankshaftedField: public BitField<bool,
5112 kIsCrankshaftedBit, 1> {}; // NOLINT
5114 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5115 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5116 static const int kSafepointTableOffsetBitCount = 30;
5118 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5119 kSafepointTableOffsetBitCount <= 32);
5120 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5122 class SafepointTableOffsetField: public BitField<int,
5123 kSafepointTableOffsetFirstBit,
5124 kSafepointTableOffsetBitCount> {}; // NOLINT
5126 // KindSpecificFlags2 layout (FUNCTION)
5127 class BackEdgeTableOffsetField: public BitField<int,
5128 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5129 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5130 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5131 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5133 static const int kArgumentsBits = 16;
5134 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5136 // This constant should be encodable in an ARM instruction.
5137 static const int kFlagsNotUsedInLookup =
5138 TypeField::kMask | CacheHolderField::kMask;
5141 friend class RelocIterator;
5142 friend class Deoptimizer; // For FindCodeAgeSequence.
5144 void ClearInlineCaches(Kind* kind);
5147 byte* FindCodeAgeSequence();
5148 static void GetCodeAgeAndParity(Code* code, Age* age,
5149 MarkingParity* parity);
5150 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5151 MarkingParity* parity);
5152 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5154 // Code aging -- platform-specific
5155 static void PatchPlatformCodeAge(Isolate* isolate,
5156 byte* sequence, Age age,
5157 MarkingParity parity);
5159 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5163 // This class describes the layout of dependent codes array of a map. The
5164 // array is partitioned into several groups of dependent codes. Each group
5165 // contains codes with the same dependency on the map. The array has the
5166 // following layout for n dependency groups:
5168 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5169 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5170 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5172 // The first n elements are Smis, each of them specifies the number of codes
5173 // in the corresponding group. The subsequent elements contain grouped code
5174 // objects in weak cells. The suffix of the array can be filled with the
5175 // undefined value if the number of codes is less than the length of the
5176 // array. The order of the code objects within a group is not preserved.
5178 // All code indexes used in the class are counted starting from the first
5179 // code object of the first group. In other words, code index 0 corresponds
5180 // to array index n = kCodesStartIndex.
5182 class DependentCode: public FixedArray {
5184 enum DependencyGroup {
5185 // Group of code that weakly embed this map and depend on being
5186 // deoptimized when the map is garbage collected.
5188 // Group of code that embed a transition to this map, and depend on being
5189 // deoptimized when the transition is replaced by a new version.
5191 // Group of code that omit run-time prototype checks for prototypes
5192 // described by this map. The group is deoptimized whenever an object
5193 // described by this map changes shape (and transitions to a new map),
5194 // possibly invalidating the assumptions embedded in the code.
5195 kPrototypeCheckGroup,
5196 // Group of code that depends on global property values in property cells
5197 // not being changed.
5198 kPropertyCellChangedGroup,
5199 // Group of code that omit run-time type checks for the field(s) introduced
5202 // Group of code that omit run-time type checks for initial maps of
5204 kInitialMapChangedGroup,
5205 // Group of code that depends on tenuring information in AllocationSites
5206 // not being changed.
5207 kAllocationSiteTenuringChangedGroup,
5208 // Group of code that depends on element transition information in
5209 // AllocationSites not being changed.
5210 kAllocationSiteTransitionChangedGroup
5213 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5215 // Array for holding the index of the first code object of each group.
5216 // The last element stores the total number of code objects.
5217 class GroupStartIndexes {
5219 explicit GroupStartIndexes(DependentCode* entries);
5220 void Recompute(DependentCode* entries);
5221 int at(int i) { return start_indexes_[i]; }
5222 int number_of_entries() { return start_indexes_[kGroupCount]; }
5224 int start_indexes_[kGroupCount + 1];
5227 bool Contains(DependencyGroup group, WeakCell* code_cell);
5229 static Handle<DependentCode> InsertCompilationDependencies(
5230 Handle<DependentCode> entries, DependencyGroup group,
5231 Handle<Foreign> info);
5233 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5234 DependencyGroup group,
5235 Handle<WeakCell> code_cell);
5237 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5238 WeakCell* code_cell);
5240 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5243 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5244 DependentCode::DependencyGroup group);
5246 bool MarkCodeForDeoptimization(Isolate* isolate,
5247 DependentCode::DependencyGroup group);
5249 // The following low-level accessors should only be used by this class
5250 // and the mark compact collector.
5251 inline int number_of_entries(DependencyGroup group);
5252 inline void set_number_of_entries(DependencyGroup group, int value);
5253 inline Object* object_at(int i);
5254 inline void set_object_at(int i, Object* object);
5255 inline void clear_at(int i);
5256 inline void copy(int from, int to);
5257 DECLARE_CAST(DependentCode)
5259 static const char* DependencyGroupName(DependencyGroup group);
5260 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5263 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5264 DependencyGroup group,
5265 Handle<Object> object);
5266 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5267 // Make a room at the end of the given group by moving out the first
5268 // code objects of the subsequent groups.
5269 inline void ExtendGroup(DependencyGroup group);
5270 // Compact by removing cleared weak cells and return true if there was
5271 // any cleared weak cell.
5273 static int Grow(int number_of_entries) {
5274 if (number_of_entries < 5) return number_of_entries + 1;
5275 return number_of_entries * 5 / 4;
5277 static const int kCodesStartIndex = kGroupCount;
5281 class PrototypeInfo;
5284 // All heap objects have a Map that describes their structure.
5285 // A Map contains information about:
5286 // - Size information about the object
5287 // - How to iterate over an object (for garbage collection)
5288 class Map: public HeapObject {
5291 // Size in bytes or kVariableSizeSentinel if instances do not have
5293 inline int instance_size();
5294 inline void set_instance_size(int value);
5296 // Only to clear an unused byte, remove once byte is used.
5297 inline void clear_unused();
5299 // [inobject_properties_or_constructor_function_index]: Provides access
5300 // to the inobject properties in case of JSObject maps, or the constructor
5301 // function index in case of primitive maps.
5302 inline int inobject_properties_or_constructor_function_index();
5303 inline void set_inobject_properties_or_constructor_function_index(int value);
5304 // Count of properties allocated in the object (JSObject only).
5305 inline int GetInObjectProperties();
5306 inline void SetInObjectProperties(int value);
5307 // Index of the constructor function in the native context (primitives only),
5308 // or the special sentinel value to indicate that there is no object wrapper
5309 // for the primitive (i.e. in case of null or undefined).
5310 static const int kNoConstructorFunctionIndex = 0;
5311 inline int GetConstructorFunctionIndex();
5312 inline void SetConstructorFunctionIndex(int value);
5315 inline InstanceType instance_type();
5316 inline void set_instance_type(InstanceType value);
5318 // Tells how many unused property fields are available in the
5319 // instance (only used for JSObject in fast mode).
5320 inline int unused_property_fields();
5321 inline void set_unused_property_fields(int value);
5324 inline byte bit_field() const;
5325 inline void set_bit_field(byte value);
5328 inline byte bit_field2() const;
5329 inline void set_bit_field2(byte value);
5332 inline uint32_t bit_field3() const;
5333 inline void set_bit_field3(uint32_t bits);
5335 class EnumLengthBits: public BitField<int,
5336 0, kDescriptorIndexBitCount> {}; // NOLINT
5337 class NumberOfOwnDescriptorsBits: public BitField<int,
5338 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5339 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5340 class DictionaryMap : public BitField<bool, 20, 1> {};
5341 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5342 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5343 class Deprecated : public BitField<bool, 23, 1> {};
5344 class IsUnstable : public BitField<bool, 24, 1> {};
5345 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5346 class IsStrong : public BitField<bool, 26, 1> {};
5349 // Keep this bit field at the very end for better code in
5350 // Builtins::kJSConstructStubGeneric stub.
5351 // This counter is used for in-object slack tracking and for map aging.
5352 // The in-object slack tracking is considered enabled when the counter is
5353 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5354 class Counter : public BitField<int, 28, 4> {};
5355 static const int kSlackTrackingCounterStart = 14;
5356 static const int kSlackTrackingCounterEnd = 8;
5357 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5358 static const int kRetainingCounterEnd = 0;
5360 // Tells whether the object in the prototype property will be used
5361 // for instances created from this function. If the prototype
5362 // property is set to a value that is not a JSObject, the prototype
5363 // property will not be used to create instances of the function.
5364 // See ECMA-262, 13.2.2.
5365 inline void set_non_instance_prototype(bool value);
5366 inline bool has_non_instance_prototype();
5368 // Tells whether the instance has a [[Construct]] internal method.
5369 // This property is implemented according to ES6, section 7.2.4.
5370 inline void set_is_constructor(bool value);
5371 inline bool is_constructor() const;
5373 // Tells whether the instance with this map should be ignored by the
5374 // Object.getPrototypeOf() function and the __proto__ accessor.
5375 inline void set_is_hidden_prototype();
5376 inline bool is_hidden_prototype() const;
5378 // Records and queries whether the instance has a named interceptor.
5379 inline void set_has_named_interceptor();
5380 inline bool has_named_interceptor();
5382 // Records and queries whether the instance has an indexed interceptor.
5383 inline void set_has_indexed_interceptor();
5384 inline bool has_indexed_interceptor();
5386 // Tells whether the instance is undetectable.
5387 // An undetectable object is a special class of JSObject: 'typeof' operator
5388 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5389 // a normal JS object. It is useful for implementing undetectable
5390 // document.all in Firefox & Safari.
5391 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5392 inline void set_is_undetectable();
5393 inline bool is_undetectable();
5395 // Tells whether the instance has a call-as-function handler.
5396 inline void set_is_observed();
5397 inline bool is_observed();
5399 // Tells whether the instance has a [[Call]] internal method.
5400 // This property is implemented according to ES6, section 7.2.3.
5401 inline void set_is_callable();
5402 inline bool is_callable() const;
5404 inline void set_is_strong();
5405 inline bool is_strong();
5406 inline void set_is_extensible(bool value);
5407 inline bool is_extensible();
5408 inline void set_is_prototype_map(bool value);
5409 inline bool is_prototype_map() const;
5411 inline void set_elements_kind(ElementsKind elements_kind);
5412 inline ElementsKind elements_kind();
5414 // Tells whether the instance has fast elements that are only Smis.
5415 inline bool has_fast_smi_elements();
5417 // Tells whether the instance has fast elements.
5418 inline bool has_fast_object_elements();
5419 inline bool has_fast_smi_or_object_elements();
5420 inline bool has_fast_double_elements();
5421 inline bool has_fast_elements();
5422 inline bool has_sloppy_arguments_elements();
5423 inline bool has_fixed_typed_array_elements();
5424 inline bool has_dictionary_elements();
5426 static bool IsValidElementsTransition(ElementsKind from_kind,
5427 ElementsKind to_kind);
5429 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5430 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5431 bool DictionaryElementsInPrototypeChainOnly();
5433 inline Map* ElementsTransitionMap();
5435 inline FixedArrayBase* GetInitialElements();
5437 // [raw_transitions]: Provides access to the transitions storage field.
5438 // Don't call set_raw_transitions() directly to overwrite transitions, use
5439 // the TransitionArray::ReplaceTransitions() wrapper instead!
5440 DECL_ACCESSORS(raw_transitions, Object)
5441 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5442 // (which prototype maps don't have).
5443 DECL_ACCESSORS(prototype_info, Object)
5444 // PrototypeInfo is created lazily using this helper (which installs it on
5445 // the given prototype's map).
5446 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5447 Handle<JSObject> prototype, Isolate* isolate);
5448 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5449 Handle<Map> prototype_map, Isolate* isolate);
5451 // [prototype chain validity cell]: Associated with a prototype object,
5452 // stored in that object's map's PrototypeInfo, indicates that prototype
5453 // chains through this object are currently valid. The cell will be
5454 // invalidated and replaced when the prototype chain changes.
5455 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5457 static const int kPrototypeChainValid = 0;
5458 static const int kPrototypeChainInvalid = 1;
5461 Map* FindFieldOwner(int descriptor);
5463 inline int GetInObjectPropertyOffset(int index);
5465 int NumberOfFields();
5467 // TODO(ishell): candidate with JSObject::MigrateToMap().
5468 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5469 int target_inobject, int target_unused,
5470 int* old_number_of_fields);
5471 // TODO(ishell): moveit!
5472 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5473 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5474 Representation rep1, Handle<HeapType> type1, Representation rep2,
5475 Handle<HeapType> type2, Isolate* isolate);
5476 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5477 Representation new_representation,
5478 Handle<HeapType> new_field_type);
5479 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5480 PropertyKind new_kind,
5481 PropertyAttributes new_attributes,
5482 Representation new_representation,
5483 Handle<HeapType> new_field_type,
5484 StoreMode store_mode);
5485 static Handle<Map> CopyGeneralizeAllRepresentations(
5486 Handle<Map> map, int modify_index, StoreMode store_mode,
5487 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5489 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5490 int descriptor_number,
5491 Handle<Object> value);
5493 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5494 const char* reason);
5496 // Returns the constructor name (the name (possibly, inferred name) of the
5497 // function that was used to instantiate the object).
5498 String* constructor_name();
5500 // Tells whether the map is used for JSObjects in dictionary mode (ie
5501 // normalized objects, ie objects for which HasFastProperties returns false).
5502 // A map can never be used for both dictionary mode and fast mode JSObjects.
5503 // False by default and for HeapObjects that are not JSObjects.
5504 inline void set_dictionary_map(bool value);
5505 inline bool is_dictionary_map();
5507 // Tells whether the instance needs security checks when accessing its
5509 inline void set_is_access_check_needed(bool access_check_needed);
5510 inline bool is_access_check_needed();
5512 // Returns true if map has a non-empty stub code cache.
5513 inline bool has_code_cache();
5515 // [prototype]: implicit prototype object.
5516 DECL_ACCESSORS(prototype, Object)
5517 // TODO(jkummerow): make set_prototype private.
5518 static void SetPrototype(
5519 Handle<Map> map, Handle<Object> prototype,
5520 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5522 // [constructor]: points back to the function responsible for this map.
5523 // The field overlaps with the back pointer. All maps in a transition tree
5524 // have the same constructor, so maps with back pointers can walk the
5525 // back pointer chain until they find the map holding their constructor.
5526 DECL_ACCESSORS(constructor_or_backpointer, Object)
5527 inline Object* GetConstructor() const;
5528 inline void SetConstructor(Object* constructor,
5529 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5530 // [back pointer]: points back to the parent map from which a transition
5531 // leads to this map. The field overlaps with the constructor (see above).
5532 inline Object* GetBackPointer();
5533 inline void SetBackPointer(Object* value,
5534 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5536 // [instance descriptors]: describes the object.
5537 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5539 // [layout descriptor]: describes the object layout.
5540 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5541 // |layout descriptor| accessor which can be used from GC.
5542 inline LayoutDescriptor* layout_descriptor_gc_safe();
5543 inline bool HasFastPointerLayout() const;
5545 // |layout descriptor| accessor that is safe to call even when
5546 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5547 // |layout_descriptor| field at all).
5548 inline LayoutDescriptor* GetLayoutDescriptor();
5550 inline void UpdateDescriptors(DescriptorArray* descriptors,
5551 LayoutDescriptor* layout_descriptor);
5552 inline void InitializeDescriptors(DescriptorArray* descriptors,
5553 LayoutDescriptor* layout_descriptor);
5555 // [stub cache]: contains stubs compiled for this map.
5556 DECL_ACCESSORS(code_cache, Object)
5558 // [dependent code]: list of optimized codes that weakly embed this map.
5559 DECL_ACCESSORS(dependent_code, DependentCode)
5561 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5562 DECL_ACCESSORS(weak_cell_cache, Object)
5564 inline PropertyDetails GetLastDescriptorDetails();
5566 inline int LastAdded();
5568 inline int NumberOfOwnDescriptors();
5569 inline void SetNumberOfOwnDescriptors(int number);
5571 inline Cell* RetrieveDescriptorsPointer();
5573 inline int EnumLength();
5574 inline void SetEnumLength(int length);
5576 inline bool owns_descriptors();
5577 inline void set_owns_descriptors(bool owns_descriptors);
5578 inline void mark_unstable();
5579 inline bool is_stable();
5580 inline void set_migration_target(bool value);
5581 inline bool is_migration_target();
5582 inline void set_counter(int value);
5583 inline int counter();
5584 inline void deprecate();
5585 inline bool is_deprecated();
5586 inline bool CanBeDeprecated();
5587 // Returns a non-deprecated version of the input. If the input was not
5588 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5589 // is found by re-transitioning from the root of the transition tree using the
5590 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5592 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5594 // Returns a non-deprecated version of the input. This method may deprecate
5595 // existing maps along the way if encodings conflict. Not for use while
5596 // gathering type feedback. Use TryUpdate in those cases instead.
5597 static Handle<Map> Update(Handle<Map> map);
5599 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5600 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5601 Descriptor* descriptor,
5602 TransitionFlag flag);
5604 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5607 Handle<HeapType> type,
5608 PropertyAttributes attributes,
5609 Representation representation,
5610 TransitionFlag flag);
5612 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5615 Handle<Object> constant,
5616 PropertyAttributes attributes,
5617 TransitionFlag flag);
5619 // Returns a new map with all transitions dropped from the given map and
5620 // the ElementsKind set.
5621 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5622 ElementsKind to_kind);
5624 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5626 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5628 TransitionFlag flag);
5630 static Handle<Map> CopyForObserved(Handle<Map> map);
5632 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5633 PropertyAttributes attrs_to_add,
5634 Handle<Symbol> transition_marker,
5635 const char* reason);
5637 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5640 // Maximal number of fast properties. Used to restrict the number of map
5641 // transitions to avoid an explosion in the number of maps for objects used as
5643 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5644 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5646 Handle<Object> value,
5647 PropertyAttributes attributes,
5648 StoreFromKeyed store_mode);
5649 static Handle<Map> TransitionToAccessorProperty(
5650 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5651 Handle<Object> accessor, PropertyAttributes attributes);
5652 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5655 PropertyAttributes attributes);
5657 inline void AppendDescriptor(Descriptor* desc);
5659 // Returns a copy of the map, prepared for inserting into the transition
5660 // tree (if the |map| owns descriptors then the new one will share
5661 // descriptors with |map|).
5662 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5664 // Returns a copy of the map, with all transitions dropped from the
5665 // instance descriptors.
5666 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5667 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5669 // Returns the next free property index (only valid for FAST MODE).
5670 int NextFreePropertyIndex();
5672 // Returns the number of properties described in instance_descriptors
5673 // filtering out properties with the specified attributes.
5674 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5675 PropertyAttributes filter = NONE);
5679 // Code cache operations.
5681 // Clears the code cache.
5682 inline void ClearCodeCache(Heap* heap);
5684 // Update code cache.
5685 static void UpdateCodeCache(Handle<Map> map,
5689 // Extend the descriptor array of the map with the list of descriptors.
5690 // In case of duplicates, the latest descriptor is used.
5691 static void AppendCallbackDescriptors(Handle<Map> map,
5692 Handle<Object> descriptors);
5694 static inline int SlackForArraySize(int old_size, int size_limit);
5696 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5698 // Returns the found code or undefined if absent.
5699 Object* FindInCodeCache(Name* name, Code::Flags flags);
5701 // Returns the non-negative index of the code object if it is in the
5702 // cache and -1 otherwise.
5703 int IndexInCodeCache(Object* name, Code* code);
5705 // Removes a code object from the code cache at the given index.
5706 void RemoveFromCodeCache(Name* name, Code* code, int index);
5708 // Computes a hash value for this map, to be used in HashTables and such.
5711 // Returns the map that this map transitions to if its elements_kind
5712 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5713 // |safe_to_add_transitions| is set to false if adding transitions is not
5715 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5717 // Returns the transitioned map for this map with the most generic
5718 // elements_kind that's found in |candidates|, or null handle if no match is
5720 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5721 MapHandleList* candidates);
5723 inline bool CanTransition();
5725 inline bool IsPrimitiveMap();
5726 inline bool IsJSObjectMap();
5727 inline bool IsJSArrayMap();
5728 inline bool IsJSFunctionMap();
5729 inline bool IsStringMap();
5730 inline bool IsJSProxyMap();
5731 inline bool IsJSGlobalProxyMap();
5732 inline bool IsJSGlobalObjectMap();
5733 inline bool IsGlobalObjectMap();
5735 inline bool CanOmitMapChecks();
5737 static void AddDependentCode(Handle<Map> map,
5738 DependentCode::DependencyGroup group,
5741 bool IsMapInArrayPrototypeChain();
5743 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5745 // Dispatched behavior.
5746 DECLARE_PRINTER(Map)
5747 DECLARE_VERIFIER(Map)
5750 void DictionaryMapVerify();
5751 void VerifyOmittedMapChecks();
5754 inline int visitor_id();
5755 inline void set_visitor_id(int visitor_id);
5757 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5758 Handle<Object> prototype,
5759 PrototypeOptimizationMode mode);
5761 static const int kMaxPreAllocatedPropertyFields = 255;
5763 // Layout description.
5764 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5765 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5766 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5767 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5768 static const int kConstructorOrBackPointerOffset =
5769 kPrototypeOffset + kPointerSize;
5770 // When there is only one transition, it is stored directly in this field;
5771 // otherwise a transition array is used.
5772 // For prototype maps, this slot is used to store this map's PrototypeInfo
5774 static const int kTransitionsOrPrototypeInfoOffset =
5775 kConstructorOrBackPointerOffset + kPointerSize;
5776 static const int kDescriptorsOffset =
5777 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5778 #if V8_DOUBLE_FIELDS_UNBOXING
5779 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5780 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5782 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5783 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5785 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5786 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5787 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5789 // Layout of pointer fields. Heap iteration code relies on them
5790 // being continuously allocated.
5791 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5792 static const int kPointerFieldsEndOffset = kSize;
5794 // Byte offsets within kInstanceSizesOffset.
5795 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5796 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5797 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5798 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5799 // Note there is one byte available for use here.
5800 static const int kUnusedByte = 2;
5801 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5802 static const int kVisitorIdByte = 3;
5803 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5805 // Byte offsets within kInstanceAttributesOffset attributes.
5806 #if V8_TARGET_LITTLE_ENDIAN
5807 // Order instance type and bit field together such that they can be loaded
5808 // together as a 16-bit word with instance type in the lower 8 bits regardless
5809 // of endianess. Also provide endian-independent offset to that 16-bit word.
5810 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5811 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5813 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5814 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5816 static const int kInstanceTypeAndBitFieldOffset =
5817 kInstanceAttributesOffset + 0;
5818 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5819 static const int kUnusedPropertyFieldsByte = 3;
5820 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5822 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5823 Internals::kMapInstanceTypeAndBitFieldOffset);
5825 // Bit positions for bit field.
5826 static const int kHasNonInstancePrototype = 0;
5827 static const int kIsCallable = 1;
5828 static const int kHasNamedInterceptor = 2;
5829 static const int kHasIndexedInterceptor = 3;
5830 static const int kIsUndetectable = 4;
5831 static const int kIsObserved = 5;
5832 static const int kIsAccessCheckNeeded = 6;
5833 static const int kIsConstructor = 7;
5835 // Bit positions for bit field 2
5836 static const int kIsExtensible = 0;
5838 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5839 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5841 // Derived values from bit field 2
5842 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5843 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5844 static const int8_t kMaximumBitField2FastSmiElementValue =
5845 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5846 Map::ElementsKindBits::kShift) - 1;
5847 static const int8_t kMaximumBitField2FastHoleyElementValue =
5848 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5849 Map::ElementsKindBits::kShift) - 1;
5850 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5851 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5852 Map::ElementsKindBits::kShift) - 1;
5854 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5855 kPointerFieldsEndOffset,
5856 kSize> BodyDescriptor;
5858 // Compares this map to another to see if they describe equivalent objects.
5859 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5860 // it had exactly zero inobject properties.
5861 // The "shared" flags of both this map and |other| are ignored.
5862 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5864 // Returns true if given field is unboxed double.
5865 inline bool IsUnboxedDoubleField(FieldIndex index);
5868 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5869 static void TraceAllTransitions(Map* map);
5872 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5873 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5874 Handle<LayoutDescriptor> layout_descriptor);
5877 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5878 Handle<Name> name, SimpleTransitionFlag flag);
5880 bool EquivalentToForTransition(Map* other);
5881 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5882 static Handle<Map> ShareDescriptor(Handle<Map> map,
5883 Handle<DescriptorArray> descriptors,
5884 Descriptor* descriptor);
5885 static Handle<Map> CopyInstallDescriptors(
5886 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5887 Handle<LayoutDescriptor> layout_descriptor);
5888 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5889 Descriptor* descriptor,
5890 TransitionFlag flag);
5891 static Handle<Map> CopyReplaceDescriptors(
5892 Handle<Map> map, Handle<DescriptorArray> descriptors,
5893 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5894 MaybeHandle<Name> maybe_name, const char* reason,
5895 SimpleTransitionFlag simple_flag);
5897 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5898 Handle<DescriptorArray> descriptors,
5899 Descriptor* descriptor,
5901 TransitionFlag flag);
5902 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5903 Handle<Map> map, int descriptor, PropertyKind kind,
5904 PropertyAttributes attributes, const char** reason);
5906 static Handle<Map> CopyNormalized(Handle<Map> map,
5907 PropertyNormalizationMode mode);
5909 // Fires when the layout of an object with a leaf map changes.
5910 // This includes adding transitions to the leaf map or changing
5911 // the descriptor array.
5912 inline void NotifyLeafMapLayoutChange();
5914 void DeprecateTransitionTree();
5915 bool DeprecateTarget(PropertyKind kind, Name* key,
5916 PropertyAttributes attributes,
5917 DescriptorArray* new_descriptors,
5918 LayoutDescriptor* new_layout_descriptor);
5920 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5922 // Update field type of the given descriptor to new representation and new
5923 // type. The type must be prepared for storing in descriptor array:
5924 // it must be either a simple type or a map wrapped in a weak cell.
5925 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5926 Representation new_representation,
5927 Handle<Object> new_wrapped_type);
5929 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5930 PropertyAttributes attributes);
5931 void PrintGeneralization(FILE* file,
5936 bool constant_to_field,
5937 Representation old_representation,
5938 Representation new_representation,
5939 HeapType* old_field_type,
5940 HeapType* new_field_type);
5942 static const int kFastPropertiesSoftLimit = 12;
5943 static const int kMaxFastProperties = 128;
5945 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5949 // An abstract superclass, a marker class really, for simple structure classes.
5950 // It doesn't carry much functionality but allows struct classes to be
5951 // identified in the type system.
5952 class Struct: public HeapObject {
5954 inline void InitializeBody(int object_size);
5955 DECLARE_CAST(Struct)
5959 // A simple one-element struct, useful where smis need to be boxed.
5960 class Box : public Struct {
5962 // [value]: the boxed contents.
5963 DECL_ACCESSORS(value, Object)
5967 // Dispatched behavior.
5968 DECLARE_PRINTER(Box)
5969 DECLARE_VERIFIER(Box)
5971 static const int kValueOffset = HeapObject::kHeaderSize;
5972 static const int kSize = kValueOffset + kPointerSize;
5975 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5979 // Container for metadata stored on each prototype map.
5980 class PrototypeInfo : public Struct {
5982 static const int UNREGISTERED = -1;
5984 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5985 // or Smi(0) if uninitialized.
5986 DECL_ACCESSORS(prototype_users, Object)
5987 // [registry_slot]: Slot in prototype's user registry where this user
5988 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5989 inline int registry_slot() const;
5990 inline void set_registry_slot(int slot);
5991 // [validity_cell]: Cell containing the validity bit for prototype chains
5992 // going through this object, or Smi(0) if uninitialized.
5993 // When a prototype object changes its map, then both its own validity cell
5994 // and those of all "downstream" prototypes are invalidated; handlers for a
5995 // given receiver embed the currently valid cell for that receiver's prototype
5996 // during their compilation and check it on execution.
5997 DECL_ACCESSORS(validity_cell, Object)
5998 // [constructor_name]: User-friendly name of the original constructor.
5999 DECL_ACCESSORS(constructor_name, Object)
6001 DECLARE_CAST(PrototypeInfo)
6003 // Dispatched behavior.
6004 DECLARE_PRINTER(PrototypeInfo)
6005 DECLARE_VERIFIER(PrototypeInfo)
6007 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6008 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6009 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6010 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6011 static const int kSize = kConstructorNameOffset + kPointerSize;
6014 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6018 // Pair used to store both a ScopeInfo and an extension object in the extension
6019 // slot of a block context. Needed in the rare case where a declaration block
6020 // scope (a "varblock" as used to desugar parameter destructuring) also contains
6021 // a sloppy direct eval. (In no other case both are needed at the same time.)
6022 class SloppyBlockWithEvalContextExtension : public Struct {
6024 // [scope_info]: Scope info.
6025 DECL_ACCESSORS(scope_info, ScopeInfo)
6026 // [extension]: Extension object.
6027 DECL_ACCESSORS(extension, JSObject)
6029 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
6031 // Dispatched behavior.
6032 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
6033 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
6035 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
6036 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
6037 static const int kSize = kExtensionOffset + kPointerSize;
6040 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6044 // Script describes a script which has been added to the VM.
6045 class Script: public Struct {
6054 // Script compilation types.
6055 enum CompilationType {
6056 COMPILATION_TYPE_HOST = 0,
6057 COMPILATION_TYPE_EVAL = 1
6060 // Script compilation state.
6061 enum CompilationState {
6062 COMPILATION_STATE_INITIAL = 0,
6063 COMPILATION_STATE_COMPILED = 1
6066 // [source]: the script source.
6067 DECL_ACCESSORS(source, Object)
6069 // [name]: the script name.
6070 DECL_ACCESSORS(name, Object)
6072 // [id]: the script id.
6073 DECL_ACCESSORS(id, Smi)
6075 // [line_offset]: script line offset in resource from where it was extracted.
6076 DECL_ACCESSORS(line_offset, Smi)
6078 // [column_offset]: script column offset in resource from where it was
6080 DECL_ACCESSORS(column_offset, Smi)
6082 // [context_data]: context data for the context this script was compiled in.
6083 DECL_ACCESSORS(context_data, Object)
6085 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6086 DECL_ACCESSORS(wrapper, HeapObject)
6088 // [type]: the script type.
6089 DECL_ACCESSORS(type, Smi)
6091 // [line_ends]: FixedArray of line ends positions.
6092 DECL_ACCESSORS(line_ends, Object)
6094 // [eval_from_shared]: for eval scripts the shared funcion info for the
6095 // function from which eval was called.
6096 DECL_ACCESSORS(eval_from_shared, Object)
6098 // [eval_from_instructions_offset]: the instruction offset in the code for the
6099 // function from which eval was called where eval was called.
6100 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6102 // [shared_function_infos]: weak fixed array containing all shared
6103 // function infos created from this script.
6104 DECL_ACCESSORS(shared_function_infos, Object)
6106 // [flags]: Holds an exciting bitfield.
6107 DECL_ACCESSORS(flags, Smi)
6109 // [source_url]: sourceURL from magic comment
6110 DECL_ACCESSORS(source_url, Object)
6112 // [source_url]: sourceMappingURL magic comment
6113 DECL_ACCESSORS(source_mapping_url, Object)
6115 // [compilation_type]: how the the script was compiled. Encoded in the
6117 inline CompilationType compilation_type();
6118 inline void set_compilation_type(CompilationType type);
6120 // [compilation_state]: determines whether the script has already been
6121 // compiled. Encoded in the 'flags' field.
6122 inline CompilationState compilation_state();
6123 inline void set_compilation_state(CompilationState state);
6125 // [hide_source]: determines whether the script source can be exposed as
6126 // function source. Encoded in the 'flags' field.
6127 inline bool hide_source();
6128 inline void set_hide_source(bool value);
6130 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6131 // and used by the embedder to make decisions about the script. V8 just passes
6132 // this through. Encoded in the 'flags' field.
6133 inline v8::ScriptOriginOptions origin_options();
6134 inline void set_origin_options(ScriptOriginOptions origin_options);
6136 DECLARE_CAST(Script)
6138 // If script source is an external string, check that the underlying
6139 // resource is accessible. Otherwise, always return true.
6140 inline bool HasValidSource();
6142 // Convert code position into column number.
6143 static int GetColumnNumber(Handle<Script> script, int code_pos);
6145 // Convert code position into (zero-based) line number.
6146 // The non-handlified version does not allocate, but may be much slower.
6147 static int GetLineNumber(Handle<Script> script, int code_pos);
6148 int GetLineNumber(int code_pos);
6150 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6152 // Init line_ends array with code positions of line ends inside script source.
6153 static void InitLineEnds(Handle<Script> script);
6155 // Get the JS object wrapping the given script; create it if none exists.
6156 static Handle<JSObject> GetWrapper(Handle<Script> script);
6158 // Look through the list of existing shared function infos to find one
6159 // that matches the function literal. Return empty handle if not found.
6160 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6162 // Iterate over all script objects on the heap.
6165 explicit Iterator(Isolate* isolate);
6169 WeakFixedArray::Iterator iterator_;
6170 DISALLOW_COPY_AND_ASSIGN(Iterator);
6173 // Dispatched behavior.
6174 DECLARE_PRINTER(Script)
6175 DECLARE_VERIFIER(Script)
6177 static const int kSourceOffset = HeapObject::kHeaderSize;
6178 static const int kNameOffset = kSourceOffset + kPointerSize;
6179 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6180 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6181 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6182 static const int kWrapperOffset = kContextOffset + kPointerSize;
6183 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6184 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6185 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6186 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6187 static const int kEvalFrominstructionsOffsetOffset =
6188 kEvalFromSharedOffset + kPointerSize;
6189 static const int kSharedFunctionInfosOffset =
6190 kEvalFrominstructionsOffsetOffset + kPointerSize;
6191 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6192 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6193 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6194 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6197 int GetLineNumberWithArray(int code_pos);
6199 // Bit positions in the flags field.
6200 static const int kCompilationTypeBit = 0;
6201 static const int kCompilationStateBit = 1;
6202 static const int kHideSourceBit = 2;
6203 static const int kOriginOptionsShift = 3;
6204 static const int kOriginOptionsSize = 3;
6205 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6206 << kOriginOptionsShift;
6208 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6212 // List of builtin functions we want to identify to improve code
6215 // Each entry has a name of a global object property holding an object
6216 // optionally followed by ".prototype", a name of a builtin function
6217 // on the object (the one the id is set for), and a label.
6219 // Installation of ids for the selected builtin functions is handled
6220 // by the bootstrapper.
6221 #define FUNCTIONS_WITH_ID_LIST(V) \
6222 V(Array.prototype, indexOf, ArrayIndexOf) \
6223 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6224 V(Array.prototype, push, ArrayPush) \
6225 V(Array.prototype, pop, ArrayPop) \
6226 V(Array.prototype, shift, ArrayShift) \
6227 V(Function.prototype, apply, FunctionApply) \
6228 V(Function.prototype, call, FunctionCall) \
6229 V(String.prototype, charCodeAt, StringCharCodeAt) \
6230 V(String.prototype, charAt, StringCharAt) \
6231 V(String, fromCharCode, StringFromCharCode) \
6232 V(Math, random, MathRandom) \
6233 V(Math, floor, MathFloor) \
6234 V(Math, round, MathRound) \
6235 V(Math, ceil, MathCeil) \
6236 V(Math, abs, MathAbs) \
6237 V(Math, log, MathLog) \
6238 V(Math, exp, MathExp) \
6239 V(Math, sqrt, MathSqrt) \
6240 V(Math, pow, MathPow) \
6241 V(Math, max, MathMax) \
6242 V(Math, min, MathMin) \
6243 V(Math, cos, MathCos) \
6244 V(Math, sin, MathSin) \
6245 V(Math, tan, MathTan) \
6246 V(Math, acos, MathAcos) \
6247 V(Math, asin, MathAsin) \
6248 V(Math, atan, MathAtan) \
6249 V(Math, atan2, MathAtan2) \
6250 V(Math, imul, MathImul) \
6251 V(Math, clz32, MathClz32) \
6252 V(Math, fround, MathFround)
6254 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6255 V(Atomics, load, AtomicsLoad) \
6256 V(Atomics, store, AtomicsStore)
6258 enum BuiltinFunctionId {
6260 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6262 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6263 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6264 #undef DECLARE_FUNCTION_ID
6265 // Fake id for a special case of Math.pow. Note, it continues the
6266 // list of math functions.
6271 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6272 // that both {code} and {literals} can be NULL to pass search result status.
6273 struct CodeAndLiterals {
6274 Code* code; // Cached optimized code.
6275 FixedArray* literals; // Cached literals array.
6279 // SharedFunctionInfo describes the JSFunction information that can be
6280 // shared by multiple instances of the function.
6281 class SharedFunctionInfo: public HeapObject {
6283 // [name]: Function name.
6284 DECL_ACCESSORS(name, Object)
6286 // [code]: Function code.
6287 DECL_ACCESSORS(code, Code)
6288 inline void ReplaceCode(Code* code);
6290 // [optimized_code_map]: Map from native context to optimized code
6291 // and a shared literals array or Smi(0) if none.
6292 DECL_ACCESSORS(optimized_code_map, Object)
6294 // Returns entry from optimized code map for specified context and OSR entry.
6295 // Note that {code == nullptr, literals == nullptr} indicates no matching
6296 // entry has been found, whereas {code, literals == nullptr} indicates that
6297 // code is context-independent.
6298 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6299 BailoutId osr_ast_id);
6301 // Clear optimized code map.
6302 void ClearOptimizedCodeMap();
6304 // Removes a specific optimized code object from the optimized code map.
6305 // In case of non-OSR the code reference is cleared from the cache entry but
6306 // the entry itself is left in the map in order to proceed sharing literals.
6307 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6309 // Trims the optimized code map after entries have been removed.
6310 void TrimOptimizedCodeMap(int shrink_by);
6312 // Add a new entry to the optimized code map for context-independent code.
6313 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6316 // Add a new entry to the optimized code map for context-dependent code.
6317 // |code| is either a code object or an undefined value. In the latter case
6318 // the entry just maps |native_context, osr_ast_id| pair to |literals| array.
6319 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6320 Handle<Context> native_context,
6321 Handle<HeapObject> code,
6322 Handle<FixedArray> literals,
6323 BailoutId osr_ast_id);
6325 // Set up the link between shared function info and the script. The shared
6326 // function info is added to the list on the script.
6327 static void SetScript(Handle<SharedFunctionInfo> shared,
6328 Handle<Object> script_object);
6330 // Layout description of the optimized code map.
6331 static const int kNextMapIndex = 0;
6332 static const int kSharedCodeIndex = 1;
6333 static const int kEntriesStart = 2;
6334 static const int kContextOffset = 0;
6335 static const int kCachedCodeOffset = 1;
6336 static const int kLiteralsOffset = 2;
6337 static const int kOsrAstIdOffset = 3;
6338 static const int kEntryLength = 4;
6339 static const int kInitialLength = kEntriesStart + kEntryLength;
6341 static const int kNotFound = -1;
6343 // [scope_info]: Scope info.
6344 DECL_ACCESSORS(scope_info, ScopeInfo)
6346 // [construct stub]: Code stub for constructing instances of this function.
6347 DECL_ACCESSORS(construct_stub, Code)
6349 // Returns if this function has been compiled to native code yet.
6350 inline bool is_compiled();
6352 // [length]: The function length - usually the number of declared parameters.
6353 // Use up to 2^30 parameters.
6354 inline int length() const;
6355 inline void set_length(int value);
6357 // [internal formal parameter count]: The declared number of parameters.
6358 // For subclass constructors, also includes new.target.
6359 // The size of function's frame is internal_formal_parameter_count + 1.
6360 inline int internal_formal_parameter_count() const;
6361 inline void set_internal_formal_parameter_count(int value);
6363 // Set the formal parameter count so the function code will be
6364 // called without using argument adaptor frames.
6365 inline void DontAdaptArguments();
6367 // [expected_nof_properties]: Expected number of properties for the function.
6368 inline int expected_nof_properties() const;
6369 inline void set_expected_nof_properties(int value);
6371 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6372 // (increasingly) from crankshafted code where sufficient feedback isn't
6374 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6376 // Unconditionally clear the type feedback vector (including vector ICs).
6377 void ClearTypeFeedbackInfo();
6379 // Clear the type feedback vector with a more subtle policy at GC time.
6380 void ClearTypeFeedbackInfoAtGCTime();
6383 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6384 // even if the GC moves this SharedFunctionInfo.
6385 inline int unique_id() const;
6386 inline void set_unique_id(int value);
6389 // [instance class name]: class name for instances.
6390 DECL_ACCESSORS(instance_class_name, Object)
6392 // [function data]: This field holds some additional data for function.
6393 // Currently it has one of:
6394 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6395 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6396 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6397 // In the long run we don't want all functions to have this field but
6398 // we can fix that when we have a better model for storing hidden data
6400 DECL_ACCESSORS(function_data, Object)
6402 inline bool IsApiFunction();
6403 inline FunctionTemplateInfo* get_api_func_data();
6404 inline bool HasBuiltinFunctionId();
6405 inline BuiltinFunctionId builtin_function_id();
6406 inline bool HasBytecodeArray();
6407 inline BytecodeArray* bytecode_array();
6409 // [script info]: Script from which the function originates.
6410 DECL_ACCESSORS(script, Object)
6412 // [num_literals]: Number of literals used by this function.
6413 inline int num_literals() const;
6414 inline void set_num_literals(int value);
6416 // [start_position_and_type]: Field used to store both the source code
6417 // position, whether or not the function is a function expression,
6418 // and whether or not the function is a toplevel function. The two
6419 // least significants bit indicates whether the function is an
6420 // expression and the rest contains the source code position.
6421 inline int start_position_and_type() const;
6422 inline void set_start_position_and_type(int value);
6424 // The function is subject to debugging if a debug info is attached.
6425 inline bool HasDebugInfo();
6426 inline DebugInfo* GetDebugInfo();
6428 // A function has debug code if the compiled code has debug break slots.
6429 inline bool HasDebugCode();
6431 // [debug info]: Debug information.
6432 DECL_ACCESSORS(debug_info, Object)
6434 // [inferred name]: Name inferred from variable or property
6435 // assignment of this function. Used to facilitate debugging and
6436 // profiling of JavaScript code written in OO style, where almost
6437 // all functions are anonymous but are assigned to object
6439 DECL_ACCESSORS(inferred_name, String)
6441 // The function's name if it is non-empty, otherwise the inferred name.
6442 String* DebugName();
6444 // Position of the 'function' token in the script source.
6445 inline int function_token_position() const;
6446 inline void set_function_token_position(int function_token_position);
6448 // Position of this function in the script source.
6449 inline int start_position() const;
6450 inline void set_start_position(int start_position);
6452 // End position of this function in the script source.
6453 inline int end_position() const;
6454 inline void set_end_position(int end_position);
6456 // Is this function a function expression in the source code.
6457 DECL_BOOLEAN_ACCESSORS(is_expression)
6459 // Is this function a top-level function (scripts, evals).
6460 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6462 // Bit field containing various information collected by the compiler to
6463 // drive optimization.
6464 inline int compiler_hints() const;
6465 inline void set_compiler_hints(int value);
6467 inline int ast_node_count() const;
6468 inline void set_ast_node_count(int count);
6470 inline int profiler_ticks() const;
6471 inline void set_profiler_ticks(int ticks);
6473 // Inline cache age is used to infer whether the function survived a context
6474 // disposal or not. In the former case we reset the opt_count.
6475 inline int ic_age();
6476 inline void set_ic_age(int age);
6478 // Indicates if this function can be lazy compiled.
6479 // This is used to determine if we can safely flush code from a function
6480 // when doing GC if we expect that the function will no longer be used.
6481 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6483 // Indicates if this function can be lazy compiled without a context.
6484 // This is used to determine if we can force compilation without reaching
6485 // the function through program execution but through other means (e.g. heap
6486 // iteration by the debugger).
6487 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6489 // Indicates whether optimizations have been disabled for this
6490 // shared function info. If a function is repeatedly optimized or if
6491 // we cannot optimize the function we disable optimization to avoid
6492 // spending time attempting to optimize it again.
6493 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6495 // Indicates the language mode.
6496 inline LanguageMode language_mode();
6497 inline void set_language_mode(LanguageMode language_mode);
6499 // False if the function definitely does not allocate an arguments object.
6500 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6502 // Indicates that this function uses a super property (or an eval that may
6503 // use a super property).
6504 // This is needed to set up the [[HomeObject]] on the function instance.
6505 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6507 // True if the function has any duplicated parameter names.
6508 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6510 // Indicates whether the function is a native function.
6511 // These needs special treatment in .call and .apply since
6512 // null passed as the receiver should not be translated to the
6514 DECL_BOOLEAN_ACCESSORS(native)
6516 // Indicate that this function should always be inlined in optimized code.
6517 DECL_BOOLEAN_ACCESSORS(force_inline)
6519 // Indicates that the function was created by the Function function.
6520 // Though it's anonymous, toString should treat it as if it had the name
6521 // "anonymous". We don't set the name itself so that the system does not
6522 // see a binding for it.
6523 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6525 // Indicates whether the function is a bound function created using
6526 // the bind function.
6527 DECL_BOOLEAN_ACCESSORS(bound)
6529 // Indicates that the function is anonymous (the name field can be set
6530 // through the API, which does not change this flag).
6531 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6533 // Is this a function or top-level/eval code.
6534 DECL_BOOLEAN_ACCESSORS(is_function)
6536 // Indicates that code for this function cannot be compiled with Crankshaft.
6537 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6539 // Indicates that code for this function cannot be flushed.
6540 DECL_BOOLEAN_ACCESSORS(dont_flush)
6542 // Indicates that this function is a generator.
6543 DECL_BOOLEAN_ACCESSORS(is_generator)
6545 // Indicates that this function is an arrow function.
6546 DECL_BOOLEAN_ACCESSORS(is_arrow)
6548 // Indicates that this function is a concise method.
6549 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6551 // Indicates that this function is an accessor (getter or setter).
6552 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6554 // Indicates that this function is a default constructor.
6555 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6557 // Indicates that this function is an asm function.
6558 DECL_BOOLEAN_ACCESSORS(asm_function)
6560 // Indicates that the the shared function info is deserialized from cache.
6561 DECL_BOOLEAN_ACCESSORS(deserialized)
6563 // Indicates that the the shared function info has never been compiled before.
6564 DECL_BOOLEAN_ACCESSORS(never_compiled)
6566 inline FunctionKind kind();
6567 inline void set_kind(FunctionKind kind);
6569 // Indicates whether or not the code in the shared function support
6571 inline bool has_deoptimization_support();
6573 // Enable deoptimization support through recompiled code.
6574 void EnableDeoptimizationSupport(Code* recompiled);
6576 // Disable (further) attempted optimization of all functions sharing this
6577 // shared function info.
6578 void DisableOptimization(BailoutReason reason);
6580 inline BailoutReason disable_optimization_reason();
6582 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6583 // code, returns whether it asserted (i.e., always true if assertions are
6585 bool VerifyBailoutId(BailoutId id);
6587 // [source code]: Source code for the function.
6588 bool HasSourceCode() const;
6589 Handle<Object> GetSourceCode();
6591 // Number of times the function was optimized.
6592 inline int opt_count();
6593 inline void set_opt_count(int opt_count);
6595 // Number of times the function was deoptimized.
6596 inline void set_deopt_count(int value);
6597 inline int deopt_count();
6598 inline void increment_deopt_count();
6600 // Number of time we tried to re-enable optimization after it
6601 // was disabled due to high number of deoptimizations.
6602 inline void set_opt_reenable_tries(int value);
6603 inline int opt_reenable_tries();
6605 inline void TryReenableOptimization();
6607 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6608 inline void set_counters(int value);
6609 inline int counters() const;
6611 // Stores opt_count and bailout_reason as bit-fields.
6612 inline void set_opt_count_and_bailout_reason(int value);
6613 inline int opt_count_and_bailout_reason() const;
6615 inline void set_disable_optimization_reason(BailoutReason reason);
6617 // Tells whether this function should be subject to debugging.
6618 inline bool IsSubjectToDebugging();
6620 // Whether this function is defined in native code or extensions.
6621 inline bool IsBuiltin();
6623 // Check whether or not this function is inlineable.
6624 bool IsInlineable();
6626 // Source size of this function.
6629 // Calculate the instance size.
6630 int CalculateInstanceSize();
6632 // Calculate the number of in-object properties.
6633 int CalculateInObjectProperties();
6635 inline bool has_simple_parameters();
6637 // Initialize a SharedFunctionInfo from a parsed function literal.
6638 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6639 FunctionLiteral* lit);
6641 // Dispatched behavior.
6642 DECLARE_PRINTER(SharedFunctionInfo)
6643 DECLARE_VERIFIER(SharedFunctionInfo)
6645 void ResetForNewContext(int new_ic_age);
6647 // Iterate over all shared function infos that are created from a script.
6648 // That excludes shared function infos created for API functions and C++
6652 explicit Iterator(Isolate* isolate);
6653 SharedFunctionInfo* Next();
6658 Script::Iterator script_iterator_;
6659 WeakFixedArray::Iterator sfi_iterator_;
6660 DisallowHeapAllocation no_gc_;
6661 DISALLOW_COPY_AND_ASSIGN(Iterator);
6664 DECLARE_CAST(SharedFunctionInfo)
6667 static const int kDontAdaptArgumentsSentinel = -1;
6669 // Layout description.
6671 static const int kNameOffset = HeapObject::kHeaderSize;
6672 static const int kCodeOffset = kNameOffset + kPointerSize;
6673 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6674 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6675 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6676 static const int kInstanceClassNameOffset =
6677 kConstructStubOffset + kPointerSize;
6678 static const int kFunctionDataOffset =
6679 kInstanceClassNameOffset + kPointerSize;
6680 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6681 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6682 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6683 static const int kFeedbackVectorOffset =
6684 kInferredNameOffset + kPointerSize;
6686 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6687 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6689 // Just to not break the postmortrem support with conditional offsets
6690 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6691 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6694 #if V8_HOST_ARCH_32_BIT
6696 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6697 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6698 static const int kExpectedNofPropertiesOffset =
6699 kFormalParameterCountOffset + kPointerSize;
6700 static const int kNumLiteralsOffset =
6701 kExpectedNofPropertiesOffset + kPointerSize;
6702 static const int kStartPositionAndTypeOffset =
6703 kNumLiteralsOffset + kPointerSize;
6704 static const int kEndPositionOffset =
6705 kStartPositionAndTypeOffset + kPointerSize;
6706 static const int kFunctionTokenPositionOffset =
6707 kEndPositionOffset + kPointerSize;
6708 static const int kCompilerHintsOffset =
6709 kFunctionTokenPositionOffset + kPointerSize;
6710 static const int kOptCountAndBailoutReasonOffset =
6711 kCompilerHintsOffset + kPointerSize;
6712 static const int kCountersOffset =
6713 kOptCountAndBailoutReasonOffset + kPointerSize;
6714 static const int kAstNodeCountOffset =
6715 kCountersOffset + kPointerSize;
6716 static const int kProfilerTicksOffset =
6717 kAstNodeCountOffset + kPointerSize;
6720 static const int kSize = kProfilerTicksOffset + kPointerSize;
6722 // The only reason to use smi fields instead of int fields
6723 // is to allow iteration without maps decoding during
6724 // garbage collections.
6725 // To avoid wasting space on 64-bit architectures we use
6726 // the following trick: we group integer fields into pairs
6727 // The least significant integer in each pair is shifted left by 1.
6728 // By doing this we guarantee that LSB of each kPointerSize aligned
6729 // word is not set and thus this word cannot be treated as pointer
6730 // to HeapObject during old space traversal.
6731 #if V8_TARGET_LITTLE_ENDIAN
6732 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6733 static const int kFormalParameterCountOffset =
6734 kLengthOffset + kIntSize;
6736 static const int kExpectedNofPropertiesOffset =
6737 kFormalParameterCountOffset + kIntSize;
6738 static const int kNumLiteralsOffset =
6739 kExpectedNofPropertiesOffset + kIntSize;
6741 static const int kEndPositionOffset =
6742 kNumLiteralsOffset + kIntSize;
6743 static const int kStartPositionAndTypeOffset =
6744 kEndPositionOffset + kIntSize;
6746 static const int kFunctionTokenPositionOffset =
6747 kStartPositionAndTypeOffset + kIntSize;
6748 static const int kCompilerHintsOffset =
6749 kFunctionTokenPositionOffset + kIntSize;
6751 static const int kOptCountAndBailoutReasonOffset =
6752 kCompilerHintsOffset + kIntSize;
6753 static const int kCountersOffset =
6754 kOptCountAndBailoutReasonOffset + kIntSize;
6756 static const int kAstNodeCountOffset =
6757 kCountersOffset + kIntSize;
6758 static const int kProfilerTicksOffset =
6759 kAstNodeCountOffset + kIntSize;
6762 static const int kSize = kProfilerTicksOffset + kIntSize;
6764 #elif V8_TARGET_BIG_ENDIAN
6765 static const int kFormalParameterCountOffset =
6766 kLastPointerFieldOffset + kPointerSize;
6767 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6769 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6770 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6772 static const int kStartPositionAndTypeOffset =
6773 kExpectedNofPropertiesOffset + kIntSize;
6774 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6776 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6777 static const int kFunctionTokenPositionOffset =
6778 kCompilerHintsOffset + kIntSize;
6780 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6781 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6783 static const int kProfilerTicksOffset =
6784 kOptCountAndBailoutReasonOffset + kIntSize;
6785 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6788 static const int kSize = kAstNodeCountOffset + kIntSize;
6791 #error Unknown byte ordering
6792 #endif // Big endian
6796 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6798 typedef FixedBodyDescriptor<kNameOffset,
6799 kLastPointerFieldOffset + kPointerSize,
6800 kSize> BodyDescriptor;
6802 // Bit positions in start_position_and_type.
6803 // The source code start position is in the 30 most significant bits of
6804 // the start_position_and_type field.
6805 static const int kIsExpressionBit = 0;
6806 static const int kIsTopLevelBit = 1;
6807 static const int kStartPositionShift = 2;
6808 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6810 // Bit positions in compiler_hints.
6811 enum CompilerHints {
6812 kAllowLazyCompilation,
6813 kAllowLazyCompilationWithoutContext,
6814 kOptimizationDisabled,
6816 kStrictModeFunction,
6817 kStrongModeFunction,
6820 kHasDuplicateParameters,
6824 kNameShouldPrintAsAnonymous,
6831 kIsAccessorFunction,
6832 kIsDefaultConstructor,
6833 kIsSubclassConstructor,
6839 kCompilerHintsCount // Pseudo entry
6841 // Add hints for other modes when they're added.
6842 STATIC_ASSERT(LANGUAGE_END == 3);
6844 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6846 class DeoptCountBits : public BitField<int, 0, 4> {};
6847 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6848 class ICAgeBits : public BitField<int, 22, 8> {};
6850 class OptCountBits : public BitField<int, 0, 22> {};
6851 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6854 #if V8_HOST_ARCH_32_BIT
6855 // On 32 bit platforms, compiler hints is a smi.
6856 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6857 static const int kCompilerHintsSize = kPointerSize;
6859 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6860 static const int kCompilerHintsSmiTagSize = 0;
6861 static const int kCompilerHintsSize = kIntSize;
6864 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6865 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6868 // Constants for optimizing codegen for strict mode function and
6870 // Allows to use byte-width instructions.
6871 static const int kStrictModeBitWithinByte =
6872 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6873 static const int kStrongModeBitWithinByte =
6874 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6876 static const int kNativeBitWithinByte =
6877 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6879 static const int kBoundBitWithinByte =
6880 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6882 #if defined(V8_TARGET_LITTLE_ENDIAN)
6883 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6884 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6885 static const int kStrongModeByteOffset =
6886 kCompilerHintsOffset +
6887 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6888 static const int kNativeByteOffset = kCompilerHintsOffset +
6889 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6890 static const int kBoundByteOffset =
6891 kCompilerHintsOffset +
6892 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6893 #elif defined(V8_TARGET_BIG_ENDIAN)
6894 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6895 (kCompilerHintsSize - 1) -
6896 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6897 static const int kStrongModeByteOffset =
6898 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6899 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6900 static const int kNativeByteOffset = kCompilerHintsOffset +
6901 (kCompilerHintsSize - 1) -
6902 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6903 static const int kBoundByteOffset =
6904 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6905 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6907 #error Unknown byte ordering
6911 // Returns entry from optimized code map for specified context and OSR entry.
6912 // The result is either kNotFound, kSharedCodeIndex for context-independent
6913 // entry or a start index of the context-dependent entry.
6914 int SearchOptimizedCodeMapEntry(Context* native_context,
6915 BailoutId osr_ast_id);
6917 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6921 // Printing support.
6922 struct SourceCodeOf {
6923 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6924 : value(v), max_length(max) {}
6925 const SharedFunctionInfo* value;
6930 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6933 class JSGeneratorObject: public JSObject {
6935 // [function]: The function corresponding to this generator object.
6936 DECL_ACCESSORS(function, JSFunction)
6938 // [context]: The context of the suspended computation.
6939 DECL_ACCESSORS(context, Context)
6941 // [receiver]: The receiver of the suspended computation.
6942 DECL_ACCESSORS(receiver, Object)
6944 // [continuation]: Offset into code of continuation.
6946 // A positive offset indicates a suspended generator. The special
6947 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6948 // cannot be resumed.
6949 inline int continuation() const;
6950 inline void set_continuation(int continuation);
6951 inline bool is_closed();
6952 inline bool is_executing();
6953 inline bool is_suspended();
6955 // [operand_stack]: Saved operand stack.
6956 DECL_ACCESSORS(operand_stack, FixedArray)
6958 DECLARE_CAST(JSGeneratorObject)
6960 // Dispatched behavior.
6961 DECLARE_PRINTER(JSGeneratorObject)
6962 DECLARE_VERIFIER(JSGeneratorObject)
6964 // Magic sentinel values for the continuation.
6965 static const int kGeneratorExecuting = -1;
6966 static const int kGeneratorClosed = 0;
6968 // Layout description.
6969 static const int kFunctionOffset = JSObject::kHeaderSize;
6970 static const int kContextOffset = kFunctionOffset + kPointerSize;
6971 static const int kReceiverOffset = kContextOffset + kPointerSize;
6972 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6973 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6974 static const int kSize = kOperandStackOffset + kPointerSize;
6976 // Resume mode, for use by runtime functions.
6977 enum ResumeMode { NEXT, THROW };
6980 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6984 // Representation for module instance objects.
6985 class JSModule: public JSObject {
6987 // [context]: the context holding the module's locals, or undefined if none.
6988 DECL_ACCESSORS(context, Object)
6990 // [scope_info]: Scope info.
6991 DECL_ACCESSORS(scope_info, ScopeInfo)
6993 DECLARE_CAST(JSModule)
6995 // Dispatched behavior.
6996 DECLARE_PRINTER(JSModule)
6997 DECLARE_VERIFIER(JSModule)
6999 // Layout description.
7000 static const int kContextOffset = JSObject::kHeaderSize;
7001 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7002 static const int kSize = kScopeInfoOffset + kPointerSize;
7005 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7009 // JSFunction describes JavaScript functions.
7010 class JSFunction: public JSObject {
7012 // [prototype_or_initial_map]:
7013 DECL_ACCESSORS(prototype_or_initial_map, Object)
7015 // [shared]: The information about the function that
7016 // can be shared by instances.
7017 DECL_ACCESSORS(shared, SharedFunctionInfo)
7019 // [context]: The context for this function.
7020 inline Context* context();
7021 inline void set_context(Object* context);
7022 inline JSObject* global_proxy();
7024 // [code]: The generated code object for this function. Executed
7025 // when the function is invoked, e.g. foo() or new foo(). See
7026 // [[Call]] and [[Construct]] description in ECMA-262, section
7028 inline Code* code();
7029 inline void set_code(Code* code);
7030 inline void set_code_no_write_barrier(Code* code);
7031 inline void ReplaceCode(Code* code);
7033 // Tells whether this function is builtin.
7034 inline bool IsBuiltin();
7036 // Tells whether this function inlines the given shared function info.
7037 bool Inlines(SharedFunctionInfo* candidate);
7039 // Tells whether this function should be subject to debugging.
7040 inline bool IsSubjectToDebugging();
7042 // Tells whether or not the function needs arguments adaption.
7043 inline bool NeedsArgumentsAdaption();
7045 // Tells whether or not this function has been optimized.
7046 inline bool IsOptimized();
7048 // Mark this function for lazy recompilation. The function will be
7049 // recompiled the next time it is executed.
7050 void MarkForOptimization();
7051 void AttemptConcurrentOptimization();
7053 // Tells whether or not the function is already marked for lazy
7055 inline bool IsMarkedForOptimization();
7056 inline bool IsMarkedForConcurrentOptimization();
7058 // Tells whether or not the function is on the concurrent recompilation queue.
7059 inline bool IsInOptimizationQueue();
7061 // Inobject slack tracking is the way to reclaim unused inobject space.
7063 // The instance size is initially determined by adding some slack to
7064 // expected_nof_properties (to allow for a few extra properties added
7065 // after the constructor). There is no guarantee that the extra space
7066 // will not be wasted.
7068 // Here is the algorithm to reclaim the unused inobject space:
7069 // - Detect the first constructor call for this JSFunction.
7070 // When it happens enter the "in progress" state: initialize construction
7071 // counter in the initial_map.
7072 // - While the tracking is in progress create objects filled with
7073 // one_pointer_filler_map instead of undefined_value. This way they can be
7074 // resized quickly and safely.
7075 // - Once enough objects have been created compute the 'slack'
7076 // (traverse the map transition tree starting from the
7077 // initial_map and find the lowest value of unused_property_fields).
7078 // - Traverse the transition tree again and decrease the instance size
7079 // of every map. Existing objects will resize automatically (they are
7080 // filled with one_pointer_filler_map). All further allocations will
7081 // use the adjusted instance size.
7082 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7083 // allocations made using different closures could actually create different
7084 // kind of objects (see prototype inheritance pattern).
7086 // Important: inobject slack tracking is not attempted during the snapshot
7089 // True if the initial_map is set and the object constructions countdown
7090 // counter is not zero.
7091 static const int kGenerousAllocationCount =
7092 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7093 inline bool IsInobjectSlackTrackingInProgress();
7095 // Starts the tracking.
7096 // Initializes object constructions countdown counter in the initial map.
7097 void StartInobjectSlackTracking();
7099 // Completes the tracking.
7100 void CompleteInobjectSlackTracking();
7102 // [literals_or_bindings]: Fixed array holding either
7103 // the materialized literals or the bindings of a bound function.
7105 // If the function contains object, regexp or array literals, the
7106 // literals array prefix contains the object, regexp, and array
7107 // function to be used when creating these literals. This is
7108 // necessary so that we do not dynamically lookup the object, regexp
7109 // or array functions. Performing a dynamic lookup, we might end up
7110 // using the functions from a new context that we should not have
7113 // On bound functions, the array is a (copy-on-write) fixed-array containing
7114 // the function that was bound, bound this-value and any bound
7115 // arguments. Bound functions never contain literals.
7116 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7118 inline FixedArray* literals();
7119 inline void set_literals(FixedArray* literals);
7121 inline FixedArray* function_bindings();
7122 inline void set_function_bindings(FixedArray* bindings);
7124 // The initial map for an object created by this constructor.
7125 inline Map* initial_map();
7126 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7127 Handle<Object> prototype);
7128 inline bool has_initial_map();
7129 static void EnsureHasInitialMap(Handle<JSFunction> function);
7131 // Get and set the prototype property on a JSFunction. If the
7132 // function has an initial map the prototype is set on the initial
7133 // map. Otherwise, the prototype is put in the initial map field
7134 // until an initial map is needed.
7135 inline bool has_prototype();
7136 inline bool has_instance_prototype();
7137 inline Object* prototype();
7138 inline Object* instance_prototype();
7139 static void SetPrototype(Handle<JSFunction> function,
7140 Handle<Object> value);
7141 static void SetInstancePrototype(Handle<JSFunction> function,
7142 Handle<Object> value);
7144 // After prototype is removed, it will not be created when accessed, and
7145 // [[Construct]] from this function will not be allowed.
7146 bool RemovePrototype();
7148 // Accessor for this function's initial map's [[class]]
7149 // property. This is primarily used by ECMA native functions. This
7150 // method sets the class_name field of this function's initial map
7151 // to a given value. It creates an initial map if this function does
7152 // not have one. Note that this method does not copy the initial map
7153 // if it has one already, but simply replaces it with the new value.
7154 // Instances created afterwards will have a map whose [[class]] is
7155 // set to 'value', but there is no guarantees on instances created
7157 void SetInstanceClassName(String* name);
7159 // Returns if this function has been compiled to native code yet.
7160 inline bool is_compiled();
7162 // Returns `false` if formal parameters include rest parameters, optional
7163 // parameters, or destructuring parameters.
7164 // TODO(caitp): make this a flag set during parsing
7165 inline bool has_simple_parameters();
7167 // [next_function_link]: Links functions into various lists, e.g. the list
7168 // of optimized functions hanging off the native_context. The CodeFlusher
7169 // uses this link to chain together flushing candidates. Treated weakly
7170 // by the garbage collector.
7171 DECL_ACCESSORS(next_function_link, Object)
7173 // Prints the name of the function using PrintF.
7174 void PrintName(FILE* out = stdout);
7176 DECLARE_CAST(JSFunction)
7178 // Iterates the objects, including code objects indirectly referenced
7179 // through pointers to the first instruction in the code object.
7180 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7182 // Dispatched behavior.
7183 DECLARE_PRINTER(JSFunction)
7184 DECLARE_VERIFIER(JSFunction)
7186 // Returns the number of allocated literals.
7187 inline int NumberOfLiterals();
7189 // Used for flags such as --hydrogen-filter.
7190 bool PassesFilter(const char* raw_filter);
7192 // The function's name if it is configured, otherwise shared function info
7194 static Handle<String> GetDebugName(Handle<JSFunction> function);
7196 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7197 // kSize) is weak and has special handling during garbage collection.
7198 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7199 static const int kPrototypeOrInitialMapOffset =
7200 kCodeEntryOffset + kPointerSize;
7201 static const int kSharedFunctionInfoOffset =
7202 kPrototypeOrInitialMapOffset + kPointerSize;
7203 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7204 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7205 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7206 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7207 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7209 // Layout of the bound-function binding array.
7210 static const int kBoundFunctionIndex = 0;
7211 static const int kBoundThisIndex = 1;
7212 static const int kBoundArgumentsStartIndex = 2;
7215 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7219 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7220 // and the prototype is hidden. JSGlobalProxy always delegates
7221 // property accesses to its prototype if the prototype is not null.
7223 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7225 // Accessing a JSGlobalProxy requires security check.
7227 class JSGlobalProxy : public JSObject {
7229 // [native_context]: the owner native context of this global proxy object.
7230 // It is null value if this object is not used by any context.
7231 DECL_ACCESSORS(native_context, Object)
7233 // [hash]: The hash code property (undefined if not initialized yet).
7234 DECL_ACCESSORS(hash, Object)
7236 DECLARE_CAST(JSGlobalProxy)
7238 inline bool IsDetachedFrom(GlobalObject* global) const;
7240 // Dispatched behavior.
7241 DECLARE_PRINTER(JSGlobalProxy)
7242 DECLARE_VERIFIER(JSGlobalProxy)
7244 // Layout description.
7245 static const int kNativeContextOffset = JSObject::kHeaderSize;
7246 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7247 static const int kSize = kHashOffset + kPointerSize;
7250 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7254 // Common super class for JavaScript global objects and the special
7255 // builtins global objects.
7256 class GlobalObject: public JSObject {
7258 // [builtins]: the object holding the runtime routines written in JS.
7259 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7261 // [native context]: the natives corresponding to this global object.
7262 DECL_ACCESSORS(native_context, Context)
7264 // [global proxy]: the global proxy object of the context
7265 DECL_ACCESSORS(global_proxy, JSObject)
7267 DECLARE_CAST(GlobalObject)
7269 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7271 // Ensure that the global object has a cell for the given property name.
7272 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7275 // Layout description.
7276 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7277 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7278 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7279 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7282 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7286 // JavaScript global object.
7287 class JSGlobalObject: public GlobalObject {
7289 DECLARE_CAST(JSGlobalObject)
7291 inline bool IsDetached();
7293 // Dispatched behavior.
7294 DECLARE_PRINTER(JSGlobalObject)
7295 DECLARE_VERIFIER(JSGlobalObject)
7297 // Layout description.
7298 static const int kSize = GlobalObject::kHeaderSize;
7301 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7305 // Builtins global object which holds the runtime routines written in
7307 class JSBuiltinsObject: public GlobalObject {
7309 DECLARE_CAST(JSBuiltinsObject)
7311 // Dispatched behavior.
7312 DECLARE_PRINTER(JSBuiltinsObject)
7313 DECLARE_VERIFIER(JSBuiltinsObject)
7315 // Layout description.
7316 static const int kSize = GlobalObject::kHeaderSize;
7319 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7323 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7324 class JSValue: public JSObject {
7326 // [value]: the object being wrapped.
7327 DECL_ACCESSORS(value, Object)
7329 DECLARE_CAST(JSValue)
7331 // Dispatched behavior.
7332 DECLARE_PRINTER(JSValue)
7333 DECLARE_VERIFIER(JSValue)
7335 // Layout description.
7336 static const int kValueOffset = JSObject::kHeaderSize;
7337 static const int kSize = kValueOffset + kPointerSize;
7340 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7346 // Representation for JS date objects.
7347 class JSDate: public JSObject {
7349 // If one component is NaN, all of them are, indicating a NaN time value.
7350 // [value]: the time value.
7351 DECL_ACCESSORS(value, Object)
7352 // [year]: caches year. Either undefined, smi, or NaN.
7353 DECL_ACCESSORS(year, Object)
7354 // [month]: caches month. Either undefined, smi, or NaN.
7355 DECL_ACCESSORS(month, Object)
7356 // [day]: caches day. Either undefined, smi, or NaN.
7357 DECL_ACCESSORS(day, Object)
7358 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7359 DECL_ACCESSORS(weekday, Object)
7360 // [hour]: caches hours. Either undefined, smi, or NaN.
7361 DECL_ACCESSORS(hour, Object)
7362 // [min]: caches minutes. Either undefined, smi, or NaN.
7363 DECL_ACCESSORS(min, Object)
7364 // [sec]: caches seconds. Either undefined, smi, or NaN.
7365 DECL_ACCESSORS(sec, Object)
7366 // [cache stamp]: sample of the date cache stamp at the
7367 // moment when chached fields were cached.
7368 DECL_ACCESSORS(cache_stamp, Object)
7370 DECLARE_CAST(JSDate)
7372 // Returns the date field with the specified index.
7373 // See FieldIndex for the list of date fields.
7374 static Object* GetField(Object* date, Smi* index);
7376 void SetValue(Object* value, bool is_value_nan);
7378 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7379 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7380 Handle<JSReceiver> receiver, Handle<Object> hint);
7382 // Dispatched behavior.
7383 DECLARE_PRINTER(JSDate)
7384 DECLARE_VERIFIER(JSDate)
7386 // The order is important. It must be kept in sync with date macros
7397 kFirstUncachedField,
7398 kMillisecond = kFirstUncachedField,
7402 kYearUTC = kFirstUTCField,
7415 // Layout description.
7416 static const int kValueOffset = JSObject::kHeaderSize;
7417 static const int kYearOffset = kValueOffset + kPointerSize;
7418 static const int kMonthOffset = kYearOffset + kPointerSize;
7419 static const int kDayOffset = kMonthOffset + kPointerSize;
7420 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7421 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7422 static const int kMinOffset = kHourOffset + kPointerSize;
7423 static const int kSecOffset = kMinOffset + kPointerSize;
7424 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7425 static const int kSize = kCacheStampOffset + kPointerSize;
7428 inline Object* DoGetField(FieldIndex index);
7430 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7432 // Computes and caches the cacheable fields of the date.
7433 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7436 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7440 // Representation of message objects used for error reporting through
7441 // the API. The messages are formatted in JavaScript so this object is
7442 // a real JavaScript object. The information used for formatting the
7443 // error messages are not directly accessible from JavaScript to
7444 // prevent leaking information to user code called during error
7446 class JSMessageObject: public JSObject {
7448 // [type]: the type of error message.
7449 inline int type() const;
7450 inline void set_type(int value);
7452 // [arguments]: the arguments for formatting the error message.
7453 DECL_ACCESSORS(argument, Object)
7455 // [script]: the script from which the error message originated.
7456 DECL_ACCESSORS(script, Object)
7458 // [stack_frames]: an array of stack frames for this error object.
7459 DECL_ACCESSORS(stack_frames, Object)
7461 // [start_position]: the start position in the script for the error message.
7462 inline int start_position() const;
7463 inline void set_start_position(int value);
7465 // [end_position]: the end position in the script for the error message.
7466 inline int end_position() const;
7467 inline void set_end_position(int value);
7469 DECLARE_CAST(JSMessageObject)
7471 // Dispatched behavior.
7472 DECLARE_PRINTER(JSMessageObject)
7473 DECLARE_VERIFIER(JSMessageObject)
7475 // Layout description.
7476 static const int kTypeOffset = JSObject::kHeaderSize;
7477 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7478 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7479 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7480 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7481 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7482 static const int kSize = kEndPositionOffset + kPointerSize;
7484 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7485 kStackFramesOffset + kPointerSize,
7486 kSize> BodyDescriptor;
7490 // Regular expressions
7491 // The regular expression holds a single reference to a FixedArray in
7492 // the kDataOffset field.
7493 // The FixedArray contains the following data:
7494 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7495 // - reference to the original source string
7496 // - reference to the original flag string
7497 // If it is an atom regexp
7498 // - a reference to a literal string to search for
7499 // If it is an irregexp regexp:
7500 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7501 // used for tracking the last usage (used for code flushing).
7502 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7503 // used for tracking the last usage (used for code flushing)..
7504 // - max number of registers used by irregexp implementations.
7505 // - number of capture registers (output values) of the regexp.
7506 class JSRegExp: public JSObject {
7509 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7510 // ATOM: A simple string to match against using an indexOf operation.
7511 // IRREGEXP: Compiled with Irregexp.
7512 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7513 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7520 UNICODE_ESCAPES = 16
7525 explicit Flags(uint32_t value) : value_(value) { }
7526 bool is_global() { return (value_ & GLOBAL) != 0; }
7527 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7528 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7529 bool is_sticky() { return (value_ & STICKY) != 0; }
7530 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7531 uint32_t value() { return value_; }
7536 DECL_ACCESSORS(data, Object)
7538 inline Type TypeTag();
7539 inline int CaptureCount();
7540 inline Flags GetFlags();
7541 inline String* Pattern();
7542 inline Object* DataAt(int index);
7543 // Set implementation data after the object has been prepared.
7544 inline void SetDataAt(int index, Object* value);
7546 static int code_index(bool is_latin1) {
7548 return kIrregexpLatin1CodeIndex;
7550 return kIrregexpUC16CodeIndex;
7554 static int saved_code_index(bool is_latin1) {
7556 return kIrregexpLatin1CodeSavedIndex;
7558 return kIrregexpUC16CodeSavedIndex;
7562 DECLARE_CAST(JSRegExp)
7564 // Dispatched behavior.
7565 DECLARE_VERIFIER(JSRegExp)
7567 static const int kDataOffset = JSObject::kHeaderSize;
7568 static const int kSize = kDataOffset + kPointerSize;
7570 // Indices in the data array.
7571 static const int kTagIndex = 0;
7572 static const int kSourceIndex = kTagIndex + 1;
7573 static const int kFlagsIndex = kSourceIndex + 1;
7574 static const int kDataIndex = kFlagsIndex + 1;
7575 // The data fields are used in different ways depending on the
7576 // value of the tag.
7577 // Atom regexps (literal strings).
7578 static const int kAtomPatternIndex = kDataIndex;
7580 static const int kAtomDataSize = kAtomPatternIndex + 1;
7582 // Irregexp compiled code or bytecode for Latin1. If compilation
7583 // fails, this fields hold an exception object that should be
7584 // thrown if the regexp is used again.
7585 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7586 // Irregexp compiled code or bytecode for UC16. If compilation
7587 // fails, this fields hold an exception object that should be
7588 // thrown if the regexp is used again.
7589 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7591 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7592 // is a potential candidate for flushing.
7593 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7594 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7595 // a potential candidate for flushing.
7596 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7598 // Maximal number of registers used by either Latin1 or UC16.
7599 // Only used to check that there is enough stack space
7600 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7601 // Number of captures in the compiled regexp.
7602 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7604 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7606 // Offsets directly into the data fixed array.
7607 static const int kDataTagOffset =
7608 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7609 static const int kDataOneByteCodeOffset =
7610 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7611 static const int kDataUC16CodeOffset =
7612 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7613 static const int kIrregexpCaptureCountOffset =
7614 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7616 // In-object fields.
7617 static const int kSourceFieldIndex = 0;
7618 static const int kGlobalFieldIndex = 1;
7619 static const int kIgnoreCaseFieldIndex = 2;
7620 static const int kMultilineFieldIndex = 3;
7621 static const int kLastIndexFieldIndex = 4;
7622 static const int kInObjectFieldCount = 5;
7624 // The uninitialized value for a regexp code object.
7625 static const int kUninitializedValue = -1;
7627 // The compilation error value for the regexp code object. The real error
7628 // object is in the saved code field.
7629 static const int kCompilationErrorValue = -2;
7631 // When we store the sweep generation at which we moved the code from the
7632 // code index to the saved code index we mask it of to be in the [0:255]
7634 static const int kCodeAgeMask = 0xff;
7638 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7640 static inline bool IsMatch(HashTableKey* key, Object* value) {
7641 return key->IsMatch(value);
7644 static inline uint32_t Hash(HashTableKey* key) {
7648 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7649 return key->HashForObject(object);
7652 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7654 static const int kPrefixSize = 0;
7655 static const int kEntrySize = 2;
7659 // This cache is used in two different variants. For regexp caching, it simply
7660 // maps identifying info of the regexp to the cached regexp object. Scripts and
7661 // eval code only gets cached after a second probe for the code object. To do
7662 // so, on first "put" only a hash identifying the source is entered into the
7663 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7664 // such lifetimes get reduced, and removed once they reach zero. If a second put
7665 // is called while such a hash is live in the cache, the hash gets replaced by
7666 // an actual cache entry. Age also removes stale live entries from the cache.
7667 // Such entries are identified by SharedFunctionInfos pointing to either the
7668 // recompilation stub, or to "old" code. This avoids memory leaks due to
7669 // premature caching of scripts and eval strings that are never needed later.
7670 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7671 CompilationCacheShape,
7674 // Find cached value for a string key, otherwise return null.
7675 Handle<Object> Lookup(
7676 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7677 Handle<Object> LookupEval(
7678 Handle<String> src, Handle<SharedFunctionInfo> shared,
7679 LanguageMode language_mode, int scope_position);
7680 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7681 static Handle<CompilationCacheTable> Put(
7682 Handle<CompilationCacheTable> cache, Handle<String> src,
7683 Handle<Context> context, LanguageMode language_mode,
7684 Handle<Object> value);
7685 static Handle<CompilationCacheTable> PutEval(
7686 Handle<CompilationCacheTable> cache, Handle<String> src,
7687 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7688 int scope_position);
7689 static Handle<CompilationCacheTable> PutRegExp(
7690 Handle<CompilationCacheTable> cache, Handle<String> src,
7691 JSRegExp::Flags flags, Handle<FixedArray> value);
7692 void Remove(Object* value);
7694 static const int kHashGenerations = 10;
7696 DECLARE_CAST(CompilationCacheTable)
7699 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7703 class CodeCache: public Struct {
7705 DECL_ACCESSORS(default_cache, FixedArray)
7706 DECL_ACCESSORS(normal_type_cache, Object)
7708 // Add the code object to the cache.
7710 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7712 // Lookup code object in the cache. Returns code object if found and undefined
7714 Object* Lookup(Name* name, Code::Flags flags);
7716 // Get the internal index of a code object in the cache. Returns -1 if the
7717 // code object is not in that cache. This index can be used to later call
7718 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7720 int GetIndex(Object* name, Code* code);
7722 // Remove an object from the cache with the provided internal index.
7723 void RemoveByIndex(Object* name, Code* code, int index);
7725 DECLARE_CAST(CodeCache)
7727 // Dispatched behavior.
7728 DECLARE_PRINTER(CodeCache)
7729 DECLARE_VERIFIER(CodeCache)
7731 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7732 static const int kNormalTypeCacheOffset =
7733 kDefaultCacheOffset + kPointerSize;
7734 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7737 static void UpdateDefaultCache(
7738 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7739 static void UpdateNormalTypeCache(
7740 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7741 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7742 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7744 // Code cache layout of the default cache. Elements are alternating name and
7745 // code objects for non normal load/store/call IC's.
7746 static const int kCodeCacheEntrySize = 2;
7747 static const int kCodeCacheEntryNameOffset = 0;
7748 static const int kCodeCacheEntryCodeOffset = 1;
7750 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7754 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7756 static inline bool IsMatch(HashTableKey* key, Object* value) {
7757 return key->IsMatch(value);
7760 static inline uint32_t Hash(HashTableKey* key) {
7764 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7765 return key->HashForObject(object);
7768 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7770 static const int kPrefixSize = 0;
7771 static const int kEntrySize = 2;
7775 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7776 CodeCacheHashTableShape,
7779 Object* Lookup(Name* name, Code::Flags flags);
7780 static Handle<CodeCacheHashTable> Put(
7781 Handle<CodeCacheHashTable> table,
7785 int GetIndex(Name* name, Code::Flags flags);
7786 void RemoveByIndex(int index);
7788 DECLARE_CAST(CodeCacheHashTable)
7790 // Initial size of the fixed array backing the hash table.
7791 static const int kInitialSize = 64;
7794 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7798 class PolymorphicCodeCache: public Struct {
7800 DECL_ACCESSORS(cache, Object)
7802 static void Update(Handle<PolymorphicCodeCache> cache,
7803 MapHandleList* maps,
7808 // Returns an undefined value if the entry is not found.
7809 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7811 DECLARE_CAST(PolymorphicCodeCache)
7813 // Dispatched behavior.
7814 DECLARE_PRINTER(PolymorphicCodeCache)
7815 DECLARE_VERIFIER(PolymorphicCodeCache)
7817 static const int kCacheOffset = HeapObject::kHeaderSize;
7818 static const int kSize = kCacheOffset + kPointerSize;
7821 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7825 class PolymorphicCodeCacheHashTable
7826 : public HashTable<PolymorphicCodeCacheHashTable,
7827 CodeCacheHashTableShape,
7830 Object* Lookup(MapHandleList* maps, int code_kind);
7832 static Handle<PolymorphicCodeCacheHashTable> Put(
7833 Handle<PolymorphicCodeCacheHashTable> hash_table,
7834 MapHandleList* maps,
7838 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7840 static const int kInitialSize = 64;
7842 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7846 class TypeFeedbackInfo: public Struct {
7848 inline int ic_total_count();
7849 inline void set_ic_total_count(int count);
7851 inline int ic_with_type_info_count();
7852 inline void change_ic_with_type_info_count(int delta);
7854 inline int ic_generic_count();
7855 inline void change_ic_generic_count(int delta);
7857 inline void initialize_storage();
7859 inline void change_own_type_change_checksum();
7860 inline int own_type_change_checksum();
7862 inline void set_inlined_type_change_checksum(int checksum);
7863 inline bool matches_inlined_type_change_checksum(int checksum);
7865 DECLARE_CAST(TypeFeedbackInfo)
7867 // Dispatched behavior.
7868 DECLARE_PRINTER(TypeFeedbackInfo)
7869 DECLARE_VERIFIER(TypeFeedbackInfo)
7871 static const int kStorage1Offset = HeapObject::kHeaderSize;
7872 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7873 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7874 static const int kSize = kStorage3Offset + kPointerSize;
7877 static const int kTypeChangeChecksumBits = 7;
7879 class ICTotalCountField: public BitField<int, 0,
7880 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7881 class OwnTypeChangeChecksum: public BitField<int,
7882 kSmiValueSize - kTypeChangeChecksumBits,
7883 kTypeChangeChecksumBits> {}; // NOLINT
7884 class ICsWithTypeInfoCountField: public BitField<int, 0,
7885 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7886 class InlinedTypeChangeChecksum: public BitField<int,
7887 kSmiValueSize - kTypeChangeChecksumBits,
7888 kTypeChangeChecksumBits> {}; // NOLINT
7890 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7894 enum AllocationSiteMode {
7895 DONT_TRACK_ALLOCATION_SITE,
7896 TRACK_ALLOCATION_SITE,
7897 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7901 class AllocationSite: public Struct {
7903 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7904 static const double kPretenureRatio;
7905 static const int kPretenureMinimumCreated = 100;
7907 // Values for pretenure decision field.
7908 enum PretenureDecision {
7914 kLastPretenureDecisionValue = kZombie
7917 const char* PretenureDecisionName(PretenureDecision decision);
7919 DECL_ACCESSORS(transition_info, Object)
7920 // nested_site threads a list of sites that represent nested literals
7921 // walked in a particular order. So [[1, 2], 1, 2] will have one
7922 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7923 DECL_ACCESSORS(nested_site, Object)
7924 DECL_ACCESSORS(pretenure_data, Smi)
7925 DECL_ACCESSORS(pretenure_create_count, Smi)
7926 DECL_ACCESSORS(dependent_code, DependentCode)
7927 DECL_ACCESSORS(weak_next, Object)
7929 inline void Initialize();
7931 // This method is expensive, it should only be called for reporting.
7932 bool IsNestedSite();
7934 // transition_info bitfields, for constructed array transition info.
7935 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7936 class UnusedBits: public BitField<int, 15, 14> {};
7937 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7939 // Bitfields for pretenure_data
7940 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7941 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7942 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7943 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7945 // Increments the mementos found counter and returns true when the first
7946 // memento was found for a given allocation site.
7947 inline bool IncrementMementoFoundCount();
7949 inline void IncrementMementoCreateCount();
7951 PretenureFlag GetPretenureMode();
7953 void ResetPretenureDecision();
7955 inline PretenureDecision pretenure_decision();
7956 inline void set_pretenure_decision(PretenureDecision decision);
7958 inline bool deopt_dependent_code();
7959 inline void set_deopt_dependent_code(bool deopt);
7961 inline int memento_found_count();
7962 inline void set_memento_found_count(int count);
7964 inline int memento_create_count();
7965 inline void set_memento_create_count(int count);
7967 // The pretenuring decision is made during gc, and the zombie state allows
7968 // us to recognize when an allocation site is just being kept alive because
7969 // a later traversal of new space may discover AllocationMementos that point
7970 // to this AllocationSite.
7971 inline bool IsZombie();
7973 inline bool IsMaybeTenure();
7975 inline void MarkZombie();
7977 inline bool MakePretenureDecision(PretenureDecision current_decision,
7979 bool maximum_size_scavenge);
7981 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7983 inline ElementsKind GetElementsKind();
7984 inline void SetElementsKind(ElementsKind kind);
7986 inline bool CanInlineCall();
7987 inline void SetDoNotInlineCall();
7989 inline bool SitePointsToLiteral();
7991 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7992 ElementsKind to_kind);
7994 DECLARE_PRINTER(AllocationSite)
7995 DECLARE_VERIFIER(AllocationSite)
7997 DECLARE_CAST(AllocationSite)
7998 static inline AllocationSiteMode GetMode(
7999 ElementsKind boilerplate_elements_kind);
8000 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8001 static inline bool CanTrack(InstanceType type);
8003 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8004 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8005 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8006 static const int kPretenureCreateCountOffset =
8007 kPretenureDataOffset + kPointerSize;
8008 static const int kDependentCodeOffset =
8009 kPretenureCreateCountOffset + kPointerSize;
8010 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8011 static const int kSize = kWeakNextOffset + kPointerSize;
8013 // During mark compact we need to take special care for the dependent code
8015 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8016 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8018 // For other visitors, use the fixed body descriptor below.
8019 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8020 kDependentCodeOffset + kPointerSize,
8021 kSize> BodyDescriptor;
8024 inline bool PretenuringDecisionMade();
8026 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8030 class AllocationMemento: public Struct {
8032 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8033 static const int kSize = kAllocationSiteOffset + kPointerSize;
8035 DECL_ACCESSORS(allocation_site, Object)
8037 inline bool IsValid();
8038 inline AllocationSite* GetAllocationSite();
8040 DECLARE_PRINTER(AllocationMemento)
8041 DECLARE_VERIFIER(AllocationMemento)
8043 DECLARE_CAST(AllocationMemento)
8046 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8050 // Representation of a slow alias as part of a sloppy arguments objects.
8051 // For fast aliases (if HasSloppyArgumentsElements()):
8052 // - the parameter map contains an index into the context
8053 // - all attributes of the element have default values
8054 // For slow aliases (if HasDictionaryArgumentsElements()):
8055 // - the parameter map contains no fast alias mapping (i.e. the hole)
8056 // - this struct (in the slow backing store) contains an index into the context
8057 // - all attributes are available as part if the property details
8058 class AliasedArgumentsEntry: public Struct {
8060 inline int aliased_context_slot() const;
8061 inline void set_aliased_context_slot(int count);
8063 DECLARE_CAST(AliasedArgumentsEntry)
8065 // Dispatched behavior.
8066 DECLARE_PRINTER(AliasedArgumentsEntry)
8067 DECLARE_VERIFIER(AliasedArgumentsEntry)
8069 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8070 static const int kSize = kAliasedContextSlot + kPointerSize;
8073 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8077 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8078 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8081 class StringHasher {
8083 explicit inline StringHasher(int length, uint32_t seed);
8085 template <typename schar>
8086 static inline uint32_t HashSequentialString(const schar* chars,
8090 // Reads all the data, even for long strings and computes the utf16 length.
8091 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8093 int* utf16_length_out);
8095 // Calculated hash value for a string consisting of 1 to
8096 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8097 // value is represented decimal value.
8098 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8100 // No string is allowed to have a hash of zero. That value is reserved
8101 // for internal properties. If the hash calculation yields zero then we
8103 static const int kZeroHash = 27;
8105 // Reusable parts of the hashing algorithm.
8106 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8107 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8108 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8109 const uc16* chars, int length));
8110 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8115 // Returns the value to store in the hash field of a string with
8116 // the given length and contents.
8117 uint32_t GetHashField();
8118 // Returns true if the hash of this string can be computed without
8119 // looking at the contents.
8120 inline bool has_trivial_hash();
8121 // Adds a block of characters to the hash.
8122 template<typename Char>
8123 inline void AddCharacters(const Char* chars, int len);
8126 // Add a character to the hash.
8127 inline void AddCharacter(uint16_t c);
8128 // Update index. Returns true if string is still an index.
8129 inline bool UpdateIndex(uint16_t c);
8132 uint32_t raw_running_hash_;
8133 uint32_t array_index_;
8134 bool is_array_index_;
8135 bool is_first_char_;
8136 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8140 class IteratingStringHasher : public StringHasher {
8142 static inline uint32_t Hash(String* string, uint32_t seed);
8143 inline void VisitOneByteString(const uint8_t* chars, int length);
8144 inline void VisitTwoByteString(const uint16_t* chars, int length);
8147 inline IteratingStringHasher(int len, uint32_t seed);
8148 void VisitConsString(ConsString* cons_string);
8149 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8153 // The characteristics of a string are stored in its map. Retrieving these
8154 // few bits of information is moderately expensive, involving two memory
8155 // loads where the second is dependent on the first. To improve efficiency
8156 // the shape of the string is given its own class so that it can be retrieved
8157 // once and used for several string operations. A StringShape is small enough
8158 // to be passed by value and is immutable, but be aware that flattening a
8159 // string can potentially alter its shape. Also be aware that a GC caused by
8160 // something else can alter the shape of a string due to ConsString
8161 // shortcutting. Keeping these restrictions in mind has proven to be error-
8162 // prone and so we no longer put StringShapes in variables unless there is a
8163 // concrete performance benefit at that particular point in the code.
8164 class StringShape BASE_EMBEDDED {
8166 inline explicit StringShape(const String* s);
8167 inline explicit StringShape(Map* s);
8168 inline explicit StringShape(InstanceType t);
8169 inline bool IsSequential();
8170 inline bool IsExternal();
8171 inline bool IsCons();
8172 inline bool IsSliced();
8173 inline bool IsIndirect();
8174 inline bool IsExternalOneByte();
8175 inline bool IsExternalTwoByte();
8176 inline bool IsSequentialOneByte();
8177 inline bool IsSequentialTwoByte();
8178 inline bool IsInternalized();
8179 inline StringRepresentationTag representation_tag();
8180 inline uint32_t encoding_tag();
8181 inline uint32_t full_representation_tag();
8182 inline uint32_t size_tag();
8184 inline uint32_t type() { return type_; }
8185 inline void invalidate() { valid_ = false; }
8186 inline bool valid() { return valid_; }
8188 inline void invalidate() { }
8194 inline void set_valid() { valid_ = true; }
8197 inline void set_valid() { }
8202 // The Name abstract class captures anything that can be used as a property
8203 // name, i.e., strings and symbols. All names store a hash value.
8204 class Name: public HeapObject {
8206 // Get and set the hash field of the name.
8207 inline uint32_t hash_field();
8208 inline void set_hash_field(uint32_t value);
8210 // Tells whether the hash code has been computed.
8211 inline bool HasHashCode();
8213 // Returns a hash value used for the property table
8214 inline uint32_t Hash();
8216 // Equality operations.
8217 inline bool Equals(Name* other);
8218 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8221 inline bool AsArrayIndex(uint32_t* index);
8223 // If the name is private, it can only name own properties.
8224 inline bool IsPrivate();
8226 // If the name is a non-flat string, this method returns a flat version of the
8227 // string. Otherwise it'll just return the input.
8228 static inline Handle<Name> Flatten(Handle<Name> name,
8229 PretenureFlag pretenure = NOT_TENURED);
8231 // Return a string version of this name that is converted according to the
8232 // rules described in ES6 section 9.2.11.
8233 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8237 DECLARE_PRINTER(Name)
8239 void NameShortPrint();
8240 int NameShortPrint(Vector<char> str);
8243 // Layout description.
8244 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8245 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8246 static const int kHashFieldOffset = kHashFieldSlot;
8248 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8250 static const int kSize = kHashFieldSlot + kPointerSize;
8252 // Mask constant for checking if a name has a computed hash code
8253 // and if it is a string that is an array index. The least significant bit
8254 // indicates whether a hash code has been computed. If the hash code has
8255 // been computed the 2nd bit tells whether the string can be used as an
8257 static const int kHashNotComputedMask = 1;
8258 static const int kIsNotArrayIndexMask = 1 << 1;
8259 static const int kNofHashBitFields = 2;
8261 // Shift constant retrieving hash code from hash field.
8262 static const int kHashShift = kNofHashBitFields;
8264 // Only these bits are relevant in the hash, since the top two are shifted
8266 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8268 // Array index strings this short can keep their index in the hash field.
8269 static const int kMaxCachedArrayIndexLength = 7;
8271 // For strings which are array indexes the hash value has the string length
8272 // mixed into the hash, mainly to avoid a hash value of zero which would be
8273 // the case for the string '0'. 24 bits are used for the array index value.
8274 static const int kArrayIndexValueBits = 24;
8275 static const int kArrayIndexLengthBits =
8276 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8278 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8280 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8281 kArrayIndexValueBits> {}; // NOLINT
8282 class ArrayIndexLengthBits : public BitField<unsigned int,
8283 kNofHashBitFields + kArrayIndexValueBits,
8284 kArrayIndexLengthBits> {}; // NOLINT
8286 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8287 // could use a mask to test if the length of string is less than or equal to
8288 // kMaxCachedArrayIndexLength.
8289 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8291 static const unsigned int kContainsCachedArrayIndexMask =
8292 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8293 << ArrayIndexLengthBits::kShift) |
8294 kIsNotArrayIndexMask;
8296 // Value of empty hash field indicating that the hash is not computed.
8297 static const int kEmptyHashField =
8298 kIsNotArrayIndexMask | kHashNotComputedMask;
8301 static inline bool IsHashFieldComputed(uint32_t field);
8304 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8309 class Symbol: public Name {
8311 // [name]: The print name of a symbol, or undefined if none.
8312 DECL_ACCESSORS(name, Object)
8314 DECL_ACCESSORS(flags, Smi)
8316 // [is_private]: Whether this is a private symbol. Private symbols can only
8317 // be used to designate own properties of objects.
8318 DECL_BOOLEAN_ACCESSORS(is_private)
8320 DECLARE_CAST(Symbol)
8322 // Dispatched behavior.
8323 DECLARE_PRINTER(Symbol)
8324 DECLARE_VERIFIER(Symbol)
8326 // Layout description.
8327 static const int kNameOffset = Name::kSize;
8328 static const int kFlagsOffset = kNameOffset + kPointerSize;
8329 static const int kSize = kFlagsOffset + kPointerSize;
8331 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8333 void SymbolShortPrint(std::ostream& os);
8336 static const int kPrivateBit = 0;
8338 const char* PrivateSymbolToName() const;
8341 friend class Name; // For PrivateSymbolToName.
8344 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8350 // The String abstract class captures JavaScript string values:
8353 // 4.3.16 String Value
8354 // A string value is a member of the type String and is a finite
8355 // ordered sequence of zero or more 16-bit unsigned integer values.
8357 // All string values have a length field.
8358 class String: public Name {
8360 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8362 // Array index strings this short can keep their index in the hash field.
8363 static const int kMaxCachedArrayIndexLength = 7;
8365 // For strings which are array indexes the hash value has the string length
8366 // mixed into the hash, mainly to avoid a hash value of zero which would be
8367 // the case for the string '0'. 24 bits are used for the array index value.
8368 static const int kArrayIndexValueBits = 24;
8369 static const int kArrayIndexLengthBits =
8370 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8372 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8374 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8375 kArrayIndexValueBits> {}; // NOLINT
8376 class ArrayIndexLengthBits : public BitField<unsigned int,
8377 kNofHashBitFields + kArrayIndexValueBits,
8378 kArrayIndexLengthBits> {}; // NOLINT
8380 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8381 // could use a mask to test if the length of string is less than or equal to
8382 // kMaxCachedArrayIndexLength.
8383 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8385 static const unsigned int kContainsCachedArrayIndexMask =
8386 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8387 << ArrayIndexLengthBits::kShift) |
8388 kIsNotArrayIndexMask;
8390 class SubStringRange {
8392 explicit inline SubStringRange(String* string, int first = 0,
8395 inline iterator begin();
8396 inline iterator end();
8404 // Representation of the flat content of a String.
8405 // A non-flat string doesn't have flat content.
8406 // A flat string has content that's encoded as a sequence of either
8407 // one-byte chars or two-byte UC16.
8408 // Returned by String::GetFlatContent().
8411 // Returns true if the string is flat and this structure contains content.
8412 bool IsFlat() { return state_ != NON_FLAT; }
8413 // Returns true if the structure contains one-byte content.
8414 bool IsOneByte() { return state_ == ONE_BYTE; }
8415 // Returns true if the structure contains two-byte content.
8416 bool IsTwoByte() { return state_ == TWO_BYTE; }
8418 // Return the one byte content of the string. Only use if IsOneByte()
8420 Vector<const uint8_t> ToOneByteVector() {
8421 DCHECK_EQ(ONE_BYTE, state_);
8422 return Vector<const uint8_t>(onebyte_start, length_);
8424 // Return the two-byte content of the string. Only use if IsTwoByte()
8426 Vector<const uc16> ToUC16Vector() {
8427 DCHECK_EQ(TWO_BYTE, state_);
8428 return Vector<const uc16>(twobyte_start, length_);
8432 DCHECK(i < length_);
8433 DCHECK(state_ != NON_FLAT);
8434 if (state_ == ONE_BYTE) return onebyte_start[i];
8435 return twobyte_start[i];
8438 bool UsesSameString(const FlatContent& other) const {
8439 return onebyte_start == other.onebyte_start;
8443 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8445 // Constructors only used by String::GetFlatContent().
8446 explicit FlatContent(const uint8_t* start, int length)
8447 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8448 explicit FlatContent(const uc16* start, int length)
8449 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8450 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8453 const uint8_t* onebyte_start;
8454 const uc16* twobyte_start;
8459 friend class String;
8460 friend class IterableSubString;
8463 template <typename Char>
8464 INLINE(Vector<const Char> GetCharVector());
8466 // Get and set the length of the string.
8467 inline int length() const;
8468 inline void set_length(int value);
8470 // Get and set the length of the string using acquire loads and release
8472 inline int synchronized_length() const;
8473 inline void synchronized_set_length(int value);
8475 // Returns whether this string has only one-byte chars, i.e. all of them can
8476 // be one-byte encoded. This might be the case even if the string is
8477 // two-byte. Such strings may appear when the embedder prefers
8478 // two-byte external representations even for one-byte data.
8479 inline bool IsOneByteRepresentation() const;
8480 inline bool IsTwoByteRepresentation() const;
8482 // Cons and slices have an encoding flag that may not represent the actual
8483 // encoding of the underlying string. This is taken into account here.
8484 // Requires: this->IsFlat()
8485 inline bool IsOneByteRepresentationUnderneath();
8486 inline bool IsTwoByteRepresentationUnderneath();
8488 // NOTE: this should be considered only a hint. False negatives are
8490 inline bool HasOnlyOneByteChars();
8492 // Get and set individual two byte chars in the string.
8493 inline void Set(int index, uint16_t value);
8494 // Get individual two byte char in the string. Repeated calls
8495 // to this method are not efficient unless the string is flat.
8496 INLINE(uint16_t Get(int index));
8498 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8499 static Handle<Object> ToNumber(Handle<String> subject);
8501 // Flattens the string. Checks first inline to see if it is
8502 // necessary. Does nothing if the string is not a cons string.
8503 // Flattening allocates a sequential string with the same data as
8504 // the given string and mutates the cons string to a degenerate
8505 // form, where the first component is the new sequential string and
8506 // the second component is the empty string. If allocation fails,
8507 // this function returns a failure. If flattening succeeds, this
8508 // function returns the sequential string that is now the first
8509 // component of the cons string.
8511 // Degenerate cons strings are handled specially by the garbage
8512 // collector (see IsShortcutCandidate).
8514 static inline Handle<String> Flatten(Handle<String> string,
8515 PretenureFlag pretenure = NOT_TENURED);
8517 // Tries to return the content of a flat string as a structure holding either
8518 // a flat vector of char or of uc16.
8519 // If the string isn't flat, and therefore doesn't have flat content, the
8520 // returned structure will report so, and can't provide a vector of either
8522 FlatContent GetFlatContent();
8524 // Returns the parent of a sliced string or first part of a flat cons string.
8525 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8526 inline String* GetUnderlying();
8528 // String relational comparison, implemented according to ES6 section 7.2.11
8529 // Abstract Relational Comparison (step 5): The comparison of Strings uses a
8530 // simple lexicographic ordering on sequences of code unit values. There is no
8531 // attempt to use the more complex, semantically oriented definitions of
8532 // character or string equality and collating order defined in the Unicode
8533 // specification. Therefore String values that are canonically equal according
8534 // to the Unicode standard could test as unequal. In effect this algorithm
8535 // assumes that both Strings are already in normalized form. Also, note that
8536 // for strings containing supplementary characters, lexicographic ordering on
8537 // sequences of UTF-16 code unit values differs from that on sequences of code
8539 MUST_USE_RESULT static ComparisonResult Compare(Handle<String> x,
8542 // String equality operations.
8543 inline bool Equals(String* other);
8544 inline static bool Equals(Handle<String> one, Handle<String> two);
8545 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8546 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8547 bool IsTwoByteEqualTo(Vector<const uc16> str);
8549 // Return a UTF8 representation of the string. The string is null
8550 // terminated but may optionally contain nulls. Length is returned
8551 // in length_output if length_output is not a null pointer The string
8552 // should be nearly flat, otherwise the performance of this method may
8553 // be very slow (quadratic in the length). Setting robustness_flag to
8554 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8555 // handles unexpected data without causing assert failures and it does not
8556 // do any heap allocations. This is useful when printing stack traces.
8557 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8558 RobustnessFlag robustness_flag,
8559 int offset, int length,
8560 int* length_output = 0);
8561 base::SmartArrayPointer<char> ToCString(
8562 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8563 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8564 int* length_output = 0);
8566 // Return a 16 bit Unicode representation of the string.
8567 // The string should be nearly flat, otherwise the performance of
8568 // of this method may be very bad. Setting robustness_flag to
8569 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8570 // handles unexpected data without causing assert failures and it does not
8571 // do any heap allocations. This is useful when printing stack traces.
8572 base::SmartArrayPointer<uc16> ToWideCString(
8573 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8575 bool ComputeArrayIndex(uint32_t* index);
8578 bool MakeExternal(v8::String::ExternalStringResource* resource);
8579 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8582 inline bool AsArrayIndex(uint32_t* index);
8584 DECLARE_CAST(String)
8586 void PrintOn(FILE* out);
8588 // For use during stack traces. Performs rudimentary sanity check.
8591 // Dispatched behavior.
8592 void StringShortPrint(StringStream* accumulator);
8593 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8594 #if defined(DEBUG) || defined(OBJECT_PRINT)
8595 char* ToAsciiArray();
8597 DECLARE_PRINTER(String)
8598 DECLARE_VERIFIER(String)
8600 inline bool IsFlat();
8602 // Layout description.
8603 static const int kLengthOffset = Name::kSize;
8604 static const int kSize = kLengthOffset + kPointerSize;
8606 // Maximum number of characters to consider when trying to convert a string
8607 // value into an array index.
8608 static const int kMaxArrayIndexSize = 10;
8609 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8612 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8613 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8614 static const int kMaxUtf16CodeUnit = 0xffff;
8615 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8617 // Value of hash field containing computed hash equal to zero.
8618 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8620 // Maximal string length.
8621 static const int kMaxLength = (1 << 28) - 16;
8623 // Max length for computing hash. For strings longer than this limit the
8624 // string length is used as the hash value.
8625 static const int kMaxHashCalcLength = 16383;
8627 // Limit for truncation in short printing.
8628 static const int kMaxShortPrintLength = 1024;
8630 // Support for regular expressions.
8631 const uc16* GetTwoByteData(unsigned start);
8633 // Helper function for flattening strings.
8634 template <typename sinkchar>
8635 static void WriteToFlat(String* source,
8640 // The return value may point to the first aligned word containing the first
8641 // non-one-byte character, rather than directly to the non-one-byte character.
8642 // If the return value is >= the passed length, the entire string was
8644 static inline int NonAsciiStart(const char* chars, int length) {
8645 const char* start = chars;
8646 const char* limit = chars + length;
8648 if (length >= kIntptrSize) {
8649 // Check unaligned bytes.
8650 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8651 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8652 return static_cast<int>(chars - start);
8656 // Check aligned words.
8657 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8658 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8659 while (chars + sizeof(uintptr_t) <= limit) {
8660 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8661 return static_cast<int>(chars - start);
8663 chars += sizeof(uintptr_t);
8666 // Check remaining unaligned bytes.
8667 while (chars < limit) {
8668 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8669 return static_cast<int>(chars - start);
8674 return static_cast<int>(chars - start);
8677 static inline bool IsAscii(const char* chars, int length) {
8678 return NonAsciiStart(chars, length) >= length;
8681 static inline bool IsAscii(const uint8_t* chars, int length) {
8683 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8686 static inline int NonOneByteStart(const uc16* chars, int length) {
8687 const uc16* limit = chars + length;
8688 const uc16* start = chars;
8689 while (chars < limit) {
8690 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8693 return static_cast<int>(chars - start);
8696 static inline bool IsOneByte(const uc16* chars, int length) {
8697 return NonOneByteStart(chars, length) >= length;
8700 template<class Visitor>
8701 static inline ConsString* VisitFlat(Visitor* visitor,
8705 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8706 bool include_ending_line);
8708 // Use the hash field to forward to the canonical internalized string
8709 // when deserializing an internalized string.
8710 inline void SetForwardedInternalizedString(String* string);
8711 inline String* GetForwardedInternalizedString();
8715 friend class StringTableInsertionKey;
8717 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8718 PretenureFlag tenure);
8720 // Slow case of String::Equals. This implementation works on any strings
8721 // but it is most efficient on strings that are almost flat.
8722 bool SlowEquals(String* other);
8724 static bool SlowEquals(Handle<String> one, Handle<String> two);
8726 // Slow case of AsArrayIndex.
8727 bool SlowAsArrayIndex(uint32_t* index);
8729 // Compute and set the hash code.
8730 uint32_t ComputeAndSetHash();
8732 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8736 // The SeqString abstract class captures sequential string values.
8737 class SeqString: public String {
8739 DECLARE_CAST(SeqString)
8741 // Layout description.
8742 static const int kHeaderSize = String::kSize;
8744 // Truncate the string in-place if possible and return the result.
8745 // In case of new_length == 0, the empty string is returned without
8746 // truncating the original string.
8747 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8750 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8754 // The OneByteString class captures sequential one-byte string objects.
8755 // Each character in the OneByteString is an one-byte character.
8756 class SeqOneByteString: public SeqString {
8758 static const bool kHasOneByteEncoding = true;
8760 // Dispatched behavior.
8761 inline uint16_t SeqOneByteStringGet(int index);
8762 inline void SeqOneByteStringSet(int index, uint16_t value);
8764 // Get the address of the characters in this string.
8765 inline Address GetCharsAddress();
8767 inline uint8_t* GetChars();
8769 DECLARE_CAST(SeqOneByteString)
8771 // Garbage collection support. This method is called by the
8772 // garbage collector to compute the actual size of an OneByteString
8774 inline int SeqOneByteStringSize(InstanceType instance_type);
8776 // Computes the size for an OneByteString instance of a given length.
8777 static int SizeFor(int length) {
8778 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8781 // Maximal memory usage for a single sequential one-byte string.
8782 static const int kMaxSize = 512 * MB - 1;
8783 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8786 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8790 // The TwoByteString class captures sequential unicode string objects.
8791 // Each character in the TwoByteString is a two-byte uint16_t.
8792 class SeqTwoByteString: public SeqString {
8794 static const bool kHasOneByteEncoding = false;
8796 // Dispatched behavior.
8797 inline uint16_t SeqTwoByteStringGet(int index);
8798 inline void SeqTwoByteStringSet(int index, uint16_t value);
8800 // Get the address of the characters in this string.
8801 inline Address GetCharsAddress();
8803 inline uc16* GetChars();
8806 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8808 DECLARE_CAST(SeqTwoByteString)
8810 // Garbage collection support. This method is called by the
8811 // garbage collector to compute the actual size of a TwoByteString
8813 inline int SeqTwoByteStringSize(InstanceType instance_type);
8815 // Computes the size for a TwoByteString instance of a given length.
8816 static int SizeFor(int length) {
8817 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8820 // Maximal memory usage for a single sequential two-byte string.
8821 static const int kMaxSize = 512 * MB - 1;
8822 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8823 String::kMaxLength);
8826 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8830 // The ConsString class describes string values built by using the
8831 // addition operator on strings. A ConsString is a pair where the
8832 // first and second components are pointers to other string values.
8833 // One or both components of a ConsString can be pointers to other
8834 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8835 // are non-ConsString string values. The string value represented by
8836 // a ConsString can be obtained by concatenating the leaf string
8837 // values in a left-to-right depth-first traversal of the tree.
8838 class ConsString: public String {
8840 // First string of the cons cell.
8841 inline String* first();
8842 // Doesn't check that the result is a string, even in debug mode. This is
8843 // useful during GC where the mark bits confuse the checks.
8844 inline Object* unchecked_first();
8845 inline void set_first(String* first,
8846 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8848 // Second string of the cons cell.
8849 inline String* second();
8850 // Doesn't check that the result is a string, even in debug mode. This is
8851 // useful during GC where the mark bits confuse the checks.
8852 inline Object* unchecked_second();
8853 inline void set_second(String* second,
8854 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8856 // Dispatched behavior.
8857 uint16_t ConsStringGet(int index);
8859 DECLARE_CAST(ConsString)
8861 // Layout description.
8862 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8863 static const int kSecondOffset = kFirstOffset + kPointerSize;
8864 static const int kSize = kSecondOffset + kPointerSize;
8866 // Minimum length for a cons string.
8867 static const int kMinLength = 13;
8869 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8872 DECLARE_VERIFIER(ConsString)
8875 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8879 // The Sliced String class describes strings that are substrings of another
8880 // sequential string. The motivation is to save time and memory when creating
8881 // a substring. A Sliced String is described as a pointer to the parent,
8882 // the offset from the start of the parent string and the length. Using
8883 // a Sliced String therefore requires unpacking of the parent string and
8884 // adding the offset to the start address. A substring of a Sliced String
8885 // are not nested since the double indirection is simplified when creating
8886 // such a substring.
8887 // Currently missing features are:
8888 // - handling externalized parent strings
8889 // - external strings as parent
8890 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8891 class SlicedString: public String {
8893 inline String* parent();
8894 inline void set_parent(String* parent,
8895 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8896 inline int offset() const;
8897 inline void set_offset(int offset);
8899 // Dispatched behavior.
8900 uint16_t SlicedStringGet(int index);
8902 DECLARE_CAST(SlicedString)
8904 // Layout description.
8905 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8906 static const int kOffsetOffset = kParentOffset + kPointerSize;
8907 static const int kSize = kOffsetOffset + kPointerSize;
8909 // Minimum length for a sliced string.
8910 static const int kMinLength = 13;
8912 typedef FixedBodyDescriptor<kParentOffset,
8913 kOffsetOffset + kPointerSize, kSize>
8916 DECLARE_VERIFIER(SlicedString)
8919 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8923 // The ExternalString class describes string values that are backed by
8924 // a string resource that lies outside the V8 heap. ExternalStrings
8925 // consist of the length field common to all strings, a pointer to the
8926 // external resource. It is important to ensure (externally) that the
8927 // resource is not deallocated while the ExternalString is live in the
8930 // The API expects that all ExternalStrings are created through the
8931 // API. Therefore, ExternalStrings should not be used internally.
8932 class ExternalString: public String {
8934 DECLARE_CAST(ExternalString)
8936 // Layout description.
8937 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8938 static const int kShortSize = kResourceOffset + kPointerSize;
8939 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8940 static const int kSize = kResourceDataOffset + kPointerSize;
8942 static const int kMaxShortLength =
8943 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8945 // Return whether external string is short (data pointer is not cached).
8946 inline bool is_short();
8948 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8951 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8955 // The ExternalOneByteString class is an external string backed by an
8957 class ExternalOneByteString : public ExternalString {
8959 static const bool kHasOneByteEncoding = true;
8961 typedef v8::String::ExternalOneByteStringResource Resource;
8963 // The underlying resource.
8964 inline const Resource* resource();
8965 inline void set_resource(const Resource* buffer);
8967 // Update the pointer cache to the external character array.
8968 // The cached pointer is always valid, as the external character array does =
8969 // not move during lifetime. Deserialization is the only exception, after
8970 // which the pointer cache has to be refreshed.
8971 inline void update_data_cache();
8973 inline const uint8_t* GetChars();
8975 // Dispatched behavior.
8976 inline uint16_t ExternalOneByteStringGet(int index);
8978 DECLARE_CAST(ExternalOneByteString)
8980 // Garbage collection support.
8981 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8983 template <typename StaticVisitor>
8984 inline void ExternalOneByteStringIterateBody();
8987 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8991 // The ExternalTwoByteString class is an external string backed by a UTF-16
8993 class ExternalTwoByteString: public ExternalString {
8995 static const bool kHasOneByteEncoding = false;
8997 typedef v8::String::ExternalStringResource Resource;
8999 // The underlying string resource.
9000 inline const Resource* resource();
9001 inline void set_resource(const Resource* buffer);
9003 // Update the pointer cache to the external character array.
9004 // The cached pointer is always valid, as the external character array does =
9005 // not move during lifetime. Deserialization is the only exception, after
9006 // which the pointer cache has to be refreshed.
9007 inline void update_data_cache();
9009 inline const uint16_t* GetChars();
9011 // Dispatched behavior.
9012 inline uint16_t ExternalTwoByteStringGet(int index);
9015 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9017 DECLARE_CAST(ExternalTwoByteString)
9019 // Garbage collection support.
9020 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9022 template<typename StaticVisitor>
9023 inline void ExternalTwoByteStringIterateBody();
9026 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9030 // Utility superclass for stack-allocated objects that must be updated
9031 // on gc. It provides two ways for the gc to update instances, either
9032 // iterating or updating after gc.
9033 class Relocatable BASE_EMBEDDED {
9035 explicit inline Relocatable(Isolate* isolate);
9036 inline virtual ~Relocatable();
9037 virtual void IterateInstance(ObjectVisitor* v) { }
9038 virtual void PostGarbageCollection() { }
9040 static void PostGarbageCollectionProcessing(Isolate* isolate);
9041 static int ArchiveSpacePerThread();
9042 static char* ArchiveState(Isolate* isolate, char* to);
9043 static char* RestoreState(Isolate* isolate, char* from);
9044 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9045 static void Iterate(ObjectVisitor* v, Relocatable* top);
9046 static char* Iterate(ObjectVisitor* v, char* t);
9054 // A flat string reader provides random access to the contents of a
9055 // string independent of the character width of the string. The handle
9056 // must be valid as long as the reader is being used.
9057 class FlatStringReader : public Relocatable {
9059 FlatStringReader(Isolate* isolate, Handle<String> str);
9060 FlatStringReader(Isolate* isolate, Vector<const char> input);
9061 void PostGarbageCollection();
9062 inline uc32 Get(int index);
9063 template <typename Char>
9064 inline Char Get(int index);
9065 int length() { return length_; }
9074 // This maintains an off-stack representation of the stack frames required
9075 // to traverse a ConsString, allowing an entirely iterative and restartable
9076 // traversal of the entire string
9077 class ConsStringIterator {
9079 inline ConsStringIterator() {}
9080 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9081 Reset(cons_string, offset);
9083 inline void Reset(ConsString* cons_string, int offset = 0) {
9085 // Next will always return NULL.
9086 if (cons_string == NULL) return;
9087 Initialize(cons_string, offset);
9089 // Returns NULL when complete.
9090 inline String* Next(int* offset_out) {
9092 if (depth_ == 0) return NULL;
9093 return Continue(offset_out);
9097 static const int kStackSize = 32;
9098 // Use a mask instead of doing modulo operations for stack wrapping.
9099 static const int kDepthMask = kStackSize-1;
9100 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9101 static inline int OffsetForDepth(int depth);
9103 inline void PushLeft(ConsString* string);
9104 inline void PushRight(ConsString* string);
9105 inline void AdjustMaximumDepth();
9107 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9108 void Initialize(ConsString* cons_string, int offset);
9109 String* Continue(int* offset_out);
9110 String* NextLeaf(bool* blew_stack);
9111 String* Search(int* offset_out);
9113 // Stack must always contain only frames for which right traversal
9114 // has not yet been performed.
9115 ConsString* frames_[kStackSize];
9120 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9124 class StringCharacterStream {
9126 inline StringCharacterStream(String* string,
9128 inline uint16_t GetNext();
9129 inline bool HasMore();
9130 inline void Reset(String* string, int offset = 0);
9131 inline void VisitOneByteString(const uint8_t* chars, int length);
9132 inline void VisitTwoByteString(const uint16_t* chars, int length);
9135 ConsStringIterator iter_;
9138 const uint8_t* buffer8_;
9139 const uint16_t* buffer16_;
9141 const uint8_t* end_;
9142 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9146 template <typename T>
9147 class VectorIterator {
9149 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9150 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9151 T GetNext() { return data_[index_++]; }
9152 bool has_more() { return index_ < data_.length(); }
9154 Vector<const T> data_;
9159 // The Oddball describes objects null, undefined, true, and false.
9160 class Oddball: public HeapObject {
9162 // [to_string]: Cached to_string computed at startup.
9163 DECL_ACCESSORS(to_string, String)
9165 // [to_number]: Cached to_number computed at startup.
9166 DECL_ACCESSORS(to_number, Object)
9168 // [typeof]: Cached type_of computed at startup.
9169 DECL_ACCESSORS(type_of, String)
9171 inline byte kind() const;
9172 inline void set_kind(byte kind);
9174 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9175 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9177 DECLARE_CAST(Oddball)
9179 // Dispatched behavior.
9180 DECLARE_VERIFIER(Oddball)
9182 // Initialize the fields.
9183 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9184 const char* to_string, Handle<Object> to_number,
9185 const char* type_of, byte kind);
9187 // Layout description.
9188 static const int kToStringOffset = HeapObject::kHeaderSize;
9189 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9190 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9191 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9192 static const int kSize = kKindOffset + kPointerSize;
9194 static const byte kFalse = 0;
9195 static const byte kTrue = 1;
9196 static const byte kNotBooleanMask = ~1;
9197 static const byte kTheHole = 2;
9198 static const byte kNull = 3;
9199 static const byte kArgumentMarker = 4;
9200 static const byte kUndefined = 5;
9201 static const byte kUninitialized = 6;
9202 static const byte kOther = 7;
9203 static const byte kException = 8;
9205 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9206 kSize> BodyDescriptor;
9208 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9209 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9210 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9213 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9217 class Cell: public HeapObject {
9219 // [value]: value of the cell.
9220 DECL_ACCESSORS(value, Object)
9224 static inline Cell* FromValueAddress(Address value) {
9225 Object* result = FromAddress(value - kValueOffset);
9226 return static_cast<Cell*>(result);
9229 inline Address ValueAddress() {
9230 return address() + kValueOffset;
9233 // Dispatched behavior.
9234 DECLARE_PRINTER(Cell)
9235 DECLARE_VERIFIER(Cell)
9237 // Layout description.
9238 static const int kValueOffset = HeapObject::kHeaderSize;
9239 static const int kSize = kValueOffset + kPointerSize;
9241 typedef FixedBodyDescriptor<kValueOffset,
9242 kValueOffset + kPointerSize,
9243 kSize> BodyDescriptor;
9246 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9250 class PropertyCell : public HeapObject {
9252 // [property_details]: details of the global property.
9253 DECL_ACCESSORS(property_details_raw, Object)
9254 // [value]: value of the global property.
9255 DECL_ACCESSORS(value, Object)
9256 // [dependent_code]: dependent code that depends on the type of the global
9258 DECL_ACCESSORS(dependent_code, DependentCode)
9260 inline PropertyDetails property_details();
9261 inline void set_property_details(PropertyDetails details);
9263 PropertyCellConstantType GetConstantType();
9265 // Computes the new type of the cell's contents for the given value, but
9266 // without actually modifying the details.
9267 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9268 Handle<Object> value,
9269 PropertyDetails details);
9270 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9271 Handle<Object> value, PropertyDetails details);
9273 static Handle<PropertyCell> InvalidateEntry(
9274 Handle<GlobalDictionary> dictionary, int entry);
9276 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9277 Handle<Object> new_value);
9279 DECLARE_CAST(PropertyCell)
9281 // Dispatched behavior.
9282 DECLARE_PRINTER(PropertyCell)
9283 DECLARE_VERIFIER(PropertyCell)
9285 // Layout description.
9286 static const int kDetailsOffset = HeapObject::kHeaderSize;
9287 static const int kValueOffset = kDetailsOffset + kPointerSize;
9288 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9289 static const int kSize = kDependentCodeOffset + kPointerSize;
9291 static const int kPointerFieldsBeginOffset = kValueOffset;
9292 static const int kPointerFieldsEndOffset = kSize;
9294 typedef FixedBodyDescriptor<kValueOffset,
9296 kSize> BodyDescriptor;
9299 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9303 class WeakCell : public HeapObject {
9305 inline Object* value() const;
9307 // This should not be called by anyone except GC.
9308 inline void clear();
9310 // This should not be called by anyone except allocator.
9311 inline void initialize(HeapObject* value);
9313 inline bool cleared() const;
9315 DECL_ACCESSORS(next, Object)
9317 inline void clear_next(Heap* heap);
9319 inline bool next_cleared();
9321 DECLARE_CAST(WeakCell)
9323 DECLARE_PRINTER(WeakCell)
9324 DECLARE_VERIFIER(WeakCell)
9326 // Layout description.
9327 static const int kValueOffset = HeapObject::kHeaderSize;
9328 static const int kNextOffset = kValueOffset + kPointerSize;
9329 static const int kSize = kNextOffset + kPointerSize;
9331 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9334 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9338 // The JSProxy describes EcmaScript Harmony proxies
9339 class JSProxy: public JSReceiver {
9341 // [handler]: The handler property.
9342 DECL_ACCESSORS(handler, Object)
9344 // [hash]: The hash code property (undefined if not initialized yet).
9345 DECL_ACCESSORS(hash, Object)
9347 DECLARE_CAST(JSProxy)
9349 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9350 Handle<JSProxy> proxy,
9351 Handle<Object> receiver,
9354 // If the handler defines an accessor property with a setter, invoke it.
9355 // If it defines an accessor property without a setter, or a data property
9356 // that is read-only, throw. In all these cases set '*done' to true,
9357 // otherwise set it to false.
9359 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9360 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9361 Handle<Object> value, LanguageMode language_mode, bool* done);
9363 MUST_USE_RESULT static Maybe<PropertyAttributes>
9364 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9365 Handle<Object> receiver,
9367 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9368 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9369 Handle<Object> value, LanguageMode language_mode);
9371 // Turn the proxy into an (empty) JSObject.
9372 static void Fix(Handle<JSProxy> proxy);
9374 // Initializes the body after the handler slot.
9375 inline void InitializeBody(int object_size, Object* value);
9377 // Invoke a trap by name. If the trap does not exist on this's handler,
9378 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9379 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9380 Handle<JSProxy> proxy,
9382 Handle<Object> derived_trap,
9384 Handle<Object> args[]);
9386 // Dispatched behavior.
9387 DECLARE_PRINTER(JSProxy)
9388 DECLARE_VERIFIER(JSProxy)
9390 // Layout description. We add padding so that a proxy has the same
9391 // size as a virgin JSObject. This is essential for becoming a JSObject
9393 static const int kHandlerOffset = HeapObject::kHeaderSize;
9394 static const int kHashOffset = kHandlerOffset + kPointerSize;
9395 static const int kPaddingOffset = kHashOffset + kPointerSize;
9396 static const int kSize = JSObject::kHeaderSize;
9397 static const int kHeaderSize = kPaddingOffset;
9398 static const int kPaddingSize = kSize - kPaddingOffset;
9400 STATIC_ASSERT(kPaddingSize >= 0);
9402 typedef FixedBodyDescriptor<kHandlerOffset,
9404 kSize> BodyDescriptor;
9407 friend class JSReceiver;
9409 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9410 Handle<JSProxy> proxy, Handle<Name> name);
9412 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9413 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9415 MUST_USE_RESULT Object* GetIdentityHash();
9417 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9419 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9423 class JSFunctionProxy: public JSProxy {
9425 // [call_trap]: The call trap.
9426 DECL_ACCESSORS(call_trap, JSReceiver)
9428 // [construct_trap]: The construct trap.
9429 DECL_ACCESSORS(construct_trap, Object)
9431 DECLARE_CAST(JSFunctionProxy)
9433 // Dispatched behavior.
9434 DECLARE_PRINTER(JSFunctionProxy)
9435 DECLARE_VERIFIER(JSFunctionProxy)
9437 // Layout description.
9438 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9439 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9440 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9441 static const int kSize = JSFunction::kSize;
9442 static const int kPaddingSize = kSize - kPaddingOffset;
9444 STATIC_ASSERT(kPaddingSize >= 0);
9446 typedef FixedBodyDescriptor<kHandlerOffset,
9447 kConstructTrapOffset + kPointerSize,
9448 kSize> BodyDescriptor;
9451 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9455 class JSCollection : public JSObject {
9457 // [table]: the backing hash table
9458 DECL_ACCESSORS(table, Object)
9460 static const int kTableOffset = JSObject::kHeaderSize;
9461 static const int kSize = kTableOffset + kPointerSize;
9464 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9468 // The JSSet describes EcmaScript Harmony sets
9469 class JSSet : public JSCollection {
9473 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9474 static void Clear(Handle<JSSet> set);
9476 // Dispatched behavior.
9477 DECLARE_PRINTER(JSSet)
9478 DECLARE_VERIFIER(JSSet)
9481 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9485 // The JSMap describes EcmaScript Harmony maps
9486 class JSMap : public JSCollection {
9490 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9491 static void Clear(Handle<JSMap> map);
9493 // Dispatched behavior.
9494 DECLARE_PRINTER(JSMap)
9495 DECLARE_VERIFIER(JSMap)
9498 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9502 // OrderedHashTableIterator is an iterator that iterates over the keys and
9503 // values of an OrderedHashTable.
9505 // The iterator has a reference to the underlying OrderedHashTable data,
9506 // [table], as well as the current [index] the iterator is at.
9508 // When the OrderedHashTable is rehashed it adds a reference from the old table
9509 // to the new table as well as storing enough data about the changes so that the
9510 // iterator [index] can be adjusted accordingly.
9512 // When the [Next] result from the iterator is requested, the iterator checks if
9513 // there is a newer table that it needs to transition to.
9514 template<class Derived, class TableType>
9515 class OrderedHashTableIterator: public JSObject {
9517 // [table]: the backing hash table mapping keys to values.
9518 DECL_ACCESSORS(table, Object)
9520 // [index]: The index into the data table.
9521 DECL_ACCESSORS(index, Object)
9523 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9524 DECL_ACCESSORS(kind, Object)
9527 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9530 static const int kTableOffset = JSObject::kHeaderSize;
9531 static const int kIndexOffset = kTableOffset + kPointerSize;
9532 static const int kKindOffset = kIndexOffset + kPointerSize;
9533 static const int kSize = kKindOffset + kPointerSize;
9541 // Whether the iterator has more elements. This needs to be called before
9542 // calling |CurrentKey| and/or |CurrentValue|.
9545 // Move the index forward one.
9547 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9550 // Populates the array with the next key and value and then moves the iterator
9552 // This returns the |kind| or 0 if the iterator is already at the end.
9553 Smi* Next(JSArray* value_array);
9555 // Returns the current key of the iterator. This should only be called when
9556 // |HasMore| returns true.
9557 inline Object* CurrentKey();
9560 // Transitions the iterator to the non obsolete backing store. This is a NOP
9561 // if the [table] is not obsolete.
9564 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9568 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9571 // Dispatched behavior.
9572 DECLARE_PRINTER(JSSetIterator)
9573 DECLARE_VERIFIER(JSSetIterator)
9575 DECLARE_CAST(JSSetIterator)
9577 // Called by |Next| to populate the array. This allows the subclasses to
9578 // populate the array differently.
9579 inline void PopulateValueArray(FixedArray* array);
9582 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9586 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9589 // Dispatched behavior.
9590 DECLARE_PRINTER(JSMapIterator)
9591 DECLARE_VERIFIER(JSMapIterator)
9593 DECLARE_CAST(JSMapIterator)
9595 // Called by |Next| to populate the array. This allows the subclasses to
9596 // populate the array differently.
9597 inline void PopulateValueArray(FixedArray* array);
9600 // Returns the current value of the iterator. This should only be called when
9601 // |HasMore| returns true.
9602 inline Object* CurrentValue();
9604 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9608 // ES6 section 25.1.1.3 The IteratorResult Interface
9609 class JSIteratorResult final : public JSObject {
9611 // [done]: This is the result status of an iterator next method call. If the
9612 // end of the iterator was reached done is true. If the end was not reached
9613 // done is false and a [value] is available.
9614 DECL_ACCESSORS(done, Object)
9616 // [value]: If [done] is false, this is the current iteration element value.
9617 // If [done] is true, this is the return value of the iterator, if it supplied
9618 // one. If the iterator does not have a return value, value is undefined.
9619 // In that case, the value property may be absent from the conforming object
9620 // if it does not inherit an explicit value property.
9621 DECL_ACCESSORS(value, Object)
9623 // Dispatched behavior.
9624 DECLARE_PRINTER(JSIteratorResult)
9625 DECLARE_VERIFIER(JSIteratorResult)
9627 DECLARE_CAST(JSIteratorResult)
9629 static const int kValueOffset = JSObject::kHeaderSize;
9630 static const int kDoneOffset = kValueOffset + kPointerSize;
9631 static const int kSize = kDoneOffset + kPointerSize;
9633 // Indices of in-object properties.
9634 static const int kValueIndex = 0;
9635 static const int kDoneIndex = 1;
9638 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9642 // Base class for both JSWeakMap and JSWeakSet
9643 class JSWeakCollection: public JSObject {
9645 // [table]: the backing hash table mapping keys to values.
9646 DECL_ACCESSORS(table, Object)
9648 // [next]: linked list of encountered weak maps during GC.
9649 DECL_ACCESSORS(next, Object)
9651 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9652 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9653 Handle<Object> value, int32_t hash);
9654 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9657 static const int kTableOffset = JSObject::kHeaderSize;
9658 static const int kNextOffset = kTableOffset + kPointerSize;
9659 static const int kSize = kNextOffset + kPointerSize;
9662 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9666 // The JSWeakMap describes EcmaScript Harmony weak maps
9667 class JSWeakMap: public JSWeakCollection {
9669 DECLARE_CAST(JSWeakMap)
9671 // Dispatched behavior.
9672 DECLARE_PRINTER(JSWeakMap)
9673 DECLARE_VERIFIER(JSWeakMap)
9676 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9680 // The JSWeakSet describes EcmaScript Harmony weak sets
9681 class JSWeakSet: public JSWeakCollection {
9683 DECLARE_CAST(JSWeakSet)
9685 // Dispatched behavior.
9686 DECLARE_PRINTER(JSWeakSet)
9687 DECLARE_VERIFIER(JSWeakSet)
9690 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9694 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9695 enum class SharedFlag { kNotShared, kShared };
9698 class JSArrayBuffer: public JSObject {
9700 // [backing_store]: backing memory for this array
9701 DECL_ACCESSORS(backing_store, void)
9703 // [byte_length]: length in bytes
9704 DECL_ACCESSORS(byte_length, Object)
9706 inline uint32_t bit_field() const;
9707 inline void set_bit_field(uint32_t bits);
9709 inline bool is_external();
9710 inline void set_is_external(bool value);
9712 inline bool is_neuterable();
9713 inline void set_is_neuterable(bool value);
9715 inline bool was_neutered();
9716 inline void set_was_neutered(bool value);
9718 inline bool is_shared();
9719 inline void set_is_shared(bool value);
9721 DECLARE_CAST(JSArrayBuffer)
9725 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9726 bool is_external, void* data, size_t allocated_length,
9727 SharedFlag shared = SharedFlag::kNotShared);
9729 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9730 Isolate* isolate, size_t allocated_length,
9731 bool initialize = true,
9732 SharedFlag shared = SharedFlag::kNotShared);
9734 // Dispatched behavior.
9735 DECLARE_PRINTER(JSArrayBuffer)
9736 DECLARE_VERIFIER(JSArrayBuffer)
9738 static const int kByteLengthOffset = JSObject::kHeaderSize;
9740 // NOTE: GC will visit objects fields:
9741 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9743 // 2. From start of the internal fields and up to the end of them
9744 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9745 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9746 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9747 static const int kBitFieldOffset = kBitFieldSlot;
9749 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9751 static const int kSize = kBitFieldSlot + kPointerSize;
9753 static const int kSizeWithInternalFields =
9754 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9756 template <typename StaticVisitor>
9757 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9759 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9762 class IsExternal : public BitField<bool, 1, 1> {};
9763 class IsNeuterable : public BitField<bool, 2, 1> {};
9764 class WasNeutered : public BitField<bool, 3, 1> {};
9765 class IsShared : public BitField<bool, 4, 1> {};
9768 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9772 class JSArrayBufferView: public JSObject {
9774 // [buffer]: ArrayBuffer that this typed array views.
9775 DECL_ACCESSORS(buffer, Object)
9777 // [byte_offset]: offset of typed array in bytes.
9778 DECL_ACCESSORS(byte_offset, Object)
9780 // [byte_length]: length of typed array in bytes.
9781 DECL_ACCESSORS(byte_length, Object)
9783 DECLARE_CAST(JSArrayBufferView)
9785 DECLARE_VERIFIER(JSArrayBufferView)
9787 inline bool WasNeutered() const;
9789 static const int kBufferOffset = JSObject::kHeaderSize;
9790 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9791 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9792 static const int kViewSize = kByteLengthOffset + kPointerSize;
9796 DECL_ACCESSORS(raw_byte_offset, Object)
9797 DECL_ACCESSORS(raw_byte_length, Object)
9800 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9804 class JSTypedArray: public JSArrayBufferView {
9806 // [length]: length of typed array in elements.
9807 DECL_ACCESSORS(length, Object)
9808 inline uint32_t length_value() const;
9810 DECLARE_CAST(JSTypedArray)
9812 ExternalArrayType type();
9813 size_t element_size();
9815 Handle<JSArrayBuffer> GetBuffer();
9817 // Dispatched behavior.
9818 DECLARE_PRINTER(JSTypedArray)
9819 DECLARE_VERIFIER(JSTypedArray)
9821 static const int kLengthOffset = kViewSize + kPointerSize;
9822 static const int kSize = kLengthOffset + kPointerSize;
9824 static const int kSizeWithInternalFields =
9825 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9828 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9829 Handle<JSTypedArray> typed_array);
9831 DECL_ACCESSORS(raw_length, Object)
9834 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9838 class JSDataView: public JSArrayBufferView {
9840 DECLARE_CAST(JSDataView)
9842 // Dispatched behavior.
9843 DECLARE_PRINTER(JSDataView)
9844 DECLARE_VERIFIER(JSDataView)
9846 static const int kSize = kViewSize;
9848 static const int kSizeWithInternalFields =
9849 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9852 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9856 // Foreign describes objects pointing from JavaScript to C structures.
9857 class Foreign: public HeapObject {
9859 // [address]: field containing the address.
9860 inline Address foreign_address();
9861 inline void set_foreign_address(Address value);
9863 DECLARE_CAST(Foreign)
9865 // Dispatched behavior.
9866 inline void ForeignIterateBody(ObjectVisitor* v);
9868 template<typename StaticVisitor>
9869 inline void ForeignIterateBody();
9871 // Dispatched behavior.
9872 DECLARE_PRINTER(Foreign)
9873 DECLARE_VERIFIER(Foreign)
9875 // Layout description.
9877 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9878 static const int kSize = kForeignAddressOffset + kPointerSize;
9880 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9883 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9887 // The JSArray describes JavaScript Arrays
9888 // Such an array can be in one of two modes:
9889 // - fast, backing storage is a FixedArray and length <= elements.length();
9890 // Please note: push and pop can be used to grow and shrink the array.
9891 // - slow, backing storage is a HashTable with numbers as keys.
9892 class JSArray: public JSObject {
9894 // [length]: The length property.
9895 DECL_ACCESSORS(length, Object)
9897 // Overload the length setter to skip write barrier when the length
9898 // is set to a smi. This matches the set function on FixedArray.
9899 inline void set_length(Smi* length);
9901 static bool HasReadOnlyLength(Handle<JSArray> array);
9902 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9903 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9905 // Initialize the array with the given capacity. The function may
9906 // fail due to out-of-memory situations, but only if the requested
9907 // capacity is non-zero.
9908 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9910 // If the JSArray has fast elements, and new_length would result in
9911 // normalization, returns true.
9912 bool SetLengthWouldNormalize(uint32_t new_length);
9913 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9915 // Initializes the array to a certain length.
9916 inline bool AllowsSetLength();
9918 static void SetLength(Handle<JSArray> array, uint32_t length);
9919 // Same as above but will also queue splice records if |array| is observed.
9920 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9923 // Set the content of the array to the content of storage.
9924 static inline void SetContent(Handle<JSArray> array,
9925 Handle<FixedArrayBase> storage);
9927 DECLARE_CAST(JSArray)
9929 // Dispatched behavior.
9930 DECLARE_PRINTER(JSArray)
9931 DECLARE_VERIFIER(JSArray)
9933 // Number of element slots to pre-allocate for an empty array.
9934 static const int kPreallocatedArrayElements = 4;
9936 // Layout description.
9937 static const int kLengthOffset = JSObject::kHeaderSize;
9938 static const int kSize = kLengthOffset + kPointerSize;
9941 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9945 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9946 Handle<Map> initial_map);
9949 // JSRegExpResult is just a JSArray with a specific initial map.
9950 // This initial map adds in-object properties for "index" and "input"
9951 // properties, as assigned by RegExp.prototype.exec, which allows
9952 // faster creation of RegExp exec results.
9953 // This class just holds constants used when creating the result.
9954 // After creation the result must be treated as a JSArray in all regards.
9955 class JSRegExpResult: public JSArray {
9957 // Offsets of object fields.
9958 static const int kIndexOffset = JSArray::kSize;
9959 static const int kInputOffset = kIndexOffset + kPointerSize;
9960 static const int kSize = kInputOffset + kPointerSize;
9961 // Indices of in-object properties.
9962 static const int kIndexIndex = 0;
9963 static const int kInputIndex = 1;
9965 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9969 class AccessorInfo: public Struct {
9971 DECL_ACCESSORS(name, Object)
9972 DECL_ACCESSORS(flag, Smi)
9973 DECL_ACCESSORS(expected_receiver_type, Object)
9975 inline bool all_can_read();
9976 inline void set_all_can_read(bool value);
9978 inline bool all_can_write();
9979 inline void set_all_can_write(bool value);
9981 inline bool is_special_data_property();
9982 inline void set_is_special_data_property(bool value);
9984 inline PropertyAttributes property_attributes();
9985 inline void set_property_attributes(PropertyAttributes attributes);
9987 // Checks whether the given receiver is compatible with this accessor.
9988 static bool IsCompatibleReceiverMap(Isolate* isolate,
9989 Handle<AccessorInfo> info,
9991 inline bool IsCompatibleReceiver(Object* receiver);
9993 DECLARE_CAST(AccessorInfo)
9995 // Dispatched behavior.
9996 DECLARE_VERIFIER(AccessorInfo)
9998 // Append all descriptors to the array that are not already there.
9999 // Return number added.
10000 static int AppendUnique(Handle<Object> descriptors,
10001 Handle<FixedArray> array,
10002 int valid_descriptors);
10004 static const int kNameOffset = HeapObject::kHeaderSize;
10005 static const int kFlagOffset = kNameOffset + kPointerSize;
10006 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10007 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10010 inline bool HasExpectedReceiverType();
10012 // Bit positions in flag.
10013 static const int kAllCanReadBit = 0;
10014 static const int kAllCanWriteBit = 1;
10015 static const int kSpecialDataProperty = 2;
10016 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10018 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10022 // An accessor must have a getter, but can have no setter.
10024 // When setting a property, V8 searches accessors in prototypes.
10025 // If an accessor was found and it does not have a setter,
10026 // the request is ignored.
10028 // If the accessor in the prototype has the READ_ONLY property attribute, then
10029 // a new value is added to the derived object when the property is set.
10030 // This shadows the accessor in the prototype.
10031 class ExecutableAccessorInfo: public AccessorInfo {
10033 DECL_ACCESSORS(getter, Object)
10034 DECL_ACCESSORS(setter, Object)
10035 DECL_ACCESSORS(data, Object)
10037 DECLARE_CAST(ExecutableAccessorInfo)
10039 // Dispatched behavior.
10040 DECLARE_PRINTER(ExecutableAccessorInfo)
10041 DECLARE_VERIFIER(ExecutableAccessorInfo)
10043 static const int kGetterOffset = AccessorInfo::kSize;
10044 static const int kSetterOffset = kGetterOffset + kPointerSize;
10045 static const int kDataOffset = kSetterOffset + kPointerSize;
10046 static const int kSize = kDataOffset + kPointerSize;
10048 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10051 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10055 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10056 // accessor can either be
10057 // * a pointer to a JavaScript function or proxy: a real accessor
10058 // * undefined: considered an accessor by the spec, too, strangely enough
10059 // * the hole: an accessor which has not been set
10060 // * a pointer to a map: a transition used to ensure map sharing
10061 class AccessorPair: public Struct {
10063 DECL_ACCESSORS(getter, Object)
10064 DECL_ACCESSORS(setter, Object)
10066 DECLARE_CAST(AccessorPair)
10068 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10070 inline Object* get(AccessorComponent component);
10071 inline void set(AccessorComponent component, Object* value);
10073 // Note: Returns undefined instead in case of a hole.
10074 Object* GetComponent(AccessorComponent component);
10076 // Set both components, skipping arguments which are a JavaScript null.
10077 inline void SetComponents(Object* getter, Object* setter);
10079 inline bool Equals(AccessorPair* pair);
10080 inline bool Equals(Object* getter_value, Object* setter_value);
10082 inline bool ContainsAccessor();
10084 // Dispatched behavior.
10085 DECLARE_PRINTER(AccessorPair)
10086 DECLARE_VERIFIER(AccessorPair)
10088 static const int kGetterOffset = HeapObject::kHeaderSize;
10089 static const int kSetterOffset = kGetterOffset + kPointerSize;
10090 static const int kSize = kSetterOffset + kPointerSize;
10093 // Strangely enough, in addition to functions and harmony proxies, the spec
10094 // requires us to consider undefined as a kind of accessor, too:
10096 // Object.defineProperty(obj, "foo", {get: undefined});
10097 // assertTrue("foo" in obj);
10098 inline bool IsJSAccessor(Object* obj);
10100 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10104 class AccessCheckInfo: public Struct {
10106 DECL_ACCESSORS(named_callback, Object)
10107 DECL_ACCESSORS(indexed_callback, Object)
10108 DECL_ACCESSORS(data, Object)
10110 DECLARE_CAST(AccessCheckInfo)
10112 // Dispatched behavior.
10113 DECLARE_PRINTER(AccessCheckInfo)
10114 DECLARE_VERIFIER(AccessCheckInfo)
10116 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10117 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10118 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10119 static const int kSize = kDataOffset + kPointerSize;
10122 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10126 class InterceptorInfo: public Struct {
10128 DECL_ACCESSORS(getter, Object)
10129 DECL_ACCESSORS(setter, Object)
10130 DECL_ACCESSORS(query, Object)
10131 DECL_ACCESSORS(deleter, Object)
10132 DECL_ACCESSORS(enumerator, Object)
10133 DECL_ACCESSORS(data, Object)
10134 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10135 DECL_BOOLEAN_ACCESSORS(all_can_read)
10136 DECL_BOOLEAN_ACCESSORS(non_masking)
10138 inline int flags() const;
10139 inline void set_flags(int flags);
10141 DECLARE_CAST(InterceptorInfo)
10143 // Dispatched behavior.
10144 DECLARE_PRINTER(InterceptorInfo)
10145 DECLARE_VERIFIER(InterceptorInfo)
10147 static const int kGetterOffset = HeapObject::kHeaderSize;
10148 static const int kSetterOffset = kGetterOffset + kPointerSize;
10149 static const int kQueryOffset = kSetterOffset + kPointerSize;
10150 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10151 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10152 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10153 static const int kFlagsOffset = kDataOffset + kPointerSize;
10154 static const int kSize = kFlagsOffset + kPointerSize;
10156 static const int kCanInterceptSymbolsBit = 0;
10157 static const int kAllCanReadBit = 1;
10158 static const int kNonMasking = 2;
10161 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10165 class CallHandlerInfo: public Struct {
10167 DECL_ACCESSORS(callback, Object)
10168 DECL_ACCESSORS(data, Object)
10170 DECLARE_CAST(CallHandlerInfo)
10172 // Dispatched behavior.
10173 DECLARE_PRINTER(CallHandlerInfo)
10174 DECLARE_VERIFIER(CallHandlerInfo)
10176 static const int kCallbackOffset = HeapObject::kHeaderSize;
10177 static const int kDataOffset = kCallbackOffset + kPointerSize;
10178 static const int kSize = kDataOffset + kPointerSize;
10181 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10185 class TemplateInfo: public Struct {
10187 DECL_ACCESSORS(tag, Object)
10188 inline int number_of_properties() const;
10189 inline void set_number_of_properties(int value);
10190 DECL_ACCESSORS(property_list, Object)
10191 DECL_ACCESSORS(property_accessors, Object)
10193 DECLARE_VERIFIER(TemplateInfo)
10195 static const int kTagOffset = HeapObject::kHeaderSize;
10196 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10197 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10198 static const int kPropertyAccessorsOffset =
10199 kPropertyListOffset + kPointerSize;
10200 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10203 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10207 class FunctionTemplateInfo: public TemplateInfo {
10209 DECL_ACCESSORS(serial_number, Object)
10210 DECL_ACCESSORS(call_code, Object)
10211 DECL_ACCESSORS(prototype_template, Object)
10212 DECL_ACCESSORS(parent_template, Object)
10213 DECL_ACCESSORS(named_property_handler, Object)
10214 DECL_ACCESSORS(indexed_property_handler, Object)
10215 DECL_ACCESSORS(instance_template, Object)
10216 DECL_ACCESSORS(class_name, Object)
10217 DECL_ACCESSORS(signature, Object)
10218 DECL_ACCESSORS(instance_call_handler, Object)
10219 DECL_ACCESSORS(access_check_info, Object)
10220 DECL_ACCESSORS(flag, Smi)
10222 inline int length() const;
10223 inline void set_length(int value);
10225 // Following properties use flag bits.
10226 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10227 DECL_BOOLEAN_ACCESSORS(undetectable)
10228 // If the bit is set, object instances created by this function
10229 // requires access check.
10230 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10231 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10232 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10233 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10234 DECL_BOOLEAN_ACCESSORS(instantiated)
10235 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10237 DECLARE_CAST(FunctionTemplateInfo)
10239 // Dispatched behavior.
10240 DECLARE_PRINTER(FunctionTemplateInfo)
10241 DECLARE_VERIFIER(FunctionTemplateInfo)
10243 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10244 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10245 static const int kPrototypeTemplateOffset =
10246 kCallCodeOffset + kPointerSize;
10247 static const int kParentTemplateOffset =
10248 kPrototypeTemplateOffset + kPointerSize;
10249 static const int kNamedPropertyHandlerOffset =
10250 kParentTemplateOffset + kPointerSize;
10251 static const int kIndexedPropertyHandlerOffset =
10252 kNamedPropertyHandlerOffset + kPointerSize;
10253 static const int kInstanceTemplateOffset =
10254 kIndexedPropertyHandlerOffset + kPointerSize;
10255 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10256 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10257 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10258 static const int kAccessCheckInfoOffset =
10259 kInstanceCallHandlerOffset + kPointerSize;
10260 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10261 static const int kLengthOffset = kFlagOffset + kPointerSize;
10262 static const int kSize = kLengthOffset + kPointerSize;
10264 // Returns true if |object| is an instance of this function template.
10265 bool IsTemplateFor(Object* object);
10266 bool IsTemplateFor(Map* map);
10268 // Returns the holder JSObject if the function can legally be called with this
10269 // receiver. Returns Heap::null_value() if the call is illegal.
10270 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10273 // Bit position in the flag, from least significant bit position.
10274 static const int kHiddenPrototypeBit = 0;
10275 static const int kUndetectableBit = 1;
10276 static const int kNeedsAccessCheckBit = 2;
10277 static const int kReadOnlyPrototypeBit = 3;
10278 static const int kRemovePrototypeBit = 4;
10279 static const int kDoNotCacheBit = 5;
10280 static const int kInstantiatedBit = 6;
10281 static const int kAcceptAnyReceiver = 7;
10283 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10287 class ObjectTemplateInfo: public TemplateInfo {
10289 DECL_ACCESSORS(constructor, Object)
10290 DECL_ACCESSORS(internal_field_count, Object)
10292 DECLARE_CAST(ObjectTemplateInfo)
10294 // Dispatched behavior.
10295 DECLARE_PRINTER(ObjectTemplateInfo)
10296 DECLARE_VERIFIER(ObjectTemplateInfo)
10298 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10299 static const int kInternalFieldCountOffset =
10300 kConstructorOffset + kPointerSize;
10301 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10305 class TypeSwitchInfo: public Struct {
10307 DECL_ACCESSORS(types, Object)
10309 DECLARE_CAST(TypeSwitchInfo)
10311 // Dispatched behavior.
10312 DECLARE_PRINTER(TypeSwitchInfo)
10313 DECLARE_VERIFIER(TypeSwitchInfo)
10315 static const int kTypesOffset = Struct::kHeaderSize;
10316 static const int kSize = kTypesOffset + kPointerSize;
10320 // The DebugInfo class holds additional information for a function being
10322 class DebugInfo: public Struct {
10324 // The shared function info for the source being debugged.
10325 DECL_ACCESSORS(shared, SharedFunctionInfo)
10326 // Code object for the patched code. This code object is the code object
10327 // currently active for the function.
10328 DECL_ACCESSORS(code, Code)
10329 // Fixed array holding status information for each active break point.
10330 DECL_ACCESSORS(break_points, FixedArray)
10332 // Check if there is a break point at a code position.
10333 bool HasBreakPoint(int code_position);
10334 // Get the break point info object for a code position.
10335 Object* GetBreakPointInfo(int code_position);
10336 // Clear a break point.
10337 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10339 Handle<Object> break_point_object);
10340 // Set a break point.
10341 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10342 int source_position, int statement_position,
10343 Handle<Object> break_point_object);
10344 // Get the break point objects for a code position.
10345 Handle<Object> GetBreakPointObjects(int code_position);
10346 // Find the break point info holding this break point object.
10347 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10348 Handle<Object> break_point_object);
10349 // Get the number of break points for this function.
10350 int GetBreakPointCount();
10352 DECLARE_CAST(DebugInfo)
10354 // Dispatched behavior.
10355 DECLARE_PRINTER(DebugInfo)
10356 DECLARE_VERIFIER(DebugInfo)
10358 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10359 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10360 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10361 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10363 static const int kEstimatedNofBreakPointsInFunction = 16;
10366 static const int kNoBreakPointInfo = -1;
10368 // Lookup the index in the break_points array for a code position.
10369 int GetBreakPointInfoIndex(int code_position);
10371 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10375 // The BreakPointInfo class holds information for break points set in a
10376 // function. The DebugInfo object holds a BreakPointInfo object for each code
10377 // position with one or more break points.
10378 class BreakPointInfo: public Struct {
10380 // The position in the code for the break point.
10381 DECL_ACCESSORS(code_position, Smi)
10382 // The position in the source for the break position.
10383 DECL_ACCESSORS(source_position, Smi)
10384 // The position in the source for the last statement before this break
10386 DECL_ACCESSORS(statement_position, Smi)
10387 // List of related JavaScript break points.
10388 DECL_ACCESSORS(break_point_objects, Object)
10390 // Removes a break point.
10391 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10392 Handle<Object> break_point_object);
10393 // Set a break point.
10394 static void SetBreakPoint(Handle<BreakPointInfo> info,
10395 Handle<Object> break_point_object);
10396 // Check if break point info has this break point object.
10397 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10398 Handle<Object> break_point_object);
10399 // Get the number of break points for this code position.
10400 int GetBreakPointCount();
10402 DECLARE_CAST(BreakPointInfo)
10404 // Dispatched behavior.
10405 DECLARE_PRINTER(BreakPointInfo)
10406 DECLARE_VERIFIER(BreakPointInfo)
10408 static const int kCodePositionIndex = Struct::kHeaderSize;
10409 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10410 static const int kStatementPositionIndex =
10411 kSourcePositionIndex + kPointerSize;
10412 static const int kBreakPointObjectsIndex =
10413 kStatementPositionIndex + kPointerSize;
10414 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10417 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10421 #undef DECL_BOOLEAN_ACCESSORS
10422 #undef DECL_ACCESSORS
10423 #undef DECLARE_CAST
10424 #undef DECLARE_VERIFIER
10426 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10427 V(kStringTable, "string_table", "(Internalized strings)") \
10428 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10429 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10430 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10431 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10432 V(kTop, "top", "(Isolate)") \
10433 V(kRelocatable, "relocatable", "(Relocatable)") \
10434 V(kDebug, "debug", "(Debugger)") \
10435 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10436 V(kHandleScope, "handlescope", "(Handle scope)") \
10437 V(kBuiltins, "builtins", "(Builtins)") \
10438 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10439 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10440 V(kThreadManager, "threadmanager", "(Thread manager)") \
10441 V(kStrongRoots, "strong roots", "(Strong roots)") \
10442 V(kExtensions, "Extensions", "(Extensions)")
10444 class VisitorSynchronization : public AllStatic {
10446 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10448 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10451 #undef DECLARE_ENUM
10453 static const char* const kTags[kNumberOfSyncTags];
10454 static const char* const kTagNames[kNumberOfSyncTags];
10457 // Abstract base class for visiting, and optionally modifying, the
10458 // pointers contained in Objects. Used in GC and serialization/deserialization.
10459 class ObjectVisitor BASE_EMBEDDED {
10461 virtual ~ObjectVisitor() {}
10463 // Visits a contiguous arrays of pointers in the half-open range
10464 // [start, end). Any or all of the values may be modified on return.
10465 virtual void VisitPointers(Object** start, Object** end) = 0;
10467 // Handy shorthand for visiting a single pointer.
10468 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10470 // Visit weak next_code_link in Code object.
10471 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10473 // To allow lazy clearing of inline caches the visitor has
10474 // a rich interface for iterating over Code objects..
10476 // Visits a code target in the instruction stream.
10477 virtual void VisitCodeTarget(RelocInfo* rinfo);
10479 // Visits a code entry in a JS function.
10480 virtual void VisitCodeEntry(Address entry_address);
10482 // Visits a global property cell reference in the instruction stream.
10483 virtual void VisitCell(RelocInfo* rinfo);
10485 // Visits a runtime entry in the instruction stream.
10486 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10488 // Visits the resource of an one-byte or two-byte string.
10489 virtual void VisitExternalOneByteString(
10490 v8::String::ExternalOneByteStringResource** resource) {}
10491 virtual void VisitExternalTwoByteString(
10492 v8::String::ExternalStringResource** resource) {}
10494 // Visits a debug call target in the instruction stream.
10495 virtual void VisitDebugTarget(RelocInfo* rinfo);
10497 // Visits the byte sequence in a function's prologue that contains information
10498 // about the code's age.
10499 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10501 // Visit pointer embedded into a code object.
10502 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10504 // Visits an external reference embedded into a code object.
10505 virtual void VisitExternalReference(RelocInfo* rinfo);
10507 // Visits an external reference.
10508 virtual void VisitExternalReference(Address* p) {}
10510 // Visits an (encoded) internal reference.
10511 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10513 // Visits a handle that has an embedder-assigned class ID.
10514 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10516 // Intended for serialization/deserialization checking: insert, or
10517 // check for the presence of, a tag at this position in the stream.
10518 // Also used for marking up GC roots in heap snapshots.
10519 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10523 class StructBodyDescriptor : public
10524 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10526 static inline int SizeOf(Map* map, HeapObject* object);
10530 // BooleanBit is a helper class for setting and getting a bit in an
10532 class BooleanBit : public AllStatic {
10534 static inline bool get(Smi* smi, int bit_position) {
10535 return get(smi->value(), bit_position);
10538 static inline bool get(int value, int bit_position) {
10539 return (value & (1 << bit_position)) != 0;
10542 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10543 return Smi::FromInt(set(smi->value(), bit_position, v));
10546 static inline int set(int value, int bit_position, bool v) {
10548 value |= (1 << bit_position);
10550 value &= ~(1 << bit_position);
10557 class KeyAccumulator final BASE_EMBEDDED {
10559 explicit KeyAccumulator(Isolate* isolate) : isolate_(isolate), length_(0) {}
10561 void AddKey(Handle<Object> key, int check_limit);
10562 void AddKeys(Handle<FixedArray> array, FixedArray::KeyFilter filter);
10563 void AddKeys(Handle<JSObject> array, FixedArray::KeyFilter filter);
10564 void PrepareForComparisons(int count);
10565 Handle<FixedArray> GetKeys();
10567 int GetLength() { return length_; }
10570 void EnsureCapacity(int capacity);
10574 Handle<FixedArray> keys_;
10575 Handle<OrderedHashSet> set_;
10577 DISALLOW_COPY_AND_ASSIGN(KeyAccumulator);
10579 } } // namespace v8::internal
10581 #endif // V8_OBJECTS_H_