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
812 #define DECL_BOOLEAN_ACCESSORS(name) \
813 inline bool name() const; \
814 inline void set_##name(bool value); \
817 #define DECL_ACCESSORS(name, type) \
818 inline type* name() const; \
819 inline void set_##name(type* value, \
820 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
823 #define DECLARE_CAST(type) \
824 INLINE(static type* cast(Object* object)); \
825 INLINE(static const type* cast(const Object* object));
829 class AllocationSite;
830 class AllocationSiteCreationContext;
831 class AllocationSiteUsageContext;
834 class ElementsAccessor;
835 class FixedArrayBase;
836 class FunctionLiteral;
838 class JSBuiltinsObject;
839 class LayoutDescriptor;
840 class LookupIterator;
841 class ObjectHashTable;
844 class SafepointEntry;
845 class SharedFunctionInfo;
847 class TypeFeedbackInfo;
848 class TypeFeedbackVector;
851 // We cannot just say "class HeapType;" if it is created from a template... =8-?
852 template<class> class TypeImpl;
853 struct HeapTypeConfig;
854 typedef TypeImpl<HeapTypeConfig> HeapType;
857 // A template-ized version of the IsXXX functions.
858 template <class C> inline bool Is(Object* obj);
861 #define DECLARE_VERIFIER(Name) void Name##Verify();
863 #define DECLARE_VERIFIER(Name)
867 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
869 #define DECLARE_PRINTER(Name)
873 #define OBJECT_TYPE_LIST(V) \
878 #define HEAP_OBJECT_TYPE_LIST(V) \
880 V(MutableHeapNumber) \
899 V(ExternalTwoByteString) \
900 V(ExternalOneByteString) \
901 V(SeqTwoByteString) \
902 V(SeqOneByteString) \
903 V(InternalizedString) \
906 V(FixedTypedArrayBase) \
909 V(FixedUint16Array) \
911 V(FixedUint32Array) \
913 V(FixedFloat32Array) \
914 V(FixedFloat64Array) \
915 V(FixedUint8ClampedArray) \
921 V(JSContextExtensionObject) \
922 V(JSGeneratorObject) \
924 V(LayoutDescriptor) \
928 V(TypeFeedbackVector) \
929 V(DeoptimizationInputData) \
930 V(DeoptimizationOutputData) \
934 V(FixedDoubleArray) \
938 V(ScriptContextTable) \
944 V(SharedFunctionInfo) \
953 V(JSArrayBufferView) \
962 V(JSIteratorResult) \
963 V(JSWeakCollection) \
970 V(NormalizedMapCache) \
971 V(CompilationCacheTable) \
972 V(CodeCacheHashTable) \
973 V(PolymorphicCodeCacheHashTable) \
978 V(JSBuiltinsObject) \
980 V(UndetectableObject) \
981 V(AccessCheckNeeded) \
989 // Object is the abstract superclass for all classes in the
991 // Object does not use any virtual functions to avoid the
992 // allocation of the C++ vtable.
993 // Since both Smi and HeapObject are subclasses of Object no
994 // data members can be present in Object.
998 bool IsObject() const { return true; }
1000 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1001 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1002 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1003 #undef IS_TYPE_FUNCTION_DECL
1005 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1006 // a keyed store is of the form a[expression] = foo.
1007 enum StoreFromKeyed {
1008 MAY_BE_STORE_FROM_KEYED,
1009 CERTAINLY_NOT_STORE_FROM_KEYED
1012 INLINE(bool IsFixedArrayBase() const);
1013 INLINE(bool IsExternal() const);
1014 INLINE(bool IsAccessorInfo() const);
1016 INLINE(bool IsStruct() const);
1017 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1018 INLINE(bool Is##Name() const);
1019 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1020 #undef DECLARE_STRUCT_PREDICATE
1022 // ES6, section 7.2.3 IsCallable.
1023 INLINE(bool IsCallable() const);
1025 INLINE(bool IsSpecObject()) const;
1026 // TODO(rossberg): IsSpecFunction should be removed in favor of IsCallable.
1027 INLINE(bool IsSpecFunction()) const;
1028 INLINE(bool IsTemplateInfo()) const;
1029 INLINE(bool IsNameDictionary() const);
1030 INLINE(bool IsGlobalDictionary() const);
1031 INLINE(bool IsSeededNumberDictionary() const);
1032 INLINE(bool IsUnseededNumberDictionary() const);
1033 INLINE(bool IsOrderedHashSet() const);
1034 INLINE(bool IsOrderedHashMap() const);
1035 static bool IsPromise(Handle<Object> object);
1038 INLINE(bool IsUndefined() const);
1039 INLINE(bool IsNull() const);
1040 INLINE(bool IsTheHole() const);
1041 INLINE(bool IsException() const);
1042 INLINE(bool IsUninitialized() const);
1043 INLINE(bool IsTrue() const);
1044 INLINE(bool IsFalse() const);
1045 INLINE(bool IsArgumentsMarker() const);
1047 // Filler objects (fillers and free space objects).
1048 INLINE(bool IsFiller() const);
1050 // Extract the number.
1051 inline double Number();
1052 INLINE(bool IsNaN() const);
1053 INLINE(bool IsMinusZero() const);
1054 bool ToInt32(int32_t* value);
1055 bool ToUint32(uint32_t* value);
1057 inline Representation OptimalRepresentation();
1059 inline ElementsKind OptimalElementsKind();
1061 inline bool FitsRepresentation(Representation representation);
1063 // Checks whether two valid primitive encodings of a property name resolve to
1064 // the same logical property. E.g., the smi 1, the string "1" and the double
1065 // 1 all refer to the same property, so this helper will return true.
1066 inline bool KeyEquals(Object* other);
1068 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1070 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1071 Handle<Object> object,
1072 Representation representation);
1074 inline static Handle<Object> WrapForRead(Isolate* isolate,
1075 Handle<Object> object,
1076 Representation representation);
1078 // Returns true if the object is of the correct type to be used as a
1079 // implementation of a JSObject's elements.
1080 inline bool HasValidElements();
1082 inline bool HasSpecificClassOf(String* name);
1084 bool BooleanValue(); // ECMA-262 9.2.
1086 // ES6 section 7.2.13 Strict Equality Comparison
1087 bool StrictEquals(Object* that);
1089 // Convert to a JSObject if needed.
1090 // native_context is used when creating wrapper object.
1091 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1092 Handle<Object> object);
1093 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1094 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1096 // ES6 section 7.1.14 ToPropertyKey
1097 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1098 Handle<Object> input);
1100 // ES6 section 7.1.1 ToPrimitive
1101 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1102 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1104 // ES6 section 7.1.3 ToNumber
1105 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Isolate* isolate,
1106 Handle<Object> input);
1108 // ES6 section 7.1.12 ToString
1109 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1110 Handle<Object> input);
1112 // ES6 section 7.3.9 GetMethod
1113 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1114 Handle<JSReceiver> receiver, Handle<Name> name);
1116 // ES6 section 12.5.6 The typeof Operator
1117 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1119 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1120 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1122 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1123 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1124 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1125 LanguageMode language_mode,
1126 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1129 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1130 StoreFromKeyed store_mode);
1132 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1133 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1134 StoreFromKeyed store_mode);
1136 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1137 LookupIterator* it, LanguageMode language_mode);
1138 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1139 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1140 LanguageMode language_mode);
1141 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1142 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1143 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1144 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1145 Handle<Object> value, LanguageMode language_mode);
1146 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1147 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1148 LanguageMode language_mode);
1149 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1150 LookupIterator* it, Handle<Object> value);
1151 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1152 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1153 LanguageMode language_mode, StoreFromKeyed store_mode);
1154 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1155 Handle<Object> object, Handle<Name> name,
1156 LanguageMode language_mode = SLOPPY);
1157 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1158 Isolate* isolate, Handle<Object> object, const char* key,
1159 LanguageMode language_mode = SLOPPY);
1160 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1161 Handle<Object> object, Handle<Name> name,
1162 LanguageMode language_mode = SLOPPY);
1164 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1165 LookupIterator* it, LanguageMode language_mode);
1166 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1167 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1169 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1170 Handle<Object> receiver,
1171 Handle<JSReceiver> getter);
1172 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1173 Handle<Object> receiver,
1174 Handle<JSReceiver> setter,
1175 Handle<Object> value);
1177 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1178 Isolate* isolate, Handle<Object> object, uint32_t index,
1179 LanguageMode language_mode = SLOPPY);
1181 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1182 Isolate* isolate, Handle<Object> object, uint32_t index,
1183 Handle<Object> value, LanguageMode language_mode);
1185 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1186 Isolate* isolate, Handle<Object> receiver);
1188 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1190 // Returns the permanent hash code associated with this object. May return
1191 // undefined if not yet created.
1194 // Returns undefined for JSObjects, but returns the hash code for simple
1195 // objects. This avoids a double lookup in the cases where we know we will
1196 // add the hash to the JSObject if it does not already exist.
1197 Object* GetSimpleHash();
1199 // Returns the permanent hash code associated with this object depending on
1200 // the actual object type. May create and store a hash code if needed and none
1202 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1204 // Checks whether this object has the same value as the given one. This
1205 // function is implemented according to ES5, section 9.12 and can be used
1206 // to implement the Harmony "egal" function.
1207 bool SameValue(Object* other);
1209 // Checks whether this object has the same value as the given one.
1210 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1211 // This function is implemented according to ES6, section 7.2.4 and is used
1212 // by ES6 Map and Set.
1213 bool SameValueZero(Object* other);
1215 // Tries to convert an object to an array length. Returns true and sets the
1216 // output parameter if it succeeds.
1217 inline bool ToArrayLength(uint32_t* index);
1219 // Tries to convert an object to an array index. Returns true and sets the
1220 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1221 // allow kMaxUInt32.
1222 inline bool ToArrayIndex(uint32_t* index);
1224 // Returns true if this is a JSValue containing a string and the index is
1225 // < the length of the string. Used to implement [] on strings.
1226 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1228 DECLARE_VERIFIER(Object)
1230 // Verify a pointer is a valid object pointer.
1231 static void VerifyPointer(Object* p);
1234 inline void VerifyApiCallResultType();
1236 // Prints this object without details.
1237 void ShortPrint(FILE* out = stdout);
1239 // Prints this object without details to a message accumulator.
1240 void ShortPrint(StringStream* accumulator);
1242 void ShortPrint(std::ostream& os); // NOLINT
1244 DECLARE_CAST(Object)
1246 // Layout description.
1247 static const int kHeaderSize = 0; // Object does not take up any space.
1250 // For our gdb macros, we should perhaps change these in the future.
1253 // Prints this object with details.
1254 void Print(std::ostream& os); // NOLINT
1256 void Print() { ShortPrint(); }
1257 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1261 friend class LookupIterator;
1262 friend class PrototypeIterator;
1264 // Return the map of the root of object's prototype chain.
1265 Map* GetRootMap(Isolate* isolate);
1267 // Helper for SetProperty and SetSuperProperty.
1268 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1269 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1270 StoreFromKeyed store_mode, bool* found);
1272 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1276 // In objects.h to be usable without objects-inl.h inclusion.
1277 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1278 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1282 explicit Brief(const Object* const v) : value(v) {}
1283 const Object* value;
1287 std::ostream& operator<<(std::ostream& os, const Brief& v);
1290 // Smi represents integer Numbers that can be stored in 31 bits.
1291 // Smis are immediate which means they are NOT allocated in the heap.
1292 // The this pointer has the following format: [31 bit signed int] 0
1293 // For long smis it has the following format:
1294 // [32 bit signed int] [31 bits zero padding] 0
1295 // Smi stands for small integer.
1296 class Smi: public Object {
1298 // Returns the integer value.
1299 inline int value() const { return Internals::SmiValue(this); }
1301 // Convert a value to a Smi object.
1302 static inline Smi* FromInt(int value) {
1303 DCHECK(Smi::IsValid(value));
1304 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1307 static inline Smi* FromIntptr(intptr_t value) {
1308 DCHECK(Smi::IsValid(value));
1309 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1310 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1313 // Returns whether value can be represented in a Smi.
1314 static inline bool IsValid(intptr_t value) {
1315 bool result = Internals::IsValidSmi(value);
1316 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1322 // Dispatched behavior.
1323 void SmiPrint(std::ostream& os) const; // NOLINT
1324 DECLARE_VERIFIER(Smi)
1326 static const int kMinValue =
1327 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1328 static const int kMaxValue = -(kMinValue + 1);
1331 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1335 // Heap objects typically have a map pointer in their first word. However,
1336 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1337 // encoded in the first word. The class MapWord is an abstraction of the
1338 // value in a heap object's first word.
1339 class MapWord BASE_EMBEDDED {
1341 // Normal state: the map word contains a map pointer.
1343 // Create a map word from a map pointer.
1344 static inline MapWord FromMap(const Map* map);
1346 // View this map word as a map pointer.
1347 inline Map* ToMap();
1350 // Scavenge collection: the map word of live objects in the from space
1351 // contains a forwarding address (a heap object pointer in the to space).
1353 // True if this map word is a forwarding address for a scavenge
1354 // collection. Only valid during a scavenge collection (specifically,
1355 // when all map words are heap object pointers, i.e. not during a full GC).
1356 inline bool IsForwardingAddress();
1358 // Create a map word from a forwarding address.
1359 static inline MapWord FromForwardingAddress(HeapObject* object);
1361 // View this map word as a forwarding address.
1362 inline HeapObject* ToForwardingAddress();
1364 static inline MapWord FromRawValue(uintptr_t value) {
1365 return MapWord(value);
1368 inline uintptr_t ToRawValue() {
1373 // HeapObject calls the private constructor and directly reads the value.
1374 friend class HeapObject;
1376 explicit MapWord(uintptr_t value) : value_(value) {}
1382 // The content of an heap object (except for the map pointer). kTaggedValues
1383 // objects can contain both heap pointers and Smis, kMixedValues can contain
1384 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1385 // objects can contain raw values and Smis.
1386 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1389 // HeapObject is the superclass for all classes describing heap allocated
1391 class HeapObject: public Object {
1393 // [map]: Contains a map which contains the object's reflective
1395 inline Map* map() const;
1396 inline void set_map(Map* value);
1397 // The no-write-barrier version. This is OK if the object is white and in
1398 // new space, or if the value is an immortal immutable object, like the maps
1399 // of primitive (non-JS) objects like strings, heap numbers etc.
1400 inline void set_map_no_write_barrier(Map* value);
1402 // Get the map using acquire load.
1403 inline Map* synchronized_map();
1404 inline MapWord synchronized_map_word() const;
1406 // Set the map using release store
1407 inline void synchronized_set_map(Map* value);
1408 inline void synchronized_set_map_no_write_barrier(Map* value);
1409 inline void synchronized_set_map_word(MapWord map_word);
1411 // During garbage collection, the map word of a heap object does not
1412 // necessarily contain a map pointer.
1413 inline MapWord map_word() const;
1414 inline void set_map_word(MapWord map_word);
1416 // The Heap the object was allocated in. Used also to access Isolate.
1417 inline Heap* GetHeap() const;
1419 // Convenience method to get current isolate.
1420 inline Isolate* GetIsolate() const;
1422 // Converts an address to a HeapObject pointer.
1423 static inline HeapObject* FromAddress(Address address) {
1424 DCHECK_TAG_ALIGNED(address);
1425 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1428 // Returns the address of this HeapObject.
1429 inline Address address() {
1430 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1433 // Iterates over pointers contained in the object (including the Map)
1434 void Iterate(ObjectVisitor* v);
1436 // Iterates over all pointers contained in the object except the
1437 // first map pointer. The object type is given in the first
1438 // parameter. This function does not access the map pointer in the
1439 // object, and so is safe to call while the map pointer is modified.
1440 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1442 // Returns the heap object's size in bytes
1445 // Indicates what type of values this heap object may contain.
1446 inline HeapObjectContents ContentType();
1448 // Given a heap object's map pointer, returns the heap size in bytes
1449 // Useful when the map pointer field is used for other purposes.
1451 inline int SizeFromMap(Map* map);
1453 // Returns the field at offset in obj, as a read/write Object* reference.
1454 // Does no checking, and is safe to use during GC, while maps are invalid.
1455 // Does not invoke write barrier, so should only be assigned to
1456 // during marking GC.
1457 static inline Object** RawField(HeapObject* obj, int offset);
1459 // Adds the |code| object related to |name| to the code cache of this map. If
1460 // this map is a dictionary map that is shared, the map copied and installed
1462 static void UpdateMapCodeCache(Handle<HeapObject> object,
1466 DECLARE_CAST(HeapObject)
1468 // Return the write barrier mode for this. Callers of this function
1469 // must be able to present a reference to an DisallowHeapAllocation
1470 // object as a sign that they are not going to use this function
1471 // from code that allocates and thus invalidates the returned write
1473 inline WriteBarrierMode GetWriteBarrierMode(
1474 const DisallowHeapAllocation& promise);
1476 // Dispatched behavior.
1477 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1479 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1481 DECLARE_PRINTER(HeapObject)
1482 DECLARE_VERIFIER(HeapObject)
1484 inline void VerifyObjectField(int offset);
1485 inline void VerifySmiField(int offset);
1487 // Verify a pointer is a valid HeapObject pointer that points to object
1488 // areas in the heap.
1489 static void VerifyHeapPointer(Object* p);
1492 inline AllocationAlignment RequiredAlignment();
1494 // Layout description.
1495 // First field in a heap object is map.
1496 static const int kMapOffset = Object::kHeaderSize;
1497 static const int kHeaderSize = kMapOffset + kPointerSize;
1499 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1502 // helpers for calling an ObjectVisitor to iterate over pointers in the
1503 // half-open range [start, end) specified as integer offsets
1504 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1505 // as above, for the single element at "offset"
1506 inline void IteratePointer(ObjectVisitor* v, int offset);
1507 // as above, for the next code link of a code object.
1508 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1511 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1515 // This class describes a body of an object of a fixed size
1516 // in which all pointer fields are located in the [start_offset, end_offset)
1518 template<int start_offset, int end_offset, int size>
1519 class FixedBodyDescriptor {
1521 static const int kStartOffset = start_offset;
1522 static const int kEndOffset = end_offset;
1523 static const int kSize = size;
1525 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1527 template<typename StaticVisitor>
1528 static inline void IterateBody(HeapObject* obj) {
1529 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1530 HeapObject::RawField(obj, end_offset));
1535 // This class describes a body of an object of a variable size
1536 // in which all pointer fields are located in the [start_offset, object_size)
1538 template<int start_offset>
1539 class FlexibleBodyDescriptor {
1541 static const int kStartOffset = start_offset;
1543 static inline void IterateBody(HeapObject* obj,
1547 template<typename StaticVisitor>
1548 static inline void IterateBody(HeapObject* obj, int object_size) {
1549 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1550 HeapObject::RawField(obj, object_size));
1555 // The HeapNumber class describes heap allocated numbers that cannot be
1556 // represented in a Smi (small integer)
1557 class HeapNumber: public HeapObject {
1559 // [value]: number value.
1560 inline double value() const;
1561 inline void set_value(double value);
1563 DECLARE_CAST(HeapNumber)
1565 // Dispatched behavior.
1566 bool HeapNumberBooleanValue();
1568 void HeapNumberPrint(std::ostream& os); // NOLINT
1569 DECLARE_VERIFIER(HeapNumber)
1571 inline int get_exponent();
1572 inline int get_sign();
1574 // Layout description.
1575 static const int kValueOffset = HeapObject::kHeaderSize;
1576 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1577 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1578 // words within double numbers are endian dependent and they are set
1580 #if defined(V8_TARGET_LITTLE_ENDIAN)
1581 static const int kMantissaOffset = kValueOffset;
1582 static const int kExponentOffset = kValueOffset + 4;
1583 #elif defined(V8_TARGET_BIG_ENDIAN)
1584 static const int kMantissaOffset = kValueOffset + 4;
1585 static const int kExponentOffset = kValueOffset;
1587 #error Unknown byte ordering
1590 static const int kSize = kValueOffset + kDoubleSize;
1591 static const uint32_t kSignMask = 0x80000000u;
1592 static const uint32_t kExponentMask = 0x7ff00000u;
1593 static const uint32_t kMantissaMask = 0xfffffu;
1594 static const int kMantissaBits = 52;
1595 static const int kExponentBits = 11;
1596 static const int kExponentBias = 1023;
1597 static const int kExponentShift = 20;
1598 static const int kInfinityOrNanExponent =
1599 (kExponentMask >> kExponentShift) - kExponentBias;
1600 static const int kMantissaBitsInTopWord = 20;
1601 static const int kNonMantissaBitsInTopWord = 12;
1604 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1608 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1609 class Simd128Value : public HeapObject {
1611 DECLARE_CAST(Simd128Value)
1613 DECLARE_PRINTER(Simd128Value)
1614 DECLARE_VERIFIER(Simd128Value)
1616 static Handle<String> ToString(Handle<Simd128Value> input);
1618 // Equality operations.
1619 inline bool Equals(Simd128Value* that);
1621 // Checks that another instance is bit-wise equal.
1622 bool BitwiseEquals(const Simd128Value* other) const;
1623 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1624 uint32_t Hash() const;
1625 // Copies the 16 bytes of SIMD data to the destination address.
1626 void CopyBits(void* destination) const;
1628 // Layout description.
1629 static const int kValueOffset = HeapObject::kHeaderSize;
1630 static const int kSize = kValueOffset + kSimd128Size;
1633 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1637 // V has parameters (TYPE, Type, type, lane count, lane type)
1638 #define SIMD128_TYPES(V) \
1639 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1640 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1641 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1642 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1643 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1644 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1645 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1646 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1647 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1648 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1650 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1651 class Type final : public Simd128Value { \
1653 inline lane_type get_lane(int lane) const; \
1654 inline void set_lane(int lane, lane_type value); \
1656 DECLARE_CAST(Type) \
1658 DECLARE_PRINTER(Type) \
1660 static Handle<String> ToString(Handle<Type> input); \
1662 inline bool Equals(Type* that); \
1665 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1667 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1668 #undef SIMD128_VALUE_CLASS
1671 enum EnsureElementsMode {
1672 DONT_ALLOW_DOUBLE_ELEMENTS,
1673 ALLOW_COPIED_DOUBLE_ELEMENTS,
1674 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1678 // Indicator for one component of an AccessorPair.
1679 enum AccessorComponent {
1685 // JSReceiver includes types on which properties can be defined, i.e.,
1686 // JSObject and JSProxy.
1687 class JSReceiver: public HeapObject {
1689 DECLARE_CAST(JSReceiver)
1691 // ES6 section 7.1.1 ToPrimitive
1692 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1693 Handle<JSReceiver> receiver,
1694 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1695 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1696 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1698 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1699 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1700 Handle<JSReceiver> object, Handle<Name> name);
1701 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1703 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1704 Handle<JSReceiver> object, uint32_t index);
1705 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1706 Handle<JSReceiver> object, uint32_t index);
1708 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1709 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1710 Handle<JSReceiver> object, Handle<Name> name,
1711 LanguageMode language_mode = SLOPPY);
1712 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1713 Handle<JSReceiver> object, Handle<Name> name,
1714 LanguageMode language_mode = SLOPPY);
1715 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1716 LookupIterator* it, LanguageMode language_mode);
1717 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1718 Handle<JSReceiver> object, uint32_t index,
1719 LanguageMode language_mode = SLOPPY);
1721 // Tests for the fast common case for property enumeration.
1722 bool IsSimpleEnum();
1724 // Returns the class name ([[Class]] property in the specification).
1725 String* class_name();
1727 // Returns the constructor name (the name (possibly, inferred name) of the
1728 // function that was used to instantiate the object).
1729 String* constructor_name();
1731 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1732 Handle<JSReceiver> object, Handle<Name> name);
1733 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1734 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1736 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1737 Handle<JSReceiver> object, uint32_t index);
1738 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1739 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1741 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1742 LookupIterator* it);
1745 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1747 static Handle<Object> GetDataProperty(LookupIterator* it);
1750 // Retrieves a permanent object identity hash code. The undefined value might
1751 // be returned in case no hash was created yet.
1752 inline Object* GetIdentityHash();
1754 // Retrieves a permanent object identity hash code. May create and store a
1755 // hash code if needed and none exists.
1756 inline static Handle<Smi> GetOrCreateIdentityHash(
1757 Handle<JSReceiver> object);
1759 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1761 // Computes the enumerable keys for a JSObject. Used for implementing
1762 // "for (n in object) { }".
1763 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1764 Handle<JSReceiver> object,
1765 KeyCollectionType type);
1768 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1772 // The JSObject describes real heap allocated JavaScript objects with
1774 // Note that the map of JSObject changes during execution to enable inline
1776 class JSObject: public JSReceiver {
1778 // [properties]: Backing storage for properties.
1779 // properties is a FixedArray in the fast case and a Dictionary in the
1781 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1782 inline void initialize_properties();
1783 inline bool HasFastProperties();
1784 // Gets slow properties for non-global objects.
1785 inline NameDictionary* property_dictionary();
1786 // Gets global object properties.
1787 inline GlobalDictionary* global_dictionary();
1789 // [elements]: The elements (properties with names that are integers).
1791 // Elements can be in two general modes: fast and slow. Each mode
1792 // corrensponds to a set of object representations of elements that
1793 // have something in common.
1795 // In the fast mode elements is a FixedArray and so each element can
1796 // be quickly accessed. This fact is used in the generated code. The
1797 // elements array can have one of three maps in this mode:
1798 // fixed_array_map, sloppy_arguments_elements_map or
1799 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1800 // the elements array may be shared by a few objects and so before
1801 // writing to any element the array must be copied. Use
1802 // EnsureWritableFastElements in this case.
1804 // In the slow mode the elements is either a NumberDictionary, a
1805 // FixedArray parameter map for a (sloppy) arguments object.
1806 DECL_ACCESSORS(elements, FixedArrayBase)
1807 inline void initialize_elements();
1808 static void ResetElements(Handle<JSObject> object);
1809 static inline void SetMapAndElements(Handle<JSObject> object,
1811 Handle<FixedArrayBase> elements);
1812 inline ElementsKind GetElementsKind();
1813 ElementsAccessor* GetElementsAccessor();
1814 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1815 inline bool HasFastSmiElements();
1816 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1817 inline bool HasFastObjectElements();
1818 // Returns true if an object has elements of FAST_ELEMENTS or
1819 // FAST_SMI_ONLY_ELEMENTS.
1820 inline bool HasFastSmiOrObjectElements();
1821 // Returns true if an object has any of the fast elements kinds.
1822 inline bool HasFastElements();
1823 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1825 inline bool HasFastDoubleElements();
1826 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1828 inline bool HasFastHoleyElements();
1829 inline bool HasSloppyArgumentsElements();
1830 inline bool HasDictionaryElements();
1832 inline bool HasFixedTypedArrayElements();
1834 inline bool HasFixedUint8ClampedElements();
1835 inline bool HasFixedArrayElements();
1836 inline bool HasFixedInt8Elements();
1837 inline bool HasFixedUint8Elements();
1838 inline bool HasFixedInt16Elements();
1839 inline bool HasFixedUint16Elements();
1840 inline bool HasFixedInt32Elements();
1841 inline bool HasFixedUint32Elements();
1842 inline bool HasFixedFloat32Elements();
1843 inline bool HasFixedFloat64Elements();
1845 inline bool HasFastArgumentsElements();
1846 inline bool HasSlowArgumentsElements();
1847 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1849 // Requires: HasFastElements().
1850 static Handle<FixedArray> EnsureWritableFastElements(
1851 Handle<JSObject> object);
1853 // Collects elements starting at index 0.
1854 // Undefined values are placed after non-undefined values.
1855 // Returns the number of non-undefined values.
1856 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1858 // As PrepareElementsForSort, but only on objects where elements is
1859 // a dictionary, and it will stay a dictionary. Collates undefined and
1860 // unexisting elements below limit from position zero of the elements.
1861 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1864 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1865 LookupIterator* it, Handle<Object> value);
1867 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1868 // grant an exemption to ExecutableAccessor callbacks in some cases.
1869 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1871 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1872 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1873 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1875 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1876 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1877 PropertyAttributes attributes,
1878 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1880 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1881 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1882 PropertyAttributes attributes,
1883 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1885 // Equivalent to one of the above depending on whether |name| can be converted
1886 // to an array index.
1887 MUST_USE_RESULT static MaybeHandle<Object>
1888 DefinePropertyOrElementIgnoreAttributes(
1889 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1890 PropertyAttributes attributes = NONE,
1891 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1893 // Adds or reconfigures a property to attributes NONE. It will fail when it
1895 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1896 Handle<Object> value);
1898 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1899 Handle<Object> value, PropertyAttributes attributes);
1901 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1902 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1903 PropertyAttributes attributes);
1905 // Extend the receiver with a single fast property appeared first in the
1906 // passed map. This also extends the property backing store if necessary.
1907 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1909 // Migrates the given object to a map whose field representations are the
1910 // lowest upper bound of all known representations for that field.
1911 static void MigrateInstance(Handle<JSObject> instance);
1913 // Migrates the given object only if the target map is already available,
1914 // or returns false if such a map is not yet available.
1915 static bool TryMigrateInstance(Handle<JSObject> instance);
1917 // Sets the property value in a normalized object given (key, value, details).
1918 // Handles the special representation of JS global objects.
1919 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1920 Handle<Object> value,
1921 PropertyDetails details);
1922 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1923 Handle<Object> value,
1924 PropertyAttributes attributes);
1925 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1927 Handle<Object> value,
1928 PropertyAttributes attributes);
1930 static void OptimizeAsPrototype(Handle<JSObject> object,
1931 PrototypeOptimizationMode mode);
1932 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1933 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1934 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1935 static void InvalidatePrototypeChains(Map* map);
1937 // Alternative implementation of WeakFixedArray::NullCallback.
1938 class PrototypeRegistryCompactionCallback {
1940 static void Callback(Object* value, int old_index, int new_index);
1943 // Retrieve interceptors.
1944 InterceptorInfo* GetNamedInterceptor();
1945 InterceptorInfo* GetIndexedInterceptor();
1947 // Used from JSReceiver.
1948 MUST_USE_RESULT static Maybe<PropertyAttributes>
1949 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1950 MUST_USE_RESULT static Maybe<PropertyAttributes>
1951 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1953 // Retrieves an AccessorPair property from the given object. Might return
1954 // undefined if the property doesn't exist or is of a different kind.
1955 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1956 Handle<JSObject> object,
1958 AccessorComponent component);
1960 // Defines an AccessorPair property on the given object.
1961 // TODO(mstarzinger): Rename to SetAccessor().
1962 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1964 Handle<Object> getter,
1965 Handle<Object> setter,
1966 PropertyAttributes attributes);
1968 // Defines an AccessorInfo property on the given object.
1969 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1970 Handle<JSObject> object,
1971 Handle<AccessorInfo> info);
1973 // The result must be checked first for exceptions. If there's no exception,
1974 // the output parameter |done| indicates whether the interceptor has a result
1976 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1977 LookupIterator* it, bool* done);
1979 // Accessors for hidden properties object.
1981 // Hidden properties are not own properties of the object itself.
1982 // Instead they are stored in an auxiliary structure kept as an own
1983 // property with a special name Heap::hidden_string(). But if the
1984 // receiver is a JSGlobalProxy then the auxiliary object is a property
1985 // of its prototype, and if it's a detached proxy, then you can't have
1986 // hidden properties.
1988 // Sets a hidden property on this object. Returns this object if successful,
1989 // undefined if called on a detached proxy.
1990 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1992 Handle<Object> value);
1993 // Gets the value of a hidden property with the given key. Returns the hole
1994 // if the property doesn't exist (or if called on a detached proxy),
1995 // otherwise returns the value set for the key.
1996 Object* GetHiddenProperty(Handle<Name> key);
1997 // Deletes a hidden property. Deleting a non-existing property is
1998 // considered successful.
1999 static void DeleteHiddenProperty(Handle<JSObject> object,
2001 // Returns true if the object has a property with the hidden string as name.
2002 static bool HasHiddenProperties(Handle<JSObject> object);
2004 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2006 static void ValidateElements(Handle<JSObject> object);
2008 // Makes sure that this object can contain HeapObject as elements.
2009 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2011 // Makes sure that this object can contain the specified elements.
2012 static inline void EnsureCanContainElements(
2013 Handle<JSObject> object,
2016 EnsureElementsMode mode);
2017 static inline void EnsureCanContainElements(
2018 Handle<JSObject> object,
2019 Handle<FixedArrayBase> elements,
2021 EnsureElementsMode mode);
2022 static void EnsureCanContainElements(
2023 Handle<JSObject> object,
2024 Arguments* arguments,
2027 EnsureElementsMode mode);
2029 // Would we convert a fast elements array to dictionary mode given
2030 // an access at key?
2031 bool WouldConvertToSlowElements(uint32_t index);
2033 // Computes the new capacity when expanding the elements of a JSObject.
2034 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2035 // (old_capacity + 50%) + 16
2036 return old_capacity + (old_capacity >> 1) + 16;
2039 // These methods do not perform access checks!
2040 static void UpdateAllocationSite(Handle<JSObject> object,
2041 ElementsKind to_kind);
2043 // Lookup interceptors are used for handling properties controlled by host
2045 inline bool HasNamedInterceptor();
2046 inline bool HasIndexedInterceptor();
2048 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2049 // by JSReceiver::GetKeys.
2050 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2051 Handle<JSObject> object,
2052 Handle<JSReceiver> receiver);
2053 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2054 Handle<JSObject> object,
2055 Handle<JSReceiver> receiver);
2057 // Support functions for v8 api (needed for correct interceptor behavior).
2058 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2059 Handle<JSObject> object, Handle<Name> name);
2060 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2061 Handle<JSObject> object, uint32_t index);
2062 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2063 Handle<JSObject> object, Handle<Name> name);
2065 // Get the header size for a JSObject. Used to compute the index of
2066 // internal fields as well as the number of internal fields.
2067 inline int GetHeaderSize();
2069 inline int GetInternalFieldCount();
2070 inline int GetInternalFieldOffset(int index);
2071 inline Object* GetInternalField(int index);
2072 inline void SetInternalField(int index, Object* value);
2073 inline void SetInternalField(int index, Smi* value);
2075 // Returns the number of properties on this object filtering out properties
2076 // with the specified attributes (ignoring interceptors).
2077 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2078 // Fill in details for properties into storage starting at the specified
2079 // index. Returns the number of properties added.
2080 int GetOwnPropertyNames(FixedArray* storage, int index,
2081 PropertyAttributes filter = NONE);
2083 // Returns the number of properties on this object filtering out properties
2084 // with the specified attributes (ignoring interceptors).
2085 int NumberOfOwnElements(PropertyAttributes filter);
2086 // Returns the number of enumerable elements (ignoring interceptors).
2087 int NumberOfEnumElements();
2088 // Returns the number of elements on this object filtering out elements
2089 // with the specified attributes (ignoring interceptors).
2090 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2091 // Count and fill in the enumerable elements into storage.
2092 // (storage->length() == NumberOfEnumElements()).
2093 // If storage is NULL, will count the elements without adding
2094 // them to any storage.
2095 // Returns the number of enumerable elements.
2096 int GetEnumElementKeys(FixedArray* storage);
2098 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2101 // Returns a new map with all transitions dropped from the object's current
2102 // map and the ElementsKind set.
2103 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2104 ElementsKind to_kind);
2105 static void TransitionElementsKind(Handle<JSObject> object,
2106 ElementsKind to_kind);
2108 // Always use this to migrate an object to a new map.
2109 // |expected_additional_properties| is only used for fast-to-slow transitions
2110 // and ignored otherwise.
2111 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2112 int expected_additional_properties = 0);
2114 // Convert the object to use the canonical dictionary
2115 // representation. If the object is expected to have additional properties
2116 // added this number can be indicated to have the backing store allocated to
2117 // an initial capacity for holding these properties.
2118 static void NormalizeProperties(Handle<JSObject> object,
2119 PropertyNormalizationMode mode,
2120 int expected_additional_properties,
2121 const char* reason);
2123 // Convert and update the elements backing store to be a
2124 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2125 static Handle<SeededNumberDictionary> NormalizeElements(
2126 Handle<JSObject> object);
2128 void RequireSlowElements(SeededNumberDictionary* dictionary);
2130 // Transform slow named properties to fast variants.
2131 static void MigrateSlowToFast(Handle<JSObject> object,
2132 int unused_property_fields, const char* reason);
2134 inline bool IsUnboxedDoubleField(FieldIndex index);
2136 // Access fast-case object properties at index.
2137 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2138 Representation representation,
2140 inline Object* RawFastPropertyAt(FieldIndex index);
2141 inline double RawFastDoublePropertyAt(FieldIndex index);
2143 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2144 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2145 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2146 inline void WriteToField(int descriptor, Object* value);
2148 // Access to in object properties.
2149 inline int GetInObjectPropertyOffset(int index);
2150 inline Object* InObjectPropertyAt(int index);
2151 inline Object* InObjectPropertyAtPut(int index,
2153 WriteBarrierMode mode
2154 = UPDATE_WRITE_BARRIER);
2156 // Set the object's prototype (only JSReceiver and null are allowed values).
2157 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2158 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2160 // Initializes the body after properties slot, properties slot is
2161 // initialized by set_properties. Fill the pre-allocated fields with
2162 // pre_allocated_value and the rest with filler_value.
2163 // Note: this call does not update write barrier, the caller is responsible
2164 // to ensure that |filler_value| can be collected without WB here.
2165 inline void InitializeBody(Map* map,
2166 Object* pre_allocated_value,
2167 Object* filler_value);
2169 // Check whether this object references another object
2170 bool ReferencesObject(Object* obj);
2172 // Disalow further properties to be added to the oject.
2173 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2174 Handle<JSObject> object);
2176 bool IsExtensible();
2179 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2181 // ES5 Object.freeze
2182 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2184 // Called the first time an object is observed with ES7 Object.observe.
2185 static void SetObserved(Handle<JSObject> object);
2188 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2190 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2191 Handle<JSObject> object,
2192 AllocationSiteUsageContext* site_context,
2193 DeepCopyHints hints = kNoHints);
2194 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2195 Handle<JSObject> object,
2196 AllocationSiteCreationContext* site_context);
2198 DECLARE_CAST(JSObject)
2200 // Dispatched behavior.
2201 void JSObjectShortPrint(StringStream* accumulator);
2202 DECLARE_PRINTER(JSObject)
2203 DECLARE_VERIFIER(JSObject)
2205 void PrintProperties(std::ostream& os); // NOLINT
2206 void PrintElements(std::ostream& os); // NOLINT
2208 #if defined(DEBUG) || defined(OBJECT_PRINT)
2209 void PrintTransitions(std::ostream& os); // NOLINT
2212 static void PrintElementsTransition(
2213 FILE* file, Handle<JSObject> object,
2214 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2215 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2217 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2220 // Structure for collecting spill information about JSObjects.
2221 class SpillInformation {
2225 int number_of_objects_;
2226 int number_of_objects_with_fast_properties_;
2227 int number_of_objects_with_fast_elements_;
2228 int number_of_fast_used_fields_;
2229 int number_of_fast_unused_fields_;
2230 int number_of_slow_used_properties_;
2231 int number_of_slow_unused_properties_;
2232 int number_of_fast_used_elements_;
2233 int number_of_fast_unused_elements_;
2234 int number_of_slow_used_elements_;
2235 int number_of_slow_unused_elements_;
2238 void IncrementSpillStatistics(SpillInformation* info);
2242 // If a GC was caused while constructing this object, the elements pointer
2243 // may point to a one pointer filler map. The object won't be rooted, but
2244 // our heap verification code could stumble across it.
2245 bool ElementsAreSafeToExamine();
2248 Object* SlowReverseLookup(Object* value);
2250 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2251 // Also maximal value of JSArray's length property.
2252 static const uint32_t kMaxElementCount = 0xffffffffu;
2254 // Constants for heuristics controlling conversion of fast elements
2255 // to slow elements.
2257 // Maximal gap that can be introduced by adding an element beyond
2258 // the current elements length.
2259 static const uint32_t kMaxGap = 1024;
2261 // Maximal length of fast elements array that won't be checked for
2262 // being dense enough on expansion.
2263 static const int kMaxUncheckedFastElementsLength = 5000;
2265 // Same as above but for old arrays. This limit is more strict. We
2266 // don't want to be wasteful with long lived objects.
2267 static const int kMaxUncheckedOldFastElementsLength = 500;
2269 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2270 // permissible values (see the DCHECK in heap.cc).
2271 static const int kInitialMaxFastElementArray = 100000;
2273 // This constant applies only to the initial map of "global.Object" and
2274 // not to arbitrary other JSObject maps.
2275 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2277 static const int kMaxInstanceSize = 255 * kPointerSize;
2278 // When extending the backing storage for property values, we increase
2279 // its size by more than the 1 entry necessary, so sequentially adding fields
2280 // to the same object requires fewer allocations and copies.
2281 static const int kFieldsAdded = 3;
2283 // Layout description.
2284 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2285 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2286 static const int kHeaderSize = kElementsOffset + kPointerSize;
2288 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2290 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2292 static inline int SizeOf(Map* map, HeapObject* object);
2295 Context* GetCreationContext();
2297 // Enqueue change record for Object.observe. May cause GC.
2298 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2299 Handle<JSObject> object, const char* type, Handle<Name> name,
2300 Handle<Object> old_value);
2302 // Gets the number of currently used elements.
2303 int GetFastElementsUsage();
2305 // Deletes an existing named property in a normalized object.
2306 static void DeleteNormalizedProperty(Handle<JSObject> object,
2307 Handle<Name> name, int entry);
2309 static bool AllCanRead(LookupIterator* it);
2310 static bool AllCanWrite(LookupIterator* it);
2313 friend class JSReceiver;
2314 friend class Object;
2316 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2317 static void MigrateFastToSlow(Handle<JSObject> object,
2318 Handle<Map> new_map,
2319 int expected_additional_properties);
2321 // Used from Object::GetProperty().
2322 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2323 LookupIterator* it);
2325 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2326 LookupIterator* it, Handle<Object> value);
2328 // Add a property to a slow-case object.
2329 static void AddSlowProperty(Handle<JSObject> object,
2331 Handle<Object> value,
2332 PropertyAttributes attributes);
2334 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2335 LookupIterator* it);
2337 bool ReferencesObjectFromElements(FixedArray* elements,
2341 // Return the hash table backing store or the inline stored identity hash,
2342 // whatever is found.
2343 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2345 // Return the hash table backing store for hidden properties. If there is no
2346 // backing store, allocate one.
2347 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2348 Handle<JSObject> object);
2350 // Set the hidden property backing store to either a hash table or
2351 // the inline-stored identity hash.
2352 static Handle<Object> SetHiddenPropertiesHashTable(
2353 Handle<JSObject> object,
2354 Handle<Object> value);
2356 MUST_USE_RESULT Object* GetIdentityHash();
2358 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2360 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2361 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2363 // Helper for fast versions of preventExtensions, seal, and freeze.
2364 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2365 template <PropertyAttributes attrs>
2366 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2367 Handle<JSObject> object);
2369 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2373 // Common superclass for FixedArrays that allow implementations to share
2374 // common accessors and some code paths.
2375 class FixedArrayBase: public HeapObject {
2377 // [length]: length of the array.
2378 inline int length() const;
2379 inline void set_length(int value);
2381 // Get and set the length using acquire loads and release stores.
2382 inline int synchronized_length() const;
2383 inline void synchronized_set_length(int value);
2385 DECLARE_CAST(FixedArrayBase)
2387 // Layout description.
2388 // Length is smi tagged when it is stored.
2389 static const int kLengthOffset = HeapObject::kHeaderSize;
2390 static const int kHeaderSize = kLengthOffset + kPointerSize;
2394 class FixedDoubleArray;
2395 class IncrementalMarking;
2398 // FixedArray describes fixed-sized arrays with element type Object*.
2399 class FixedArray: public FixedArrayBase {
2401 // Setter and getter for elements.
2402 inline Object* get(int index) const;
2403 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2404 // Setter that uses write barrier.
2405 inline void set(int index, Object* value);
2406 inline bool is_the_hole(int index);
2408 // Setter that doesn't need write barrier.
2409 inline void set(int index, Smi* value);
2410 // Setter with explicit barrier mode.
2411 inline void set(int index, Object* value, WriteBarrierMode mode);
2413 // Setters for frequently used oddballs located in old space.
2414 inline void set_undefined(int index);
2415 inline void set_null(int index);
2416 inline void set_the_hole(int index);
2418 inline Object** GetFirstElementAddress();
2419 inline bool ContainsOnlySmisOrHoles();
2421 // Gives access to raw memory which stores the array's data.
2422 inline Object** data_start();
2424 inline void FillWithHoles(int from, int to);
2426 // Shrink length and insert filler objects.
2427 void Shrink(int length);
2429 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2431 // Add the elements of a JSArray to this FixedArray.
2432 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2433 Handle<FixedArray> content, Handle<JSObject> array,
2434 KeyFilter filter = ALL_KEYS);
2436 // Computes the union of keys and return the result.
2437 // Used for implementing "for (n in object) { }"
2438 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2439 Handle<FixedArray> first,
2440 Handle<FixedArray> second);
2442 // Copy a sub array from the receiver to dest.
2443 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2445 // Garbage collection support.
2446 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2448 // Code Generation support.
2449 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2451 // Garbage collection support.
2452 inline Object** RawFieldOfElementAt(int index);
2454 DECLARE_CAST(FixedArray)
2456 // Maximal allowed size, in bytes, of a single FixedArray.
2457 // Prevents overflowing size computations, as well as extreme memory
2459 static const int kMaxSize = 128 * MB * kPointerSize;
2460 // Maximally allowed length of a FixedArray.
2461 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2463 // Dispatched behavior.
2464 DECLARE_PRINTER(FixedArray)
2465 DECLARE_VERIFIER(FixedArray)
2467 // Checks if two FixedArrays have identical contents.
2468 bool IsEqualTo(FixedArray* other);
2471 // Swap two elements in a pair of arrays. If this array and the
2472 // numbers array are the same object, the elements are only swapped
2474 void SwapPairs(FixedArray* numbers, int i, int j);
2476 // Sort prefix of this array and the numbers array as pairs wrt. the
2477 // numbers. If the numbers array and the this array are the same
2478 // object, the prefix of this array is sorted.
2479 void SortPairs(FixedArray* numbers, uint32_t len);
2481 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2483 static inline int SizeOf(Map* map, HeapObject* object);
2487 // Set operation on FixedArray without using write barriers. Can
2488 // only be used for storing old space objects or smis.
2489 static inline void NoWriteBarrierSet(FixedArray* array,
2493 // Set operation on FixedArray without incremental write barrier. Can
2494 // only be used if the object is guaranteed to be white (whiteness witness
2496 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2501 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2503 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2507 // FixedDoubleArray describes fixed-sized arrays with element type double.
2508 class FixedDoubleArray: public FixedArrayBase {
2510 // Setter and getter for elements.
2511 inline double get_scalar(int index);
2512 inline uint64_t get_representation(int index);
2513 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2514 inline void set(int index, double value);
2515 inline void set_the_hole(int index);
2517 // Checking for the hole.
2518 inline bool is_the_hole(int index);
2520 // Garbage collection support.
2521 inline static int SizeFor(int length) {
2522 return kHeaderSize + length * kDoubleSize;
2525 // Gives access to raw memory which stores the array's data.
2526 inline double* data_start();
2528 inline void FillWithHoles(int from, int to);
2530 // Code Generation support.
2531 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2533 DECLARE_CAST(FixedDoubleArray)
2535 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2536 // Prevents overflowing size computations, as well as extreme memory
2538 static const int kMaxSize = 512 * MB;
2539 // Maximally allowed length of a FixedArray.
2540 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2542 // Dispatched behavior.
2543 DECLARE_PRINTER(FixedDoubleArray)
2544 DECLARE_VERIFIER(FixedDoubleArray)
2547 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2551 class WeakFixedArray : public FixedArray {
2553 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2554 // This function does not check if the value exists already, callers must
2555 // ensure this themselves if necessary.
2556 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2557 Handle<HeapObject> value,
2558 int* assigned_index = NULL);
2560 // Returns true if an entry was found and removed.
2561 bool Remove(Handle<HeapObject> value);
2563 class NullCallback {
2565 static void Callback(Object* value, int old_index, int new_index) {}
2568 template <class CompactionCallback>
2571 inline Object* Get(int index) const;
2572 inline void Clear(int index);
2573 inline int Length() const;
2575 inline bool IsEmptySlot(int index) const;
2576 static Object* Empty() { return Smi::FromInt(0); }
2580 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2581 void Reset(Object* maybe_array);
2588 WeakFixedArray* list_;
2590 int last_used_index_;
2591 DisallowHeapAllocation no_gc_;
2593 DISALLOW_COPY_AND_ASSIGN(Iterator);
2596 DECLARE_CAST(WeakFixedArray)
2599 static const int kLastUsedIndexIndex = 0;
2600 static const int kFirstIndex = 1;
2602 static Handle<WeakFixedArray> Allocate(
2603 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2605 static void Set(Handle<WeakFixedArray> array, int index,
2606 Handle<HeapObject> value);
2607 inline void clear(int index);
2609 inline int last_used_index() const;
2610 inline void set_last_used_index(int index);
2612 // Disallow inherited setters.
2613 void set(int index, Smi* value);
2614 void set(int index, Object* value);
2615 void set(int index, Object* value, WriteBarrierMode mode);
2616 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2620 // Generic array grows dynamically with O(1) amortized insertion.
2621 class ArrayList : public FixedArray {
2625 // Use this if GC can delete elements from the array.
2626 kReloadLengthAfterAllocation,
2628 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2629 AddMode mode = kNone);
2630 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2631 Handle<Object> obj2, AddMode = kNone);
2632 inline int Length();
2633 inline void SetLength(int length);
2634 inline Object* Get(int index);
2635 inline Object** Slot(int index);
2636 inline void Set(int index, Object* obj);
2637 inline void Clear(int index, Object* undefined);
2638 DECLARE_CAST(ArrayList)
2641 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2642 static const int kLengthIndex = 0;
2643 static const int kFirstIndex = 1;
2644 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2648 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2649 // The format of the these objects is:
2650 // [0]: Number of descriptors
2651 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2652 // [0]: pointer to fixed array with enum cache
2653 // [1]: either Smi(0) or pointer to fixed array with indices
2655 // [2 + number of descriptors * kDescriptorSize]: start of slack
2656 class DescriptorArray: public FixedArray {
2658 // Returns true for both shared empty_descriptor_array and for smis, which the
2659 // map uses to encode additional bit fields when the descriptor array is not
2661 inline bool IsEmpty();
2663 // Returns the number of descriptors in the array.
2664 inline int number_of_descriptors();
2666 inline int number_of_descriptors_storage();
2668 inline int NumberOfSlackDescriptors();
2670 inline void SetNumberOfDescriptors(int number_of_descriptors);
2671 inline int number_of_entries();
2673 inline bool HasEnumCache();
2675 inline void CopyEnumCacheFrom(DescriptorArray* array);
2677 inline FixedArray* GetEnumCache();
2679 inline bool HasEnumIndicesCache();
2681 inline FixedArray* GetEnumIndicesCache();
2683 inline Object** GetEnumCacheSlot();
2685 void ClearEnumCache();
2687 // Initialize or change the enum cache,
2688 // using the supplied storage for the small "bridge".
2689 void SetEnumCache(FixedArray* bridge_storage,
2690 FixedArray* new_cache,
2691 Object* new_index_cache);
2693 bool CanHoldValue(int descriptor, Object* value);
2695 // Accessors for fetching instance descriptor at descriptor number.
2696 inline Name* GetKey(int descriptor_number);
2697 inline Object** GetKeySlot(int descriptor_number);
2698 inline Object* GetValue(int descriptor_number);
2699 inline void SetValue(int descriptor_number, Object* value);
2700 inline Object** GetValueSlot(int descriptor_number);
2701 static inline int GetValueOffset(int descriptor_number);
2702 inline Object** GetDescriptorStartSlot(int descriptor_number);
2703 inline Object** GetDescriptorEndSlot(int descriptor_number);
2704 inline PropertyDetails GetDetails(int descriptor_number);
2705 inline PropertyType GetType(int descriptor_number);
2706 inline int GetFieldIndex(int descriptor_number);
2707 inline HeapType* GetFieldType(int descriptor_number);
2708 inline Object* GetConstant(int descriptor_number);
2709 inline Object* GetCallbacksObject(int descriptor_number);
2710 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2712 inline Name* GetSortedKey(int descriptor_number);
2713 inline int GetSortedKeyIndex(int descriptor_number);
2714 inline void SetSortedKey(int pointer, int descriptor_number);
2715 inline void SetRepresentation(int descriptor_number,
2716 Representation representation);
2718 // Accessor for complete descriptor.
2719 inline void Get(int descriptor_number, Descriptor* desc);
2720 inline void Set(int descriptor_number, Descriptor* desc);
2721 void Replace(int descriptor_number, Descriptor* descriptor);
2723 // Append automatically sets the enumeration index. This should only be used
2724 // to add descriptors in bulk at the end, followed by sorting the descriptor
2726 inline void Append(Descriptor* desc);
2728 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2729 int enumeration_index,
2732 static Handle<DescriptorArray> CopyUpToAddAttributes(
2733 Handle<DescriptorArray> desc,
2734 int enumeration_index,
2735 PropertyAttributes attributes,
2738 // Sort the instance descriptors by the hash codes of their keys.
2741 // Search the instance descriptors for given name.
2742 INLINE(int Search(Name* name, int number_of_own_descriptors));
2744 // As the above, but uses DescriptorLookupCache and updates it when
2746 INLINE(int SearchWithCache(Name* name, Map* map));
2748 // Allocates a DescriptorArray, but returns the singleton
2749 // empty descriptor array object if number_of_descriptors is 0.
2750 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2751 int number_of_descriptors,
2754 DECLARE_CAST(DescriptorArray)
2756 // Constant for denoting key was not found.
2757 static const int kNotFound = -1;
2759 static const int kDescriptorLengthIndex = 0;
2760 static const int kEnumCacheIndex = 1;
2761 static const int kFirstIndex = 2;
2763 // The length of the "bridge" to the enum cache.
2764 static const int kEnumCacheBridgeLength = 2;
2765 static const int kEnumCacheBridgeCacheIndex = 0;
2766 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2768 // Layout description.
2769 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2770 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2771 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2773 // Layout description for the bridge array.
2774 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2776 // Layout of descriptor.
2777 static const int kDescriptorKey = 0;
2778 static const int kDescriptorDetails = 1;
2779 static const int kDescriptorValue = 2;
2780 static const int kDescriptorSize = 3;
2782 #if defined(DEBUG) || defined(OBJECT_PRINT)
2783 // For our gdb macros, we should perhaps change these in the future.
2786 // Print all the descriptors.
2787 void PrintDescriptors(std::ostream& os); // NOLINT
2791 // Is the descriptor array sorted and without duplicates?
2792 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2794 // Is the descriptor array consistent with the back pointers in targets?
2795 bool IsConsistentWithBackPointers(Map* current_map);
2797 // Are two DescriptorArrays equal?
2798 bool IsEqualTo(DescriptorArray* other);
2801 // Returns the fixed array length required to hold number_of_descriptors
2803 static int LengthFor(int number_of_descriptors) {
2804 return ToKeyIndex(number_of_descriptors);
2808 // WhitenessWitness is used to prove that a descriptor array is white
2809 // (unmarked), so incremental write barriers can be skipped because the
2810 // marking invariant cannot be broken and slots pointing into evacuation
2811 // candidates will be discovered when the object is scanned. A witness is
2812 // always stack-allocated right after creating an array. By allocating a
2813 // witness, incremental marking is globally disabled. The witness is then
2814 // passed along wherever needed to statically prove that the array is known to
2816 class WhitenessWitness {
2818 inline explicit WhitenessWitness(DescriptorArray* array);
2819 inline ~WhitenessWitness();
2822 IncrementalMarking* marking_;
2825 // An entry in a DescriptorArray, represented as an (array, index) pair.
2828 inline explicit Entry(DescriptorArray* descs, int index) :
2829 descs_(descs), index_(index) { }
2831 inline PropertyType type();
2832 inline Object* GetCallbackObject();
2835 DescriptorArray* descs_;
2839 // Conversion from descriptor number to array indices.
2840 static int ToKeyIndex(int descriptor_number) {
2841 return kFirstIndex +
2842 (descriptor_number * kDescriptorSize) +
2846 static int ToDetailsIndex(int descriptor_number) {
2847 return kFirstIndex +
2848 (descriptor_number * kDescriptorSize) +
2852 static int ToValueIndex(int descriptor_number) {
2853 return kFirstIndex +
2854 (descriptor_number * kDescriptorSize) +
2858 // Transfer a complete descriptor from the src descriptor array to this
2859 // descriptor array.
2860 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2862 inline void Set(int descriptor_number,
2864 const WhitenessWitness&);
2866 // Swap first and second descriptor.
2867 inline void SwapSortedKeys(int first, int second);
2869 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2873 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2875 template <SearchMode search_mode, typename T>
2876 inline int Search(T* array, Name* name, int valid_entries = 0,
2877 int* out_insertion_index = NULL);
2880 // HashTable is a subclass of FixedArray that implements a hash table
2881 // that uses open addressing and quadratic probing.
2883 // In order for the quadratic probing to work, elements that have not
2884 // yet been used and elements that have been deleted are
2885 // distinguished. Probing continues when deleted elements are
2886 // encountered and stops when unused elements are encountered.
2888 // - Elements with key == undefined have not been used yet.
2889 // - Elements with key == the_hole have been deleted.
2891 // The hash table class is parameterized with a Shape and a Key.
2892 // Shape must be a class with the following interface:
2893 // class ExampleShape {
2895 // // Tells whether key matches other.
2896 // static bool IsMatch(Key key, Object* other);
2897 // // Returns the hash value for key.
2898 // static uint32_t Hash(Key key);
2899 // // Returns the hash value for object.
2900 // static uint32_t HashForObject(Key key, Object* object);
2901 // // Convert key to an object.
2902 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2903 // // The prefix size indicates number of elements in the beginning
2904 // // of the backing storage.
2905 // static const int kPrefixSize = ..;
2906 // // The Element size indicates number of elements per entry.
2907 // static const int kEntrySize = ..;
2909 // The prefix size indicates an amount of memory in the
2910 // beginning of the backing storage that can be used for non-element
2911 // information by subclasses.
2913 template<typename Key>
2916 static const bool UsesSeed = false;
2917 static uint32_t Hash(Key key) { return 0; }
2918 static uint32_t SeededHash(Key key, uint32_t seed) {
2922 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2923 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2925 return HashForObject(key, object);
2930 class HashTableBase : public FixedArray {
2932 // Returns the number of elements in the hash table.
2933 inline int NumberOfElements();
2935 // Returns the number of deleted elements in the hash table.
2936 inline int NumberOfDeletedElements();
2938 // Returns the capacity of the hash table.
2939 inline int Capacity();
2941 // ElementAdded should be called whenever an element is added to a
2943 inline void ElementAdded();
2945 // ElementRemoved should be called whenever an element is removed from
2947 inline void ElementRemoved();
2948 inline void ElementsRemoved(int n);
2950 // Computes the required capacity for a table holding the given
2951 // number of elements. May be more than HashTable::kMaxCapacity.
2952 static inline int ComputeCapacity(int at_least_space_for);
2954 // Tells whether k is a real key. The hole and undefined are not allowed
2955 // as keys and can be used to indicate missing or deleted elements.
2956 inline bool IsKey(Object* k);
2958 // Compute the probe offset (quadratic probing).
2959 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2960 return (n + n * n) >> 1;
2963 static const int kNumberOfElementsIndex = 0;
2964 static const int kNumberOfDeletedElementsIndex = 1;
2965 static const int kCapacityIndex = 2;
2966 static const int kPrefixStartIndex = 3;
2968 // Constant used for denoting a absent entry.
2969 static const int kNotFound = -1;
2972 // Update the number of elements in the hash table.
2973 inline void SetNumberOfElements(int nof);
2975 // Update the number of deleted elements in the hash table.
2976 inline void SetNumberOfDeletedElements(int nod);
2978 // Returns probe entry.
2979 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2980 DCHECK(base::bits::IsPowerOfTwo32(size));
2981 return (hash + GetProbeOffset(number)) & (size - 1);
2984 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2985 return hash & (size - 1);
2988 inline static uint32_t NextProbe(
2989 uint32_t last, uint32_t number, uint32_t size) {
2990 return (last + number) & (size - 1);
2995 template <typename Derived, typename Shape, typename Key>
2996 class HashTable : public HashTableBase {
2999 inline uint32_t Hash(Key key) {
3000 if (Shape::UsesSeed) {
3001 return Shape::SeededHash(key, GetHeap()->HashSeed());
3003 return Shape::Hash(key);
3007 inline uint32_t HashForObject(Key key, Object* object) {
3008 if (Shape::UsesSeed) {
3009 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3011 return Shape::HashForObject(key, object);
3015 // Returns a new HashTable object.
3016 MUST_USE_RESULT static Handle<Derived> New(
3017 Isolate* isolate, int at_least_space_for,
3018 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3019 PretenureFlag pretenure = NOT_TENURED);
3021 DECLARE_CAST(HashTable)
3023 // Garbage collection support.
3024 void IteratePrefix(ObjectVisitor* visitor);
3025 void IterateElements(ObjectVisitor* visitor);
3027 // Find entry for key otherwise return kNotFound.
3028 inline int FindEntry(Key key);
3029 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3030 int FindEntry(Isolate* isolate, Key key);
3032 // Rehashes the table in-place.
3033 void Rehash(Key key);
3035 // Returns the key at entry.
3036 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3038 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3039 static const int kEntrySize = Shape::kEntrySize;
3040 static const int kElementsStartOffset =
3041 kHeaderSize + kElementsStartIndex * kPointerSize;
3042 static const int kCapacityOffset =
3043 kHeaderSize + kCapacityIndex * kPointerSize;
3045 // Returns the index for an entry (of the key)
3046 static inline int EntryToIndex(int entry) {
3047 return (entry * kEntrySize) + kElementsStartIndex;
3051 friend class ObjectHashTable;
3053 // Find the entry at which to insert element with the given key that
3054 // has the given hash value.
3055 uint32_t FindInsertionEntry(uint32_t hash);
3057 // Attempt to shrink hash table after removal of key.
3058 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3060 // Ensure enough space for n additional elements.
3061 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3062 Handle<Derived> table,
3065 PretenureFlag pretenure = NOT_TENURED);
3067 // Sets the capacity of the hash table.
3068 void SetCapacity(int capacity) {
3069 // To scale a computed hash code to fit within the hash table, we
3070 // use bit-wise AND with a mask, so the capacity must be positive
3072 DCHECK(capacity > 0);
3073 DCHECK(capacity <= kMaxCapacity);
3074 set(kCapacityIndex, Smi::FromInt(capacity));
3077 // Maximal capacity of HashTable. Based on maximal length of underlying
3078 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3080 static const int kMaxCapacity =
3081 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3084 // Returns _expected_ if one of entries given by the first _probe_ probes is
3085 // equal to _expected_. Otherwise, returns the entry given by the probe
3087 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3089 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3091 // Rehashes this hash-table into the new table.
3092 void Rehash(Handle<Derived> new_table, Key key);
3096 // HashTableKey is an abstract superclass for virtual key behavior.
3097 class HashTableKey {
3099 // Returns whether the other object matches this key.
3100 virtual bool IsMatch(Object* other) = 0;
3101 // Returns the hash value for this key.
3102 virtual uint32_t Hash() = 0;
3103 // Returns the hash value for object.
3104 virtual uint32_t HashForObject(Object* key) = 0;
3105 // Returns the key object for storing into the hash table.
3106 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3108 virtual ~HashTableKey() {}
3112 class StringTableShape : public BaseShape<HashTableKey*> {
3114 static inline bool IsMatch(HashTableKey* key, Object* value) {
3115 return key->IsMatch(value);
3118 static inline uint32_t Hash(HashTableKey* key) {
3122 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3123 return key->HashForObject(object);
3126 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3128 static const int kPrefixSize = 0;
3129 static const int kEntrySize = 1;
3132 class SeqOneByteString;
3136 // No special elements in the prefix and the element size is 1
3137 // because only the string itself (the key) needs to be stored.
3138 class StringTable: public HashTable<StringTable,
3142 // Find string in the string table. If it is not there yet, it is
3143 // added. The return value is the string found.
3144 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3145 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3146 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3148 // Tries to internalize given string and returns string handle on success
3149 // or an empty handle otherwise.
3150 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3152 Handle<String> string);
3154 // Looks up a string that is equal to the given string and returns
3155 // string handle if it is found, or an empty handle otherwise.
3156 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3158 Handle<String> str);
3159 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3164 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3166 DECLARE_CAST(StringTable)
3169 template <bool seq_one_byte>
3170 friend class JsonParser;
3172 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3176 template <typename Derived, typename Shape, typename Key>
3177 class Dictionary: public HashTable<Derived, Shape, Key> {
3178 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3181 // Returns the value at entry.
3182 Object* ValueAt(int entry) {
3183 return this->get(Derived::EntryToIndex(entry) + 1);
3186 // Set the value for entry.
3187 void ValueAtPut(int entry, Object* value) {
3188 this->set(Derived::EntryToIndex(entry) + 1, value);
3191 // Returns the property details for the property at entry.
3192 PropertyDetails DetailsAt(int entry) {
3193 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3196 // Set the details for entry.
3197 void DetailsAtPut(int entry, PropertyDetails value) {
3198 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3201 // Returns true if property at given entry is deleted.
3202 bool IsDeleted(int entry) {
3203 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3206 // Delete a property from the dictionary.
3207 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3209 // Attempt to shrink the dictionary after deletion of key.
3210 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3211 Handle<Derived> dictionary,
3213 return DerivedHashTable::Shrink(dictionary, key);
3217 // TODO(dcarney): templatize or move to SeededNumberDictionary
3218 void CopyValuesTo(FixedArray* elements);
3220 // Returns the number of elements in the dictionary filtering out properties
3221 // with the specified attributes.
3222 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3224 // Returns the number of enumerable elements in the dictionary.
3225 int NumberOfEnumElements() {
3226 return NumberOfElementsFilterAttributes(
3227 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3230 // Returns true if the dictionary contains any elements that are non-writable,
3231 // non-configurable, non-enumerable, or have getters/setters.
3232 bool HasComplexElements();
3234 enum SortMode { UNSORTED, SORTED };
3236 // Fill in details for properties into storage.
3237 // Returns the number of properties added.
3238 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3239 SortMode sort_mode);
3241 // Copies enumerable keys to preallocated fixed array.
3242 void CopyEnumKeysTo(FixedArray* storage);
3244 // Accessors for next enumeration index.
3245 void SetNextEnumerationIndex(int index) {
3247 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3250 int NextEnumerationIndex() {
3251 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3254 // Creates a new dictionary.
3255 MUST_USE_RESULT static Handle<Derived> New(
3257 int at_least_space_for,
3258 PretenureFlag pretenure = NOT_TENURED);
3260 // Ensure enough space for n additional elements.
3261 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3264 void Print(std::ostream& os); // NOLINT
3266 // Returns the key (slow).
3267 Object* SlowReverseLookup(Object* value);
3269 // Sets the entry to (key, value) pair.
3270 inline void SetEntry(int entry,
3272 Handle<Object> value);
3273 inline void SetEntry(int entry,
3275 Handle<Object> value,
3276 PropertyDetails details);
3278 MUST_USE_RESULT static Handle<Derived> Add(
3279 Handle<Derived> dictionary,
3281 Handle<Object> value,
3282 PropertyDetails details);
3284 // Returns iteration indices array for the |dictionary|.
3285 // Values are direct indices in the |HashTable| array.
3286 static Handle<FixedArray> BuildIterationIndicesArray(
3287 Handle<Derived> dictionary);
3290 // Generic at put operation.
3291 MUST_USE_RESULT static Handle<Derived> AtPut(
3292 Handle<Derived> dictionary,
3294 Handle<Object> value);
3296 // Add entry to dictionary.
3297 static void AddEntry(
3298 Handle<Derived> dictionary,
3300 Handle<Object> value,
3301 PropertyDetails details,
3304 // Generate new enumeration indices to avoid enumeration index overflow.
3305 // Returns iteration indices array for the |dictionary|.
3306 static Handle<FixedArray> GenerateNewEnumerationIndices(
3307 Handle<Derived> dictionary);
3308 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3309 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3313 template <typename Derived, typename Shape>
3314 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3315 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3318 // Find entry for key, otherwise return kNotFound. Optimized version of
3319 // HashTable::FindEntry.
3320 int FindEntry(Handle<Name> key);
3324 template <typename Key>
3325 class BaseDictionaryShape : public BaseShape<Key> {
3327 template <typename Dictionary>
3328 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3329 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3330 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3331 return PropertyDetails(
3332 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3335 template <typename Dictionary>
3336 static inline void DetailsAtPut(Dictionary* dict, int entry,
3337 PropertyDetails value) {
3338 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3339 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3342 template <typename Dictionary>
3343 static bool IsDeleted(Dictionary* dict, int entry) {
3347 template <typename Dictionary>
3348 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3349 Handle<Object> value, PropertyDetails details);
3353 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3355 static inline bool IsMatch(Handle<Name> key, Object* other);
3356 static inline uint32_t Hash(Handle<Name> key);
3357 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3358 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3359 static const int kPrefixSize = 2;
3360 static const int kEntrySize = 3;
3361 static const bool kIsEnumerable = true;
3365 class NameDictionary
3366 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3367 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3371 DECLARE_CAST(NameDictionary)
3373 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3374 Handle<NameDictionary> dictionary);
3378 class GlobalDictionaryShape : public NameDictionaryShape {
3380 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3382 template <typename Dictionary>
3383 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3385 template <typename Dictionary>
3386 static inline void DetailsAtPut(Dictionary* dict, int entry,
3387 PropertyDetails value);
3389 template <typename Dictionary>
3390 static bool IsDeleted(Dictionary* dict, int entry);
3392 template <typename Dictionary>
3393 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3394 Handle<Object> value, PropertyDetails details);
3398 class GlobalDictionary
3399 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3401 DECLARE_CAST(GlobalDictionary)
3405 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3407 static inline bool IsMatch(uint32_t key, Object* other);
3408 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3409 static const int kEntrySize = 3;
3410 static const bool kIsEnumerable = false;
3414 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3416 static const bool UsesSeed = true;
3417 static const int kPrefixSize = 2;
3419 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3420 static inline uint32_t SeededHashForObject(uint32_t key,
3426 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3428 static const int kPrefixSize = 0;
3430 static inline uint32_t Hash(uint32_t key);
3431 static inline uint32_t HashForObject(uint32_t key, Object* object);
3435 class SeededNumberDictionary
3436 : public Dictionary<SeededNumberDictionary,
3437 SeededNumberDictionaryShape,
3440 DECLARE_CAST(SeededNumberDictionary)
3442 // Type specific at put (default NONE attributes is used when adding).
3443 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3444 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3445 Handle<Object> value, bool used_as_prototype);
3446 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3447 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3448 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3450 // Set an existing entry or add a new one if needed.
3451 // Return the updated dictionary.
3452 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3453 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3454 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3456 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3458 // If slow elements are required we will never go back to fast-case
3459 // for the elements kept in this dictionary. We require slow
3460 // elements if an element has been added at an index larger than
3461 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3462 // when defining a getter or setter with a number key.
3463 inline bool requires_slow_elements();
3464 inline void set_requires_slow_elements();
3466 // Get the value of the max number key that has been added to this
3467 // dictionary. max_number_key can only be called if
3468 // requires_slow_elements returns false.
3469 inline uint32_t max_number_key();
3472 static const int kRequiresSlowElementsMask = 1;
3473 static const int kRequiresSlowElementsTagSize = 1;
3474 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3478 class UnseededNumberDictionary
3479 : public Dictionary<UnseededNumberDictionary,
3480 UnseededNumberDictionaryShape,
3483 DECLARE_CAST(UnseededNumberDictionary)
3485 // Type specific at put (default NONE attributes is used when adding).
3486 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3487 Handle<UnseededNumberDictionary> dictionary,
3489 Handle<Object> value);
3490 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3491 Handle<UnseededNumberDictionary> dictionary,
3493 Handle<Object> value);
3495 // Set an existing entry or add a new one if needed.
3496 // Return the updated dictionary.
3497 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3498 Handle<UnseededNumberDictionary> dictionary,
3500 Handle<Object> value);
3504 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3506 static inline bool IsMatch(Handle<Object> key, Object* other);
3507 static inline uint32_t Hash(Handle<Object> key);
3508 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3509 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3510 static const int kPrefixSize = 0;
3511 static const int kEntrySize = 2;
3515 // ObjectHashTable maps keys that are arbitrary objects to object values by
3516 // using the identity hash of the key for hashing purposes.
3517 class ObjectHashTable: public HashTable<ObjectHashTable,
3518 ObjectHashTableShape,
3521 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3523 DECLARE_CAST(ObjectHashTable)
3525 // Attempt to shrink hash table after removal of key.
3526 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3527 Handle<ObjectHashTable> table,
3528 Handle<Object> key);
3530 // Looks up the value associated with the given key. The hole value is
3531 // returned in case the key is not present.
3532 Object* Lookup(Handle<Object> key);
3533 Object* Lookup(Handle<Object> key, int32_t hash);
3534 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3536 // Adds (or overwrites) the value associated with the given key.
3537 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3539 Handle<Object> value);
3540 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3541 Handle<Object> key, Handle<Object> value,
3544 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3545 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3548 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3549 Handle<Object> key, bool* was_present,
3553 friend class MarkCompactCollector;
3555 void AddEntry(int entry, Object* key, Object* value);
3556 void RemoveEntry(int entry);
3558 // Returns the index to the value of an entry.
3559 static inline int EntryToValueIndex(int entry) {
3560 return EntryToIndex(entry) + 1;
3565 // OrderedHashTable is a HashTable with Object keys that preserves
3566 // insertion order. There are Map and Set interfaces (OrderedHashMap
3567 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3569 // Only Object* keys are supported, with Object::SameValueZero() used as the
3570 // equality operator and Object::GetHash() for the hash function.
3572 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3573 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3574 // Originally attributed to Tyler Close.
3577 // [0]: bucket count
3578 // [1]: element count
3579 // [2]: deleted element count
3580 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3581 // offset into the data table (see below) where the
3582 // first item in this bucket is stored.
3583 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3584 // Capacity() * kEntrySize, where the first entrysize
3585 // items are handled by the derived class and the
3586 // item at kChainOffset is another entry into the
3587 // data table indicating the next entry in this hash
3590 // When we transition the table to a new version we obsolete it and reuse parts
3591 // of the memory to store information how to transition an iterator to the new
3594 // Memory layout for obsolete table:
3595 // [0]: bucket count
3596 // [1]: Next newer table
3597 // [2]: Number of removed holes or -1 when the table was cleared.
3598 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3599 // [3 + NumberOfRemovedHoles()..length]: Not used
3601 template<class Derived, class Iterator, int entrysize>
3602 class OrderedHashTable: public FixedArray {
3604 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3605 static Handle<Derived> Allocate(
3606 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3608 // Returns an OrderedHashTable (possibly |table|) with enough space
3609 // to add at least one new element.
3610 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3612 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3614 static Handle<Derived> Shrink(Handle<Derived> table);
3616 // Returns a new empty OrderedHashTable and records the clearing so that
3617 // exisiting iterators can be updated.
3618 static Handle<Derived> Clear(Handle<Derived> table);
3620 int NumberOfElements() {
3621 return Smi::cast(get(kNumberOfElementsIndex))->value();
3624 int NumberOfDeletedElements() {
3625 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3628 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3630 int NumberOfBuckets() {
3631 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3634 // Returns an index into |this| for the given entry.
3635 int EntryToIndex(int entry) {
3636 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3639 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3642 return !get(kNextTableIndex)->IsSmi();
3645 // The next newer table. This is only valid if the table is obsolete.
3646 Derived* NextTable() {
3647 return Derived::cast(get(kNextTableIndex));
3650 // When the table is obsolete we store the indexes of the removed holes.
3651 int RemovedIndexAt(int index) {
3652 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3655 static const int kNotFound = -1;
3656 static const int kMinCapacity = 4;
3658 static const int kNumberOfBucketsIndex = 0;
3659 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3660 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3661 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3662 static const int kNextTableIndex = kNumberOfElementsIndex;
3664 static const int kNumberOfBucketsOffset =
3665 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3666 static const int kNumberOfElementsOffset =
3667 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3668 static const int kNumberOfDeletedElementsOffset =
3669 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3670 static const int kHashTableStartOffset =
3671 kHeaderSize + kHashTableStartIndex * kPointerSize;
3672 static const int kNextTableOffset =
3673 kHeaderSize + kNextTableIndex * kPointerSize;
3675 static const int kEntrySize = entrysize + 1;
3676 static const int kChainOffset = entrysize;
3678 static const int kLoadFactor = 2;
3680 // NumberOfDeletedElements is set to kClearedTableSentinel when
3681 // the table is cleared, which allows iterator transitions to
3682 // optimize that case.
3683 static const int kClearedTableSentinel = -1;
3686 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3688 void SetNumberOfBuckets(int num) {
3689 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3692 void SetNumberOfElements(int num) {
3693 set(kNumberOfElementsIndex, Smi::FromInt(num));
3696 void SetNumberOfDeletedElements(int num) {
3697 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3701 return NumberOfBuckets() * kLoadFactor;
3704 void SetNextTable(Derived* next_table) {
3705 set(kNextTableIndex, next_table);
3708 void SetRemovedIndexAt(int index, int removed_index) {
3709 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3712 static const int kRemovedHolesIndex = kHashTableStartIndex;
3714 static const int kMaxCapacity =
3715 (FixedArray::kMaxLength - kHashTableStartIndex)
3716 / (1 + (kEntrySize * kLoadFactor));
3720 class JSSetIterator;
3723 class OrderedHashSet: public OrderedHashTable<
3724 OrderedHashSet, JSSetIterator, 1> {
3726 DECLARE_CAST(OrderedHashSet)
3730 class JSMapIterator;
3733 class OrderedHashMap
3734 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3736 DECLARE_CAST(OrderedHashMap)
3738 inline Object* ValueAt(int entry);
3740 static const int kValueOffset = 1;
3744 template <int entrysize>
3745 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3747 static inline bool IsMatch(Handle<Object> key, Object* other);
3748 static inline uint32_t Hash(Handle<Object> key);
3749 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3750 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3751 static const int kPrefixSize = 0;
3752 static const int kEntrySize = entrysize;
3756 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3757 // values. The table wraps the keys in weak cells and store values directly.
3758 // Thus it references keys weakly and values strongly.
3759 class WeakHashTable: public HashTable<WeakHashTable,
3760 WeakHashTableShape<2>,
3763 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3765 DECLARE_CAST(WeakHashTable)
3767 // Looks up the value associated with the given key. The hole value is
3768 // returned in case the key is not present.
3769 Object* Lookup(Handle<HeapObject> key);
3771 // Adds (or overwrites) the value associated with the given key. Mapping a
3772 // key to the hole value causes removal of the whole entry.
3773 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3774 Handle<HeapObject> key,
3775 Handle<HeapObject> value);
3777 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3780 friend class MarkCompactCollector;
3782 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3784 // Returns the index to the value of an entry.
3785 static inline int EntryToValueIndex(int entry) {
3786 return EntryToIndex(entry) + 1;
3791 // ScopeInfo represents information about different scopes of a source
3792 // program and the allocation of the scope's variables. Scope information
3793 // is stored in a compressed form in ScopeInfo objects and is used
3794 // at runtime (stack dumps, deoptimization, etc.).
3796 // This object provides quick access to scope info details for runtime
3798 class ScopeInfo : public FixedArray {
3800 DECLARE_CAST(ScopeInfo)
3802 // Return the type of this scope.
3803 ScopeType scope_type();
3805 // Does this scope call eval?
3808 // Return the language mode of this scope.
3809 LanguageMode language_mode();
3811 // True if this scope is a (var) declaration scope.
3812 bool is_declaration_scope();
3814 // Does this scope make a sloppy eval call?
3815 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3817 // Return the total number of locals allocated on the stack and in the
3818 // context. This includes the parameters that are allocated in the context.
3821 // Return the number of stack slots for code. This number consists of two
3823 // 1. One stack slot per stack allocated local.
3824 // 2. One stack slot for the function name if it is stack allocated.
3825 int StackSlotCount();
3827 // Return the number of context slots for code if a context is allocated. This
3828 // number consists of three parts:
3829 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3830 // 2. One context slot per context allocated local.
3831 // 3. One context slot for the function name if it is context allocated.
3832 // Parameters allocated in the context count as context allocated locals. If
3833 // no contexts are allocated for this scope ContextLength returns 0.
3834 int ContextLength();
3836 // Does this scope declare a "this" binding?
3839 // Does this scope declare a "this" binding, and the "this" binding is stack-
3840 // or context-allocated?
3841 bool HasAllocatedReceiver();
3843 // Is this scope the scope of a named function expression?
3844 bool HasFunctionName();
3846 // Return if this has context allocated locals.
3847 bool HasHeapAllocatedLocals();
3849 // Return if contexts are allocated for this scope.
3852 // Return if this is a function scope with "use asm".
3853 inline bool IsAsmModule();
3855 // Return if this is a nested function within an asm module scope.
3856 inline bool IsAsmFunction();
3858 inline bool HasSimpleParameters();
3860 // Return the function_name if present.
3861 String* FunctionName();
3863 // Return the name of the given parameter.
3864 String* ParameterName(int var);
3866 // Return the name of the given local.
3867 String* LocalName(int var);
3869 // Return the name of the given stack local.
3870 String* StackLocalName(int var);
3872 // Return the name of the given stack local.
3873 int StackLocalIndex(int var);
3875 // Return the name of the given context local.
3876 String* ContextLocalName(int var);
3878 // Return the mode of the given context local.
3879 VariableMode ContextLocalMode(int var);
3881 // Return the initialization flag of the given context local.
3882 InitializationFlag ContextLocalInitFlag(int var);
3884 // Return the initialization flag of the given context local.
3885 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3887 // Return true if this local was introduced by the compiler, and should not be
3888 // exposed to the user in a debugger.
3889 bool LocalIsSynthetic(int var);
3891 String* StrongModeFreeVariableName(int var);
3892 int StrongModeFreeVariableStartPosition(int var);
3893 int StrongModeFreeVariableEndPosition(int var);
3895 // Lookup support for serialized scope info. Returns the
3896 // the stack slot index for a given slot name if the slot is
3897 // present; otherwise returns a value < 0. The name must be an internalized
3899 int StackSlotIndex(String* name);
3901 // Lookup support for serialized scope info. Returns the local context slot
3902 // index for a given slot name if the slot is present; otherwise
3903 // returns a value < 0. The name must be an internalized string.
3904 // If the slot is present and mode != NULL, sets *mode to the corresponding
3905 // mode for that variable.
3906 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3907 VariableMode* mode, InitializationFlag* init_flag,
3908 MaybeAssignedFlag* maybe_assigned_flag);
3910 // Similar to ContextSlotIndex() but this method searches only among
3911 // global slots of the serialized scope info. Returns the context slot index
3912 // for a given slot name if the slot is present; otherwise returns a
3913 // value < 0. The name must be an internalized string. If the slot is present
3914 // and mode != NULL, sets *mode to the corresponding mode for that variable.
3915 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
3916 Handle<String> name, VariableMode* mode,
3917 InitializationFlag* init_flag,
3918 MaybeAssignedFlag* maybe_assigned_flag);
3920 // Lookup the name of a certain context slot by its index.
3921 String* ContextSlotName(int slot_index);
3923 // Lookup support for serialized scope info. Returns the
3924 // parameter index for a given parameter name if the parameter is present;
3925 // otherwise returns a value < 0. The name must be an internalized string.
3926 int ParameterIndex(String* name);
3928 // Lookup support for serialized scope info. Returns the function context
3929 // slot index if the function name is present and context-allocated (named
3930 // function expressions, only), otherwise returns a value < 0. The name
3931 // must be an internalized string.
3932 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3934 // Lookup support for serialized scope info. Returns the receiver context
3935 // slot index if scope has a "this" binding, and the binding is
3936 // context-allocated. Otherwise returns a value < 0.
3937 int ReceiverContextSlotIndex();
3939 FunctionKind function_kind();
3941 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3942 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3944 // Serializes empty scope info.
3945 static ScopeInfo* Empty(Isolate* isolate);
3951 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3952 // numeric and occupies one array slot.
3953 // 1. A set of properties of the scope
3954 // 2. The number of parameters. This only applies to function scopes. For
3955 // non-function scopes this is 0.
3956 // 3. The number of non-parameter variables allocated on the stack.
3957 // 4. The number of non-parameter and parameter variables allocated in the
3959 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3962 V(StackLocalCount) \
3963 V(ContextLocalCount) \
3964 V(ContextGlobalCount) \
3965 V(StrongModeFreeVariableCount)
3967 #define FIELD_ACCESSORS(name) \
3968 inline void Set##name(int value); \
3970 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3971 #undef FIELD_ACCESSORS
3975 #define DECL_INDEX(name) k##name,
3976 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3981 // The layout of the variable part of a ScopeInfo is as follows:
3982 // 1. ParameterEntries:
3983 // This part stores the names of the parameters for function scopes. One
3984 // slot is used per parameter, so in total this part occupies
3985 // ParameterCount() slots in the array. For other scopes than function
3986 // scopes ParameterCount() is 0.
3987 // 2. StackLocalFirstSlot:
3988 // Index of a first stack slot for stack local. Stack locals belonging to
3989 // this scope are located on a stack at slots starting from this index.
3990 // 3. StackLocalEntries:
3991 // Contains the names of local variables that are allocated on the stack,
3992 // in increasing order of the stack slot index. First local variable has
3993 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3994 // One slot is used per stack local, so in total this part occupies
3995 // StackLocalCount() slots in the array.
3996 // 4. ContextLocalNameEntries:
3997 // Contains the names of local variables and parameters that are allocated
3998 // in the context. They are stored in increasing order of the context slot
3999 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4000 // context local, so in total this part occupies ContextLocalCount() slots
4002 // 5. ContextLocalInfoEntries:
4003 // Contains the variable modes and initialization flags corresponding to
4004 // the context locals in ContextLocalNameEntries. One slot is used per
4005 // context local, so in total this part occupies ContextLocalCount()
4006 // slots in the array.
4007 // 6. StrongModeFreeVariableNameEntries:
4008 // Stores the names of strong mode free variables.
4009 // 7. StrongModeFreeVariablePositionEntries:
4010 // Stores the locations (start and end position) of strong mode free
4012 // 8. RecieverEntryIndex:
4013 // If the scope binds a "this" value, one slot is reserved to hold the
4014 // context or stack slot index for the variable.
4015 // 9. FunctionNameEntryIndex:
4016 // If the scope belongs to a named function expression this part contains
4017 // information about the function variable. It always occupies two array
4018 // slots: a. The name of the function variable.
4019 // b. The context or stack slot index for the variable.
4020 int ParameterEntriesIndex();
4021 int StackLocalFirstSlotIndex();
4022 int StackLocalEntriesIndex();
4023 int ContextLocalNameEntriesIndex();
4024 int ContextGlobalNameEntriesIndex();
4025 int ContextLocalInfoEntriesIndex();
4026 int ContextGlobalInfoEntriesIndex();
4027 int StrongModeFreeVariableNameEntriesIndex();
4028 int StrongModeFreeVariablePositionEntriesIndex();
4029 int ReceiverEntryIndex();
4030 int FunctionNameEntryIndex();
4032 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4033 VariableLocation* location, InitializationFlag* init_flag,
4034 MaybeAssignedFlag* maybe_assigned_flag);
4036 // Used for the function name variable for named function expressions, and for
4038 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4040 // Properties of scopes.
4041 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4042 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4043 STATIC_ASSERT(LANGUAGE_END == 3);
4044 class LanguageModeField
4045 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4046 class DeclarationScopeField
4047 : public BitField<bool, LanguageModeField::kNext, 1> {};
4048 class ReceiverVariableField
4049 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4051 class FunctionVariableField
4052 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4054 class FunctionVariableMode
4055 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4056 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4058 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4059 class HasSimpleParametersField
4060 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4061 class FunctionKindField
4062 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4064 // BitFields representing the encoded information for context locals in the
4065 // ContextLocalInfoEntries part.
4066 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4067 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4068 class ContextLocalMaybeAssignedFlag
4069 : public BitField<MaybeAssignedFlag, 4, 1> {};
4071 friend class ScopeIterator;
4075 // The cache for maps used by normalized (dictionary mode) objects.
4076 // Such maps do not have property descriptors, so a typical program
4077 // needs very limited number of distinct normalized maps.
4078 class NormalizedMapCache: public FixedArray {
4080 static Handle<NormalizedMapCache> New(Isolate* isolate);
4082 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4083 PropertyNormalizationMode mode);
4084 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4088 DECLARE_CAST(NormalizedMapCache)
4090 static inline bool IsNormalizedMapCache(const Object* obj);
4092 DECLARE_VERIFIER(NormalizedMapCache)
4094 static const int kEntries = 64;
4096 static inline int GetIndex(Handle<Map> map);
4098 // The following declarations hide base class methods.
4099 Object* get(int index);
4100 void set(int index, Object* value);
4104 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4105 // that is attached to code objects.
4106 class ByteArray: public FixedArrayBase {
4110 // Setter and getter.
4111 inline byte get(int index);
4112 inline void set(int index, byte value);
4114 // Treat contents as an int array.
4115 inline int get_int(int index);
4117 static int SizeFor(int length) {
4118 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4120 // We use byte arrays for free blocks in the heap. Given a desired size in
4121 // bytes that is a multiple of the word size and big enough to hold a byte
4122 // array, this function returns the number of elements a byte array should
4124 static int LengthFor(int size_in_bytes) {
4125 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4126 DCHECK(size_in_bytes >= kHeaderSize);
4127 return size_in_bytes - kHeaderSize;
4130 // Returns data start address.
4131 inline Address GetDataStartAddress();
4133 // Returns a pointer to the ByteArray object for a given data start address.
4134 static inline ByteArray* FromDataStartAddress(Address address);
4136 DECLARE_CAST(ByteArray)
4138 // Dispatched behavior.
4139 inline int ByteArraySize();
4140 DECLARE_PRINTER(ByteArray)
4141 DECLARE_VERIFIER(ByteArray)
4143 // Layout description.
4144 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4146 // Maximal memory consumption for a single ByteArray.
4147 static const int kMaxSize = 512 * MB;
4148 // Maximal length of a single ByteArray.
4149 static const int kMaxLength = kMaxSize - kHeaderSize;
4152 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4156 // BytecodeArray represents a sequence of interpreter bytecodes.
4157 class BytecodeArray : public FixedArrayBase {
4159 static int SizeFor(int length) {
4160 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4163 // Setter and getter
4164 inline byte get(int index);
4165 inline void set(int index, byte value);
4167 // Returns data start address.
4168 inline Address GetFirstBytecodeAddress();
4170 // Accessors for frame size.
4171 inline int frame_size() const;
4172 inline void set_frame_size(int frame_size);
4174 // Accessors for parameter count (including implicit 'this' receiver).
4175 inline int parameter_count() const;
4176 inline void set_parameter_count(int number_of_parameters);
4178 // Accessors for the constant pool.
4179 DECL_ACCESSORS(constant_pool, FixedArray)
4181 DECLARE_CAST(BytecodeArray)
4183 // Dispatched behavior.
4184 inline int BytecodeArraySize();
4185 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4187 DECLARE_PRINTER(BytecodeArray)
4188 DECLARE_VERIFIER(BytecodeArray)
4190 void Disassemble(std::ostream& os);
4192 // Layout description.
4193 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4194 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4195 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4196 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4198 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4200 // Maximal memory consumption for a single BytecodeArray.
4201 static const int kMaxSize = 512 * MB;
4202 // Maximal length of a single BytecodeArray.
4203 static const int kMaxLength = kMaxSize - kHeaderSize;
4206 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4210 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4211 // They look like heap objects (are heap object tagged and have a map) so that
4212 // the heap remains iterable. They have a size and a next pointer.
4213 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4214 // in the free list.
4215 class FreeSpace: public HeapObject {
4217 // [size]: size of the free space including the header.
4218 inline int size() const;
4219 inline void set_size(int value);
4221 inline int nobarrier_size() const;
4222 inline void nobarrier_set_size(int value);
4226 // Accessors for the next field.
4227 inline FreeSpace* next();
4228 inline FreeSpace** next_address();
4229 inline void set_next(FreeSpace* next);
4231 inline static FreeSpace* cast(HeapObject* obj);
4233 // Dispatched behavior.
4234 DECLARE_PRINTER(FreeSpace)
4235 DECLARE_VERIFIER(FreeSpace)
4237 // Layout description.
4238 // Size is smi tagged when it is stored.
4239 static const int kSizeOffset = HeapObject::kHeaderSize;
4240 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4243 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4247 // V has parameters (Type, type, TYPE, C type, element_size)
4248 #define TYPED_ARRAYS(V) \
4249 V(Uint8, uint8, UINT8, uint8_t, 1) \
4250 V(Int8, int8, INT8, int8_t, 1) \
4251 V(Uint16, uint16, UINT16, uint16_t, 2) \
4252 V(Int16, int16, INT16, int16_t, 2) \
4253 V(Uint32, uint32, UINT32, uint32_t, 4) \
4254 V(Int32, int32, INT32, int32_t, 4) \
4255 V(Float32, float32, FLOAT32, float, 4) \
4256 V(Float64, float64, FLOAT64, double, 8) \
4257 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4260 class FixedTypedArrayBase: public FixedArrayBase {
4262 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4263 DECL_ACCESSORS(base_pointer, Object)
4265 // [external_pointer]: Contains the offset between base_pointer and the start
4266 // of the data. If the base_pointer is a nullptr, the external_pointer
4267 // therefore points to the actual backing store.
4268 DECL_ACCESSORS(external_pointer, void)
4270 // Dispatched behavior.
4271 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4273 template <typename StaticVisitor>
4274 inline void FixedTypedArrayBaseIterateBody();
4276 DECLARE_CAST(FixedTypedArrayBase)
4278 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4279 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4280 static const int kHeaderSize =
4281 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4283 static const int kDataOffset = kHeaderSize;
4287 static inline int TypedArraySize(InstanceType type, int length);
4288 inline int TypedArraySize(InstanceType type);
4290 // Use with care: returns raw pointer into heap.
4291 inline void* DataPtr();
4293 inline int DataSize();
4296 static inline int ElementSize(InstanceType type);
4298 inline int DataSize(InstanceType type);
4300 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4304 template <class Traits>
4305 class FixedTypedArray: public FixedTypedArrayBase {
4307 typedef typename Traits::ElementType ElementType;
4308 static const InstanceType kInstanceType = Traits::kInstanceType;
4310 DECLARE_CAST(FixedTypedArray<Traits>)
4312 inline ElementType get_scalar(int index);
4313 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4314 inline void set(int index, ElementType value);
4316 static inline ElementType from_int(int value);
4317 static inline ElementType from_double(double value);
4319 // This accessor applies the correct conversion from Smi, HeapNumber
4321 inline void SetValue(uint32_t index, Object* value);
4323 DECLARE_PRINTER(FixedTypedArray)
4324 DECLARE_VERIFIER(FixedTypedArray)
4327 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4330 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4331 class Type##ArrayTraits { \
4332 public: /* NOLINT */ \
4333 typedef elementType ElementType; \
4334 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4335 static const char* Designator() { return #type " array"; } \
4336 static inline Handle<Object> ToHandle(Isolate* isolate, \
4337 elementType scalar); \
4338 static inline elementType defaultValue(); \
4341 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4343 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4345 #undef FIXED_TYPED_ARRAY_TRAITS
4348 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4349 // data for code generated by the Hydrogen/Lithium compiler. It also
4350 // contains information about functions that were inlined. If N different
4351 // functions were inlined then first N elements of the literal array will
4352 // contain these functions.
4355 class DeoptimizationInputData: public FixedArray {
4357 // Layout description. Indices in the array.
4358 static const int kTranslationByteArrayIndex = 0;
4359 static const int kInlinedFunctionCountIndex = 1;
4360 static const int kLiteralArrayIndex = 2;
4361 static const int kOsrAstIdIndex = 3;
4362 static const int kOsrPcOffsetIndex = 4;
4363 static const int kOptimizationIdIndex = 5;
4364 static const int kSharedFunctionInfoIndex = 6;
4365 static const int kWeakCellCacheIndex = 7;
4366 static const int kFirstDeoptEntryIndex = 8;
4368 // Offsets of deopt entry elements relative to the start of the entry.
4369 static const int kAstIdRawOffset = 0;
4370 static const int kTranslationIndexOffset = 1;
4371 static const int kArgumentsStackHeightOffset = 2;
4372 static const int kPcOffset = 3;
4373 static const int kDeoptEntrySize = 4;
4375 // Simple element accessors.
4376 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4377 inline type* name(); \
4378 inline void Set##name(type* value);
4380 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4381 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4382 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4383 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4384 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4385 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4386 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4387 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4389 #undef DECLARE_ELEMENT_ACCESSORS
4391 // Accessors for elements of the ith deoptimization entry.
4392 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4393 inline type* name(int i); \
4394 inline void Set##name(int i, type* value);
4396 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4397 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4398 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4399 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4401 #undef DECLARE_ENTRY_ACCESSORS
4403 inline BailoutId AstId(int i);
4405 inline void SetAstId(int i, BailoutId value);
4407 inline int DeoptCount();
4409 // Allocates a DeoptimizationInputData.
4410 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4411 int deopt_entry_count,
4412 PretenureFlag pretenure);
4414 DECLARE_CAST(DeoptimizationInputData)
4416 #ifdef ENABLE_DISASSEMBLER
4417 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4421 static int IndexForEntry(int i) {
4422 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4426 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4430 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4431 // data for code generated by the full compiler.
4432 // The format of the these objects is
4433 // [i * 2]: Ast ID for ith deoptimization.
4434 // [i * 2 + 1]: PC and state of ith deoptimization
4435 class DeoptimizationOutputData: public FixedArray {
4437 inline int DeoptPoints();
4439 inline BailoutId AstId(int index);
4441 inline void SetAstId(int index, BailoutId id);
4443 inline Smi* PcAndState(int index);
4444 inline void SetPcAndState(int index, Smi* offset);
4446 static int LengthOfFixedArray(int deopt_points) {
4447 return deopt_points * 2;
4450 // Allocates a DeoptimizationOutputData.
4451 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4452 int number_of_deopt_points,
4453 PretenureFlag pretenure);
4455 DECLARE_CAST(DeoptimizationOutputData)
4457 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4458 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4463 // HandlerTable is a fixed array containing entries for exception handlers in
4464 // the code object it is associated with. The tables comes in two flavors:
4465 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4466 // exception handler and a range representing the try-block covered by that
4467 // handler. Layout looks as follows:
4468 // [ range-start , range-end , handler-offset , stack-depth ]
4469 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4470 // per call-site that could throw an exception. Layout looks as follows:
4471 // [ return-address-offset , handler-offset ]
4472 class HandlerTable : public FixedArray {
4474 // Conservative prediction whether a given handler will locally catch an
4475 // exception or cause a re-throw to outside the code boundary. Since this is
4476 // undecidable it is merely an approximation (e.g. useful for debugger).
4477 enum CatchPrediction { UNCAUGHT, CAUGHT };
4479 // Accessors for handler table based on ranges.
4480 inline void SetRangeStart(int index, int value);
4481 inline void SetRangeEnd(int index, int value);
4482 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4483 inline void SetRangeDepth(int index, int value);
4485 // Accessors for handler table based on return addresses.
4486 inline void SetReturnOffset(int index, int value);
4487 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4489 // Lookup handler in a table based on ranges.
4490 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4492 // Lookup handler in a table based on return addresses.
4493 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4495 // Returns the required length of the underlying fixed array.
4496 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4497 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4499 DECLARE_CAST(HandlerTable)
4501 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4502 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4503 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4507 // Layout description for handler table based on ranges.
4508 static const int kRangeStartIndex = 0;
4509 static const int kRangeEndIndex = 1;
4510 static const int kRangeHandlerIndex = 2;
4511 static const int kRangeDepthIndex = 3;
4512 static const int kRangeEntrySize = 4;
4514 // Layout description for handler table based on return addresses.
4515 static const int kReturnOffsetIndex = 0;
4516 static const int kReturnHandlerIndex = 1;
4517 static const int kReturnEntrySize = 2;
4519 // Encoding of the {handler} field.
4520 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4521 class HandlerOffsetField : public BitField<int, 1, 30> {};
4525 // Code describes objects with on-the-fly generated machine code.
4526 class Code: public HeapObject {
4528 // Opaque data type for encapsulating code flags like kind, inline
4529 // cache state, and arguments count.
4530 typedef uint32_t Flags;
4532 #define NON_IC_KIND_LIST(V) \
4534 V(OPTIMIZED_FUNCTION) \
4541 #define IC_KIND_LIST(V) \
4552 #define CODE_KIND_LIST(V) \
4553 NON_IC_KIND_LIST(V) \
4557 #define DEFINE_CODE_KIND_ENUM(name) name,
4558 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4559 #undef DEFINE_CODE_KIND_ENUM
4563 // No more than 16 kinds. The value is currently encoded in four bits in
4565 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4567 static const char* Kind2String(Kind kind);
4575 static const int kPrologueOffsetNotSet = -1;
4577 #ifdef ENABLE_DISASSEMBLER
4579 static const char* ICState2String(InlineCacheState state);
4580 static const char* StubType2String(StubType type);
4581 static void PrintExtraICState(std::ostream& os, // NOLINT
4582 Kind kind, ExtraICState extra);
4583 void Disassemble(const char* name, std::ostream& os); // NOLINT
4584 #endif // ENABLE_DISASSEMBLER
4586 // [instruction_size]: Size of the native instructions
4587 inline int instruction_size() const;
4588 inline void set_instruction_size(int value);
4590 // [relocation_info]: Code relocation information
4591 DECL_ACCESSORS(relocation_info, ByteArray)
4592 void InvalidateRelocation();
4593 void InvalidateEmbeddedObjects();
4595 // [handler_table]: Fixed array containing offsets of exception handlers.
4596 DECL_ACCESSORS(handler_table, FixedArray)
4598 // [deoptimization_data]: Array containing data for deopt.
4599 DECL_ACCESSORS(deoptimization_data, FixedArray)
4601 // [raw_type_feedback_info]: This field stores various things, depending on
4602 // the kind of the code object.
4603 // FUNCTION => type feedback information.
4604 // STUB and ICs => major/minor key as Smi.
4605 DECL_ACCESSORS(raw_type_feedback_info, Object)
4606 inline Object* type_feedback_info();
4607 inline void set_type_feedback_info(
4608 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4609 inline uint32_t stub_key();
4610 inline void set_stub_key(uint32_t key);
4612 // [next_code_link]: Link for lists of optimized or deoptimized code.
4613 // Note that storage for this field is overlapped with typefeedback_info.
4614 DECL_ACCESSORS(next_code_link, Object)
4616 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4617 // field does not have to be traced during garbage collection since
4618 // it is only used by the garbage collector itself.
4619 DECL_ACCESSORS(gc_metadata, Object)
4621 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4622 // at the moment when this object was created.
4623 inline void set_ic_age(int count);
4624 inline int ic_age() const;
4626 // [prologue_offset]: Offset of the function prologue, used for aging
4627 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4628 inline int prologue_offset() const;
4629 inline void set_prologue_offset(int offset);
4631 // [constant_pool offset]: Offset of the constant pool.
4632 // Valid for FLAG_enable_embedded_constant_pool only
4633 inline int constant_pool_offset() const;
4634 inline void set_constant_pool_offset(int offset);
4636 // Unchecked accessors to be used during GC.
4637 inline ByteArray* unchecked_relocation_info();
4639 inline int relocation_size();
4641 // [flags]: Various code flags.
4642 inline Flags flags();
4643 inline void set_flags(Flags flags);
4645 // [flags]: Access to specific code flags.
4647 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4648 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4650 inline StubType type(); // Only valid for monomorphic IC stubs.
4652 // Testers for IC stub kinds.
4653 inline bool is_inline_cache_stub();
4654 inline bool is_debug_stub();
4655 inline bool is_handler();
4656 inline bool is_load_stub();
4657 inline bool is_keyed_load_stub();
4658 inline bool is_store_stub();
4659 inline bool is_keyed_store_stub();
4660 inline bool is_call_stub();
4661 inline bool is_binary_op_stub();
4662 inline bool is_compare_ic_stub();
4663 inline bool is_compare_nil_ic_stub();
4664 inline bool is_to_boolean_ic_stub();
4665 inline bool is_keyed_stub();
4666 inline bool is_optimized_code();
4667 inline bool embeds_maps_weakly();
4669 inline bool IsCodeStubOrIC();
4670 inline bool IsJavaScriptCode();
4672 inline void set_raw_kind_specific_flags1(int value);
4673 inline void set_raw_kind_specific_flags2(int value);
4675 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4676 // object was generated by either the hydrogen or the TurboFan optimizing
4677 // compiler (but it may not be an optimized function).
4678 inline bool is_crankshafted();
4679 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4680 inline void set_is_crankshafted(bool value);
4682 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4683 // code object was generated by the TurboFan optimizing compiler.
4684 inline bool is_turbofanned();
4685 inline void set_is_turbofanned(bool value);
4687 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4688 // embedded objects in code should be treated weakly.
4689 inline bool can_have_weak_objects();
4690 inline void set_can_have_weak_objects(bool value);
4692 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4693 // deoptimization support.
4694 inline bool has_deoptimization_support();
4695 inline void set_has_deoptimization_support(bool value);
4697 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4698 // been compiled with debug break slots.
4699 inline bool has_debug_break_slots();
4700 inline void set_has_debug_break_slots(bool value);
4702 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4703 // reloc info includes runtime and external references to support
4704 // serialization/deserialization.
4705 inline bool has_reloc_info_for_serialization();
4706 inline void set_has_reloc_info_for_serialization(bool value);
4708 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4709 // how long the function has been marked for OSR and therefore which
4710 // level of loop nesting we are willing to do on-stack replacement
4712 inline void set_allow_osr_at_loop_nesting_level(int level);
4713 inline int allow_osr_at_loop_nesting_level();
4715 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4716 // the code object was seen on the stack with no IC patching going on.
4717 inline int profiler_ticks();
4718 inline void set_profiler_ticks(int ticks);
4720 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4721 // For builtins, tells which builtin index it has.
4722 // Note that builtins can have a code kind other than BUILTIN, which means
4723 // that for arbitrary code objects, this index value may be random garbage.
4724 // To verify in that case, compare the code object to the indexed builtin.
4725 inline int builtin_index();
4726 inline void set_builtin_index(int id);
4728 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4729 // reserved in the code prologue.
4730 inline unsigned stack_slots();
4731 inline void set_stack_slots(unsigned slots);
4733 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4734 // the instruction stream where the safepoint table starts.
4735 inline unsigned safepoint_table_offset();
4736 inline void set_safepoint_table_offset(unsigned offset);
4738 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4739 // instruction stream where the back edge table starts.
4740 inline unsigned back_edge_table_offset();
4741 inline void set_back_edge_table_offset(unsigned offset);
4743 inline bool back_edges_patched_for_osr();
4745 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4746 inline uint16_t to_boolean_state();
4748 // [has_function_cache]: For kind STUB tells whether there is a function
4749 // cache is passed to the stub.
4750 inline bool has_function_cache();
4751 inline void set_has_function_cache(bool flag);
4754 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4755 // the code is going to be deoptimized because of dead embedded maps.
4756 inline bool marked_for_deoptimization();
4757 inline void set_marked_for_deoptimization(bool flag);
4759 // [constant_pool]: The constant pool for this function.
4760 inline Address constant_pool();
4762 // Get the safepoint entry for the given pc.
4763 SafepointEntry GetSafepointEntry(Address pc);
4765 // Find an object in a stub with a specified map
4766 Object* FindNthObject(int n, Map* match_map);
4768 // Find the first allocation site in an IC stub.
4769 AllocationSite* FindFirstAllocationSite();
4771 // Find the first map in an IC stub.
4772 Map* FindFirstMap();
4773 void FindAllMaps(MapHandleList* maps);
4775 // Find the first handler in an IC stub.
4776 Code* FindFirstHandler();
4778 // Find |length| handlers and put them into |code_list|. Returns false if not
4779 // enough handlers can be found.
4780 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4782 // Find the handler for |map|.
4783 MaybeHandle<Code> FindHandlerForMap(Map* map);
4785 // Find the first name in an IC stub.
4786 Name* FindFirstName();
4788 class FindAndReplacePattern;
4789 // For each (map-to-find, object-to-replace) pair in the pattern, this
4790 // function replaces the corresponding placeholder in the code with the
4791 // object-to-replace. The function assumes that pairs in the pattern come in
4792 // the same order as the placeholders in the code.
4793 // If the placeholder is a weak cell, then the value of weak cell is matched
4794 // against the map-to-find.
4795 void FindAndReplace(const FindAndReplacePattern& pattern);
4797 // The entire code object including its header is copied verbatim to the
4798 // snapshot so that it can be written in one, fast, memcpy during
4799 // deserialization. The deserializer will overwrite some pointers, rather
4800 // like a runtime linker, but the random allocation addresses used in the
4801 // mksnapshot process would still be present in the unlinked snapshot data,
4802 // which would make snapshot production non-reproducible. This method wipes
4803 // out the to-be-overwritten header data for reproducible snapshots.
4804 inline void WipeOutHeader();
4806 // Flags operations.
4807 static inline Flags ComputeFlags(
4808 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4809 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4810 CacheHolderFlag holder = kCacheOnReceiver);
4812 static inline Flags ComputeMonomorphicFlags(
4813 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4814 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4816 static inline Flags ComputeHandlerFlags(
4817 Kind handler_kind, StubType type = NORMAL,
4818 CacheHolderFlag holder = kCacheOnReceiver);
4820 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4821 static inline StubType ExtractTypeFromFlags(Flags flags);
4822 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4823 static inline Kind ExtractKindFromFlags(Flags flags);
4824 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4826 static inline Flags RemoveTypeFromFlags(Flags flags);
4827 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4829 // Convert a target address into a code object.
4830 static inline Code* GetCodeFromTargetAddress(Address address);
4832 // Convert an entry address into an object.
4833 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4835 // Returns the address of the first instruction.
4836 inline byte* instruction_start();
4838 // Returns the address right after the last instruction.
4839 inline byte* instruction_end();
4841 // Returns the size of the instructions, padding, and relocation information.
4842 inline int body_size();
4844 // Returns the address of the first relocation info (read backwards!).
4845 inline byte* relocation_start();
4847 // Code entry point.
4848 inline byte* entry();
4850 // Returns true if pc is inside this object's instructions.
4851 inline bool contains(byte* pc);
4853 // Relocate the code by delta bytes. Called to signal that this code
4854 // object has been moved by delta bytes.
4855 void Relocate(intptr_t delta);
4857 // Migrate code described by desc.
4858 void CopyFrom(const CodeDesc& desc);
4860 // Returns the object size for a given body (used for allocation).
4861 static int SizeFor(int body_size) {
4862 DCHECK_SIZE_TAG_ALIGNED(body_size);
4863 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4866 // Calculate the size of the code object to report for log events. This takes
4867 // the layout of the code object into account.
4868 inline int ExecutableSize();
4870 // Locating source position.
4871 int SourcePosition(Address pc);
4872 int SourceStatementPosition(Address pc);
4876 // Dispatched behavior.
4877 inline int CodeSize();
4878 inline void CodeIterateBody(ObjectVisitor* v);
4880 template<typename StaticVisitor>
4881 inline void CodeIterateBody(Heap* heap);
4883 DECLARE_PRINTER(Code)
4884 DECLARE_VERIFIER(Code)
4886 void ClearInlineCaches();
4887 void ClearInlineCaches(Kind kind);
4889 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4890 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4892 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4894 kToBeExecutedOnceCodeAge = -3,
4895 kNotExecutedCodeAge = -2,
4896 kExecutedOnceCodeAge = -1,
4898 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4900 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4901 kLastCodeAge = kAfterLastCodeAge - 1,
4902 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4903 kIsOldCodeAge = kSexagenarianCodeAge,
4904 kPreAgedCodeAge = kIsOldCodeAge - 1
4906 #undef DECLARE_CODE_AGE_ENUM
4908 // Code aging. Indicates how many full GCs this code has survived without
4909 // being entered through the prologue. Used to determine when it is
4910 // relatively safe to flush this code object and replace it with the lazy
4911 // compilation stub.
4912 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4913 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4914 void MakeYoung(Isolate* isolate);
4915 void MarkToBeExecutedOnce(Isolate* isolate);
4916 void MakeOlder(MarkingParity);
4917 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4920 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4921 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4924 void PrintDeoptLocation(FILE* out, Address pc);
4925 bool CanDeoptAt(Address pc);
4928 void VerifyEmbeddedObjectsDependency();
4932 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4933 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4934 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4937 inline bool CanContainWeakObjects();
4939 inline bool IsWeakObject(Object* object);
4941 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4943 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4944 WeakCell* CachedWeakCell();
4946 // Max loop nesting marker used to postpose OSR. We don't take loop
4947 // nesting that is deeper than 5 levels into account.
4948 static const int kMaxLoopNestingMarker = 6;
4950 static const int kConstantPoolSize =
4951 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4953 // Layout description.
4954 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4955 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4956 static const int kDeoptimizationDataOffset =
4957 kHandlerTableOffset + kPointerSize;
4958 // For FUNCTION kind, we store the type feedback info here.
4959 static const int kTypeFeedbackInfoOffset =
4960 kDeoptimizationDataOffset + kPointerSize;
4961 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4962 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4963 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4964 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4965 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4966 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4967 static const int kKindSpecificFlags2Offset =
4968 kKindSpecificFlags1Offset + kIntSize;
4969 // Note: We might be able to squeeze this into the flags above.
4970 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4971 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4972 static const int kHeaderPaddingStart =
4973 kConstantPoolOffset + kConstantPoolSize;
4975 // Add padding to align the instruction start following right after
4976 // the Code object header.
4977 static const int kHeaderSize =
4978 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4980 // Byte offsets within kKindSpecificFlags1Offset.
4981 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4982 class FullCodeFlagsHasDeoptimizationSupportField:
4983 public BitField<bool, 0, 1> {}; // NOLINT
4984 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4985 class FullCodeFlagsHasRelocInfoForSerialization
4986 : public BitField<bool, 2, 1> {};
4987 // Bit 3 in this bitfield is unused.
4988 class ProfilerTicksField : public BitField<int, 4, 28> {};
4990 // Flags layout. BitField<type, shift, size>.
4991 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4992 class TypeField : public BitField<StubType, 4, 1> {};
4993 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4994 class KindField : public BitField<Kind, 7, 4> {};
4995 class ExtraICStateField: public BitField<ExtraICState, 11,
4996 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4998 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4999 static const int kStackSlotsFirstBit = 0;
5000 static const int kStackSlotsBitCount = 24;
5001 static const int kHasFunctionCacheBit =
5002 kStackSlotsFirstBit + kStackSlotsBitCount;
5003 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5004 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5005 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5007 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5008 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5010 class StackSlotsField: public BitField<int,
5011 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5012 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5014 class MarkedForDeoptimizationField
5015 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5016 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5018 class CanHaveWeakObjectsField
5019 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5021 // KindSpecificFlags2 layout (ALL)
5022 static const int kIsCrankshaftedBit = 0;
5023 class IsCrankshaftedField: public BitField<bool,
5024 kIsCrankshaftedBit, 1> {}; // NOLINT
5026 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5027 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5028 static const int kSafepointTableOffsetBitCount = 30;
5030 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5031 kSafepointTableOffsetBitCount <= 32);
5032 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5034 class SafepointTableOffsetField: public BitField<int,
5035 kSafepointTableOffsetFirstBit,
5036 kSafepointTableOffsetBitCount> {}; // NOLINT
5038 // KindSpecificFlags2 layout (FUNCTION)
5039 class BackEdgeTableOffsetField: public BitField<int,
5040 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5041 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5042 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5043 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5045 static const int kArgumentsBits = 16;
5046 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5048 // This constant should be encodable in an ARM instruction.
5049 static const int kFlagsNotUsedInLookup =
5050 TypeField::kMask | CacheHolderField::kMask;
5053 friend class RelocIterator;
5054 friend class Deoptimizer; // For FindCodeAgeSequence.
5056 void ClearInlineCaches(Kind* kind);
5059 byte* FindCodeAgeSequence();
5060 static void GetCodeAgeAndParity(Code* code, Age* age,
5061 MarkingParity* parity);
5062 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5063 MarkingParity* parity);
5064 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5066 // Code aging -- platform-specific
5067 static void PatchPlatformCodeAge(Isolate* isolate,
5068 byte* sequence, Age age,
5069 MarkingParity parity);
5071 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5075 // This class describes the layout of dependent codes array of a map. The
5076 // array is partitioned into several groups of dependent codes. Each group
5077 // contains codes with the same dependency on the map. The array has the
5078 // following layout for n dependency groups:
5080 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5081 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5082 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5084 // The first n elements are Smis, each of them specifies the number of codes
5085 // in the corresponding group. The subsequent elements contain grouped code
5086 // objects in weak cells. The suffix of the array can be filled with the
5087 // undefined value if the number of codes is less than the length of the
5088 // array. The order of the code objects within a group is not preserved.
5090 // All code indexes used in the class are counted starting from the first
5091 // code object of the first group. In other words, code index 0 corresponds
5092 // to array index n = kCodesStartIndex.
5094 class DependentCode: public FixedArray {
5096 enum DependencyGroup {
5097 // Group of code that weakly embed this map and depend on being
5098 // deoptimized when the map is garbage collected.
5100 // Group of code that embed a transition to this map, and depend on being
5101 // deoptimized when the transition is replaced by a new version.
5103 // Group of code that omit run-time prototype checks for prototypes
5104 // described by this map. The group is deoptimized whenever an object
5105 // described by this map changes shape (and transitions to a new map),
5106 // possibly invalidating the assumptions embedded in the code.
5107 kPrototypeCheckGroup,
5108 // Group of code that depends on global property values in property cells
5109 // not being changed.
5110 kPropertyCellChangedGroup,
5111 // Group of code that omit run-time type checks for the field(s) introduced
5114 // Group of code that omit run-time type checks for initial maps of
5116 kInitialMapChangedGroup,
5117 // Group of code that depends on tenuring information in AllocationSites
5118 // not being changed.
5119 kAllocationSiteTenuringChangedGroup,
5120 // Group of code that depends on element transition information in
5121 // AllocationSites not being changed.
5122 kAllocationSiteTransitionChangedGroup
5125 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5127 // Array for holding the index of the first code object of each group.
5128 // The last element stores the total number of code objects.
5129 class GroupStartIndexes {
5131 explicit GroupStartIndexes(DependentCode* entries);
5132 void Recompute(DependentCode* entries);
5133 int at(int i) { return start_indexes_[i]; }
5134 int number_of_entries() { return start_indexes_[kGroupCount]; }
5136 int start_indexes_[kGroupCount + 1];
5139 bool Contains(DependencyGroup group, WeakCell* code_cell);
5141 static Handle<DependentCode> InsertCompilationDependencies(
5142 Handle<DependentCode> entries, DependencyGroup group,
5143 Handle<Foreign> info);
5145 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5146 DependencyGroup group,
5147 Handle<WeakCell> code_cell);
5149 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5150 WeakCell* code_cell);
5152 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5155 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5156 DependentCode::DependencyGroup group);
5158 bool MarkCodeForDeoptimization(Isolate* isolate,
5159 DependentCode::DependencyGroup group);
5161 // The following low-level accessors should only be used by this class
5162 // and the mark compact collector.
5163 inline int number_of_entries(DependencyGroup group);
5164 inline void set_number_of_entries(DependencyGroup group, int value);
5165 inline Object* object_at(int i);
5166 inline void set_object_at(int i, Object* object);
5167 inline void clear_at(int i);
5168 inline void copy(int from, int to);
5169 DECLARE_CAST(DependentCode)
5171 static const char* DependencyGroupName(DependencyGroup group);
5172 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5175 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5176 DependencyGroup group,
5177 Handle<Object> object);
5178 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5179 // Make a room at the end of the given group by moving out the first
5180 // code objects of the subsequent groups.
5181 inline void ExtendGroup(DependencyGroup group);
5182 // Compact by removing cleared weak cells and return true if there was
5183 // any cleared weak cell.
5185 static int Grow(int number_of_entries) {
5186 if (number_of_entries < 5) return number_of_entries + 1;
5187 return number_of_entries * 5 / 4;
5189 static const int kCodesStartIndex = kGroupCount;
5193 class PrototypeInfo;
5196 // All heap objects have a Map that describes their structure.
5197 // A Map contains information about:
5198 // - Size information about the object
5199 // - How to iterate over an object (for garbage collection)
5200 class Map: public HeapObject {
5203 // Size in bytes or kVariableSizeSentinel if instances do not have
5205 inline int instance_size();
5206 inline void set_instance_size(int value);
5208 // Only to clear an unused byte, remove once byte is used.
5209 inline void clear_unused();
5211 // [inobject_properties_or_constructor_function_index]: Provides access
5212 // to the inobject properties in case of JSObject maps, or the constructor
5213 // function index in case of primitive maps.
5214 inline int inobject_properties_or_constructor_function_index();
5215 inline void set_inobject_properties_or_constructor_function_index(int value);
5216 // Count of properties allocated in the object (JSObject only).
5217 inline int GetInObjectProperties();
5218 inline void SetInObjectProperties(int value);
5219 // Index of the constructor function in the native context (primitives only),
5220 // or the special sentinel value to indicate that there is no object wrapper
5221 // for the primitive (i.e. in case of null or undefined).
5222 static const int kNoConstructorFunctionIndex = 0;
5223 inline int GetConstructorFunctionIndex();
5224 inline void SetConstructorFunctionIndex(int value);
5227 inline InstanceType instance_type();
5228 inline void set_instance_type(InstanceType value);
5230 // Tells how many unused property fields are available in the
5231 // instance (only used for JSObject in fast mode).
5232 inline int unused_property_fields();
5233 inline void set_unused_property_fields(int value);
5236 inline byte bit_field() const;
5237 inline void set_bit_field(byte value);
5240 inline byte bit_field2() const;
5241 inline void set_bit_field2(byte value);
5244 inline uint32_t bit_field3() const;
5245 inline void set_bit_field3(uint32_t bits);
5247 class EnumLengthBits: public BitField<int,
5248 0, kDescriptorIndexBitCount> {}; // NOLINT
5249 class NumberOfOwnDescriptorsBits: public BitField<int,
5250 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5251 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5252 class DictionaryMap : public BitField<bool, 20, 1> {};
5253 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5254 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5255 class Deprecated : public BitField<bool, 23, 1> {};
5256 class IsUnstable : public BitField<bool, 24, 1> {};
5257 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5258 class IsStrong : public BitField<bool, 26, 1> {};
5261 // Keep this bit field at the very end for better code in
5262 // Builtins::kJSConstructStubGeneric stub.
5263 // This counter is used for in-object slack tracking and for map aging.
5264 // The in-object slack tracking is considered enabled when the counter is
5265 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5266 class Counter : public BitField<int, 28, 4> {};
5267 static const int kSlackTrackingCounterStart = 14;
5268 static const int kSlackTrackingCounterEnd = 8;
5269 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5270 static const int kRetainingCounterEnd = 0;
5272 // Tells whether the object in the prototype property will be used
5273 // for instances created from this function. If the prototype
5274 // property is set to a value that is not a JSObject, the prototype
5275 // property will not be used to create instances of the function.
5276 // See ECMA-262, 13.2.2.
5277 inline void set_non_instance_prototype(bool value);
5278 inline bool has_non_instance_prototype();
5280 // Tells whether function has special prototype property. If not, prototype
5281 // property will not be created when accessed (will return undefined),
5282 // and construction from this function will not be allowed.
5283 inline void set_function_with_prototype(bool value);
5284 inline bool function_with_prototype();
5286 // Tells whether the instance with this map should be ignored by the
5287 // Object.getPrototypeOf() function and the __proto__ accessor.
5288 inline void set_is_hidden_prototype();
5289 inline bool is_hidden_prototype() const;
5291 // Records and queries whether the instance has a named interceptor.
5292 inline void set_has_named_interceptor();
5293 inline bool has_named_interceptor();
5295 // Records and queries whether the instance has an indexed interceptor.
5296 inline void set_has_indexed_interceptor();
5297 inline bool has_indexed_interceptor();
5299 // Tells whether the instance is undetectable.
5300 // An undetectable object is a special class of JSObject: 'typeof' operator
5301 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5302 // a normal JS object. It is useful for implementing undetectable
5303 // document.all in Firefox & Safari.
5304 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5305 inline void set_is_undetectable();
5306 inline bool is_undetectable();
5308 // Tells whether the instance has a call-as-function handler.
5309 inline void set_is_observed();
5310 inline bool is_observed();
5312 // Tells whether the instance has a [[Call]] internal field.
5313 // This property is implemented according to ES6, section 7.2.3.
5314 inline void set_is_callable();
5315 inline bool is_callable() const;
5317 inline void set_is_strong();
5318 inline bool is_strong();
5319 inline void set_is_extensible(bool value);
5320 inline bool is_extensible();
5321 inline void set_is_prototype_map(bool value);
5322 inline bool is_prototype_map() const;
5324 inline void set_elements_kind(ElementsKind elements_kind);
5325 inline ElementsKind elements_kind();
5327 // Tells whether the instance has fast elements that are only Smis.
5328 inline bool has_fast_smi_elements();
5330 // Tells whether the instance has fast elements.
5331 inline bool has_fast_object_elements();
5332 inline bool has_fast_smi_or_object_elements();
5333 inline bool has_fast_double_elements();
5334 inline bool has_fast_elements();
5335 inline bool has_sloppy_arguments_elements();
5336 inline bool has_fixed_typed_array_elements();
5337 inline bool has_dictionary_elements();
5339 static bool IsValidElementsTransition(ElementsKind from_kind,
5340 ElementsKind to_kind);
5342 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5343 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5344 bool DictionaryElementsInPrototypeChainOnly();
5346 inline Map* ElementsTransitionMap();
5348 inline FixedArrayBase* GetInitialElements();
5350 // [raw_transitions]: Provides access to the transitions storage field.
5351 // Don't call set_raw_transitions() directly to overwrite transitions, use
5352 // the TransitionArray::ReplaceTransitions() wrapper instead!
5353 DECL_ACCESSORS(raw_transitions, Object)
5354 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5355 // (which prototype maps don't have).
5356 DECL_ACCESSORS(prototype_info, Object)
5357 // PrototypeInfo is created lazily using this helper (which installs it on
5358 // the given prototype's map).
5359 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5360 Handle<JSObject> prototype, Isolate* isolate);
5361 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5362 Handle<Map> prototype_map, Isolate* isolate);
5364 // [prototype chain validity cell]: Associated with a prototype object,
5365 // stored in that object's map's PrototypeInfo, indicates that prototype
5366 // chains through this object are currently valid. The cell will be
5367 // invalidated and replaced when the prototype chain changes.
5368 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5370 static const int kPrototypeChainValid = 0;
5371 static const int kPrototypeChainInvalid = 1;
5374 Map* FindFieldOwner(int descriptor);
5376 inline int GetInObjectPropertyOffset(int index);
5378 int NumberOfFields();
5380 // TODO(ishell): candidate with JSObject::MigrateToMap().
5381 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5382 int target_inobject, int target_unused,
5383 int* old_number_of_fields);
5384 // TODO(ishell): moveit!
5385 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5386 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5387 Handle<HeapType> type1,
5388 Handle<HeapType> type2,
5390 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5391 Representation new_representation,
5392 Handle<HeapType> new_field_type);
5393 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5394 PropertyKind new_kind,
5395 PropertyAttributes new_attributes,
5396 Representation new_representation,
5397 Handle<HeapType> new_field_type,
5398 StoreMode store_mode);
5399 static Handle<Map> CopyGeneralizeAllRepresentations(
5400 Handle<Map> map, int modify_index, StoreMode store_mode,
5401 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5403 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5404 int descriptor_number,
5405 Handle<Object> value);
5407 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5408 const char* reason);
5410 // Returns the constructor name (the name (possibly, inferred name) of the
5411 // function that was used to instantiate the object).
5412 String* constructor_name();
5414 // Tells whether the map is used for JSObjects in dictionary mode (ie
5415 // normalized objects, ie objects for which HasFastProperties returns false).
5416 // A map can never be used for both dictionary mode and fast mode JSObjects.
5417 // False by default and for HeapObjects that are not JSObjects.
5418 inline void set_dictionary_map(bool value);
5419 inline bool is_dictionary_map();
5421 // Tells whether the instance needs security checks when accessing its
5423 inline void set_is_access_check_needed(bool access_check_needed);
5424 inline bool is_access_check_needed();
5426 // Returns true if map has a non-empty stub code cache.
5427 inline bool has_code_cache();
5429 // [prototype]: implicit prototype object.
5430 DECL_ACCESSORS(prototype, Object)
5431 // TODO(jkummerow): make set_prototype private.
5432 static void SetPrototype(
5433 Handle<Map> map, Handle<Object> prototype,
5434 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5436 // [constructor]: points back to the function responsible for this map.
5437 // The field overlaps with the back pointer. All maps in a transition tree
5438 // have the same constructor, so maps with back pointers can walk the
5439 // back pointer chain until they find the map holding their constructor.
5440 DECL_ACCESSORS(constructor_or_backpointer, Object)
5441 inline Object* GetConstructor() const;
5442 inline void SetConstructor(Object* constructor,
5443 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5444 // [back pointer]: points back to the parent map from which a transition
5445 // leads to this map. The field overlaps with the constructor (see above).
5446 inline Object* GetBackPointer();
5447 inline void SetBackPointer(Object* value,
5448 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5450 // [instance descriptors]: describes the object.
5451 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5453 // [layout descriptor]: describes the object layout.
5454 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5455 // |layout descriptor| accessor which can be used from GC.
5456 inline LayoutDescriptor* layout_descriptor_gc_safe();
5457 inline bool HasFastPointerLayout() const;
5459 // |layout descriptor| accessor that is safe to call even when
5460 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5461 // |layout_descriptor| field at all).
5462 inline LayoutDescriptor* GetLayoutDescriptor();
5464 inline void UpdateDescriptors(DescriptorArray* descriptors,
5465 LayoutDescriptor* layout_descriptor);
5466 inline void InitializeDescriptors(DescriptorArray* descriptors,
5467 LayoutDescriptor* layout_descriptor);
5469 // [stub cache]: contains stubs compiled for this map.
5470 DECL_ACCESSORS(code_cache, Object)
5472 // [dependent code]: list of optimized codes that weakly embed this map.
5473 DECL_ACCESSORS(dependent_code, DependentCode)
5475 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5476 DECL_ACCESSORS(weak_cell_cache, Object)
5478 inline PropertyDetails GetLastDescriptorDetails();
5480 inline int LastAdded();
5482 inline int NumberOfOwnDescriptors();
5483 inline void SetNumberOfOwnDescriptors(int number);
5485 inline Cell* RetrieveDescriptorsPointer();
5487 inline int EnumLength();
5488 inline void SetEnumLength(int length);
5490 inline bool owns_descriptors();
5491 inline void set_owns_descriptors(bool owns_descriptors);
5492 inline void mark_unstable();
5493 inline bool is_stable();
5494 inline void set_migration_target(bool value);
5495 inline bool is_migration_target();
5496 inline void set_counter(int value);
5497 inline int counter();
5498 inline void deprecate();
5499 inline bool is_deprecated();
5500 inline bool CanBeDeprecated();
5501 // Returns a non-deprecated version of the input. If the input was not
5502 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5503 // is found by re-transitioning from the root of the transition tree using the
5504 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5506 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5508 // Returns a non-deprecated version of the input. This method may deprecate
5509 // existing maps along the way if encodings conflict. Not for use while
5510 // gathering type feedback. Use TryUpdate in those cases instead.
5511 static Handle<Map> Update(Handle<Map> map);
5513 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5514 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5515 Descriptor* descriptor,
5516 TransitionFlag flag);
5518 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5521 Handle<HeapType> type,
5522 PropertyAttributes attributes,
5523 Representation representation,
5524 TransitionFlag flag);
5526 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5529 Handle<Object> constant,
5530 PropertyAttributes attributes,
5531 TransitionFlag flag);
5533 // Returns a new map with all transitions dropped from the given map and
5534 // the ElementsKind set.
5535 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5536 ElementsKind to_kind);
5538 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5540 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5542 TransitionFlag flag);
5544 static Handle<Map> CopyForObserved(Handle<Map> map);
5546 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5547 PropertyAttributes attrs_to_add,
5548 Handle<Symbol> transition_marker,
5549 const char* reason);
5551 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5554 // Maximal number of fast properties. Used to restrict the number of map
5555 // transitions to avoid an explosion in the number of maps for objects used as
5557 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5558 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5560 Handle<Object> value,
5561 PropertyAttributes attributes,
5562 StoreFromKeyed store_mode);
5563 static Handle<Map> TransitionToAccessorProperty(
5564 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5565 Handle<Object> accessor, PropertyAttributes attributes);
5566 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5569 PropertyAttributes attributes);
5571 inline void AppendDescriptor(Descriptor* desc);
5573 // Returns a copy of the map, prepared for inserting into the transition
5574 // tree (if the |map| owns descriptors then the new one will share
5575 // descriptors with |map|).
5576 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5578 // Returns a copy of the map, with all transitions dropped from the
5579 // instance descriptors.
5580 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5581 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5583 // Returns the next free property index (only valid for FAST MODE).
5584 int NextFreePropertyIndex();
5586 // Returns the number of properties described in instance_descriptors
5587 // filtering out properties with the specified attributes.
5588 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5589 PropertyAttributes filter = NONE);
5593 // Code cache operations.
5595 // Clears the code cache.
5596 inline void ClearCodeCache(Heap* heap);
5598 // Update code cache.
5599 static void UpdateCodeCache(Handle<Map> map,
5603 // Extend the descriptor array of the map with the list of descriptors.
5604 // In case of duplicates, the latest descriptor is used.
5605 static void AppendCallbackDescriptors(Handle<Map> map,
5606 Handle<Object> descriptors);
5608 static inline int SlackForArraySize(int old_size, int size_limit);
5610 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5612 // Returns the found code or undefined if absent.
5613 Object* FindInCodeCache(Name* name, Code::Flags flags);
5615 // Returns the non-negative index of the code object if it is in the
5616 // cache and -1 otherwise.
5617 int IndexInCodeCache(Object* name, Code* code);
5619 // Removes a code object from the code cache at the given index.
5620 void RemoveFromCodeCache(Name* name, Code* code, int index);
5622 // Computes a hash value for this map, to be used in HashTables and such.
5625 // Returns the map that this map transitions to if its elements_kind
5626 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5627 // |safe_to_add_transitions| is set to false if adding transitions is not
5629 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5631 // Returns the transitioned map for this map with the most generic
5632 // elements_kind that's found in |candidates|, or null handle if no match is
5634 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5635 MapHandleList* candidates);
5637 inline bool CanTransition();
5639 inline bool IsPrimitiveMap();
5640 inline bool IsJSObjectMap();
5641 inline bool IsJSArrayMap();
5642 inline bool IsStringMap();
5643 inline bool IsJSProxyMap();
5644 inline bool IsJSGlobalProxyMap();
5645 inline bool IsJSGlobalObjectMap();
5646 inline bool IsGlobalObjectMap();
5648 inline bool CanOmitMapChecks();
5650 static void AddDependentCode(Handle<Map> map,
5651 DependentCode::DependencyGroup group,
5654 bool IsMapInArrayPrototypeChain();
5656 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5658 // Dispatched behavior.
5659 DECLARE_PRINTER(Map)
5660 DECLARE_VERIFIER(Map)
5663 void DictionaryMapVerify();
5664 void VerifyOmittedMapChecks();
5667 inline int visitor_id();
5668 inline void set_visitor_id(int visitor_id);
5670 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5671 Handle<Object> prototype,
5672 PrototypeOptimizationMode mode);
5674 static const int kMaxPreAllocatedPropertyFields = 255;
5676 // Layout description.
5677 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5678 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5679 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5680 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5681 static const int kConstructorOrBackPointerOffset =
5682 kPrototypeOffset + kPointerSize;
5683 // When there is only one transition, it is stored directly in this field;
5684 // otherwise a transition array is used.
5685 // For prototype maps, this slot is used to store this map's PrototypeInfo
5687 static const int kTransitionsOrPrototypeInfoOffset =
5688 kConstructorOrBackPointerOffset + kPointerSize;
5689 static const int kDescriptorsOffset =
5690 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5691 #if V8_DOUBLE_FIELDS_UNBOXING
5692 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5693 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5695 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5696 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5698 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5699 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5700 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5702 // Layout of pointer fields. Heap iteration code relies on them
5703 // being continuously allocated.
5704 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5705 static const int kPointerFieldsEndOffset = kSize;
5707 // Byte offsets within kInstanceSizesOffset.
5708 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5709 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5710 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5711 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5712 // Note there is one byte available for use here.
5713 static const int kUnusedByte = 2;
5714 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5715 static const int kVisitorIdByte = 3;
5716 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5718 // Byte offsets within kInstanceAttributesOffset attributes.
5719 #if V8_TARGET_LITTLE_ENDIAN
5720 // Order instance type and bit field together such that they can be loaded
5721 // together as a 16-bit word with instance type in the lower 8 bits regardless
5722 // of endianess. Also provide endian-independent offset to that 16-bit word.
5723 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5724 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5726 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5727 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5729 static const int kInstanceTypeAndBitFieldOffset =
5730 kInstanceAttributesOffset + 0;
5731 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5732 static const int kUnusedPropertyFieldsByte = 3;
5733 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5735 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5736 Internals::kMapInstanceTypeAndBitFieldOffset);
5738 // Bit positions for bit field.
5739 static const int kHasNonInstancePrototype = 0;
5740 static const int kIsCallable = 1;
5741 static const int kHasNamedInterceptor = 2;
5742 static const int kHasIndexedInterceptor = 3;
5743 static const int kIsUndetectable = 4;
5744 static const int kIsObserved = 5;
5745 static const int kIsAccessCheckNeeded = 6;
5746 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5748 // Bit positions for bit field 2
5749 static const int kIsExtensible = 0;
5750 static const int kStringWrapperSafeForDefaultValueOf = 1;
5751 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5752 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5754 // Derived values from bit field 2
5755 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5756 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5757 static const int8_t kMaximumBitField2FastSmiElementValue =
5758 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5759 Map::ElementsKindBits::kShift) - 1;
5760 static const int8_t kMaximumBitField2FastHoleyElementValue =
5761 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5762 Map::ElementsKindBits::kShift) - 1;
5763 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5764 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5765 Map::ElementsKindBits::kShift) - 1;
5767 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5768 kPointerFieldsEndOffset,
5769 kSize> BodyDescriptor;
5771 // Compares this map to another to see if they describe equivalent objects.
5772 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5773 // it had exactly zero inobject properties.
5774 // The "shared" flags of both this map and |other| are ignored.
5775 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5777 // Returns true if given field is unboxed double.
5778 inline bool IsUnboxedDoubleField(FieldIndex index);
5781 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5782 static void TraceAllTransitions(Map* map);
5785 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5786 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5787 Handle<LayoutDescriptor> layout_descriptor);
5790 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5791 Handle<Name> name, SimpleTransitionFlag flag);
5793 bool EquivalentToForTransition(Map* other);
5794 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5795 static Handle<Map> ShareDescriptor(Handle<Map> map,
5796 Handle<DescriptorArray> descriptors,
5797 Descriptor* descriptor);
5798 static Handle<Map> CopyInstallDescriptors(
5799 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5800 Handle<LayoutDescriptor> layout_descriptor);
5801 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5802 Descriptor* descriptor,
5803 TransitionFlag flag);
5804 static Handle<Map> CopyReplaceDescriptors(
5805 Handle<Map> map, Handle<DescriptorArray> descriptors,
5806 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5807 MaybeHandle<Name> maybe_name, const char* reason,
5808 SimpleTransitionFlag simple_flag);
5810 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5811 Handle<DescriptorArray> descriptors,
5812 Descriptor* descriptor,
5814 TransitionFlag flag);
5815 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5816 Handle<Map> map, int descriptor, PropertyKind kind,
5817 PropertyAttributes attributes, const char** reason);
5819 static Handle<Map> CopyNormalized(Handle<Map> map,
5820 PropertyNormalizationMode mode);
5822 // Fires when the layout of an object with a leaf map changes.
5823 // This includes adding transitions to the leaf map or changing
5824 // the descriptor array.
5825 inline void NotifyLeafMapLayoutChange();
5827 void DeprecateTransitionTree();
5828 bool DeprecateTarget(PropertyKind kind, Name* key,
5829 PropertyAttributes attributes,
5830 DescriptorArray* new_descriptors,
5831 LayoutDescriptor* new_layout_descriptor);
5833 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5835 // Update field type of the given descriptor to new representation and new
5836 // type. The type must be prepared for storing in descriptor array:
5837 // it must be either a simple type or a map wrapped in a weak cell.
5838 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5839 Representation new_representation,
5840 Handle<Object> new_wrapped_type);
5842 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5843 PropertyAttributes attributes);
5844 void PrintGeneralization(FILE* file,
5849 bool constant_to_field,
5850 Representation old_representation,
5851 Representation new_representation,
5852 HeapType* old_field_type,
5853 HeapType* new_field_type);
5855 static const int kFastPropertiesSoftLimit = 12;
5856 static const int kMaxFastProperties = 128;
5858 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5862 // An abstract superclass, a marker class really, for simple structure classes.
5863 // It doesn't carry much functionality but allows struct classes to be
5864 // identified in the type system.
5865 class Struct: public HeapObject {
5867 inline void InitializeBody(int object_size);
5868 DECLARE_CAST(Struct)
5872 // A simple one-element struct, useful where smis need to be boxed.
5873 class Box : public Struct {
5875 // [value]: the boxed contents.
5876 DECL_ACCESSORS(value, Object)
5880 // Dispatched behavior.
5881 DECLARE_PRINTER(Box)
5882 DECLARE_VERIFIER(Box)
5884 static const int kValueOffset = HeapObject::kHeaderSize;
5885 static const int kSize = kValueOffset + kPointerSize;
5888 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5892 // Container for metadata stored on each prototype map.
5893 class PrototypeInfo : public Struct {
5895 static const int UNREGISTERED = -1;
5897 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5898 // or Smi(0) if uninitialized.
5899 DECL_ACCESSORS(prototype_users, Object)
5900 // [registry_slot]: Slot in prototype's user registry where this user
5901 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5902 inline int registry_slot() const;
5903 inline void set_registry_slot(int slot);
5904 // [validity_cell]: Cell containing the validity bit for prototype chains
5905 // going through this object, or Smi(0) if uninitialized.
5906 DECL_ACCESSORS(validity_cell, Object)
5907 // [constructor_name]: User-friendly name of the original constructor.
5908 DECL_ACCESSORS(constructor_name, Object)
5910 DECLARE_CAST(PrototypeInfo)
5912 // Dispatched behavior.
5913 DECLARE_PRINTER(PrototypeInfo)
5914 DECLARE_VERIFIER(PrototypeInfo)
5916 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5917 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5918 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5919 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5920 static const int kSize = kConstructorNameOffset + kPointerSize;
5923 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5927 // Pair used to store both a ScopeInfo and an extension object in the extension
5928 // slot of a block context. Needed in the rare case where a declaration block
5929 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5930 // a sloppy direct eval. (In no other case both are needed at the same time.)
5931 class SloppyBlockWithEvalContextExtension : public Struct {
5933 // [scope_info]: Scope info.
5934 DECL_ACCESSORS(scope_info, ScopeInfo)
5935 // [extension]: Extension object.
5936 DECL_ACCESSORS(extension, JSObject)
5938 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5940 // Dispatched behavior.
5941 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5942 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5944 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5945 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5946 static const int kSize = kExtensionOffset + kPointerSize;
5949 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5953 // Script describes a script which has been added to the VM.
5954 class Script: public Struct {
5963 // Script compilation types.
5964 enum CompilationType {
5965 COMPILATION_TYPE_HOST = 0,
5966 COMPILATION_TYPE_EVAL = 1
5969 // Script compilation state.
5970 enum CompilationState {
5971 COMPILATION_STATE_INITIAL = 0,
5972 COMPILATION_STATE_COMPILED = 1
5975 // [source]: the script source.
5976 DECL_ACCESSORS(source, Object)
5978 // [name]: the script name.
5979 DECL_ACCESSORS(name, Object)
5981 // [id]: the script id.
5982 DECL_ACCESSORS(id, Smi)
5984 // [line_offset]: script line offset in resource from where it was extracted.
5985 DECL_ACCESSORS(line_offset, Smi)
5987 // [column_offset]: script column offset in resource from where it was
5989 DECL_ACCESSORS(column_offset, Smi)
5991 // [context_data]: context data for the context this script was compiled in.
5992 DECL_ACCESSORS(context_data, Object)
5994 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5995 DECL_ACCESSORS(wrapper, HeapObject)
5997 // [type]: the script type.
5998 DECL_ACCESSORS(type, Smi)
6000 // [line_ends]: FixedArray of line ends positions.
6001 DECL_ACCESSORS(line_ends, Object)
6003 // [eval_from_shared]: for eval scripts the shared funcion info for the
6004 // function from which eval was called.
6005 DECL_ACCESSORS(eval_from_shared, Object)
6007 // [eval_from_instructions_offset]: the instruction offset in the code for the
6008 // function from which eval was called where eval was called.
6009 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6011 // [shared_function_infos]: weak fixed array containing all shared
6012 // function infos created from this script.
6013 DECL_ACCESSORS(shared_function_infos, Object)
6015 // [flags]: Holds an exciting bitfield.
6016 DECL_ACCESSORS(flags, Smi)
6018 // [source_url]: sourceURL from magic comment
6019 DECL_ACCESSORS(source_url, Object)
6021 // [source_url]: sourceMappingURL magic comment
6022 DECL_ACCESSORS(source_mapping_url, Object)
6024 // [compilation_type]: how the the script was compiled. Encoded in the
6026 inline CompilationType compilation_type();
6027 inline void set_compilation_type(CompilationType type);
6029 // [compilation_state]: determines whether the script has already been
6030 // compiled. Encoded in the 'flags' field.
6031 inline CompilationState compilation_state();
6032 inline void set_compilation_state(CompilationState state);
6034 // [hide_source]: determines whether the script source can be exposed as
6035 // function source. Encoded in the 'flags' field.
6036 inline bool hide_source();
6037 inline void set_hide_source(bool value);
6039 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6040 // and used by the embedder to make decisions about the script. V8 just passes
6041 // this through. Encoded in the 'flags' field.
6042 inline v8::ScriptOriginOptions origin_options();
6043 inline void set_origin_options(ScriptOriginOptions origin_options);
6045 DECLARE_CAST(Script)
6047 // If script source is an external string, check that the underlying
6048 // resource is accessible. Otherwise, always return true.
6049 inline bool HasValidSource();
6051 // Convert code position into column number.
6052 static int GetColumnNumber(Handle<Script> script, int code_pos);
6054 // Convert code position into (zero-based) line number.
6055 // The non-handlified version does not allocate, but may be much slower.
6056 static int GetLineNumber(Handle<Script> script, int code_pos);
6057 int GetLineNumber(int code_pos);
6059 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6061 // Init line_ends array with code positions of line ends inside script source.
6062 static void InitLineEnds(Handle<Script> script);
6064 // Get the JS object wrapping the given script; create it if none exists.
6065 static Handle<JSObject> GetWrapper(Handle<Script> script);
6067 // Look through the list of existing shared function infos to find one
6068 // that matches the function literal. Return empty handle if not found.
6069 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6071 // Iterate over all script objects on the heap.
6074 explicit Iterator(Isolate* isolate);
6078 WeakFixedArray::Iterator iterator_;
6079 DISALLOW_COPY_AND_ASSIGN(Iterator);
6082 // Dispatched behavior.
6083 DECLARE_PRINTER(Script)
6084 DECLARE_VERIFIER(Script)
6086 static const int kSourceOffset = HeapObject::kHeaderSize;
6087 static const int kNameOffset = kSourceOffset + kPointerSize;
6088 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6089 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6090 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6091 static const int kWrapperOffset = kContextOffset + kPointerSize;
6092 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6093 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6094 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6095 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6096 static const int kEvalFrominstructionsOffsetOffset =
6097 kEvalFromSharedOffset + kPointerSize;
6098 static const int kSharedFunctionInfosOffset =
6099 kEvalFrominstructionsOffsetOffset + kPointerSize;
6100 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6101 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6102 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6103 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6106 int GetLineNumberWithArray(int code_pos);
6108 // Bit positions in the flags field.
6109 static const int kCompilationTypeBit = 0;
6110 static const int kCompilationStateBit = 1;
6111 static const int kHideSourceBit = 2;
6112 static const int kOriginOptionsShift = 3;
6113 static const int kOriginOptionsSize = 3;
6114 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6115 << kOriginOptionsShift;
6117 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6121 // List of builtin functions we want to identify to improve code
6124 // Each entry has a name of a global object property holding an object
6125 // optionally followed by ".prototype", a name of a builtin function
6126 // on the object (the one the id is set for), and a label.
6128 // Installation of ids for the selected builtin functions is handled
6129 // by the bootstrapper.
6130 #define FUNCTIONS_WITH_ID_LIST(V) \
6131 V(Array.prototype, indexOf, ArrayIndexOf) \
6132 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6133 V(Array.prototype, push, ArrayPush) \
6134 V(Array.prototype, pop, ArrayPop) \
6135 V(Array.prototype, shift, ArrayShift) \
6136 V(Function.prototype, apply, FunctionApply) \
6137 V(Function.prototype, call, FunctionCall) \
6138 V(String.prototype, charCodeAt, StringCharCodeAt) \
6139 V(String.prototype, charAt, StringCharAt) \
6140 V(String, fromCharCode, StringFromCharCode) \
6141 V(Math, random, MathRandom) \
6142 V(Math, floor, MathFloor) \
6143 V(Math, round, MathRound) \
6144 V(Math, ceil, MathCeil) \
6145 V(Math, abs, MathAbs) \
6146 V(Math, log, MathLog) \
6147 V(Math, exp, MathExp) \
6148 V(Math, sqrt, MathSqrt) \
6149 V(Math, pow, MathPow) \
6150 V(Math, max, MathMax) \
6151 V(Math, min, MathMin) \
6152 V(Math, cos, MathCos) \
6153 V(Math, sin, MathSin) \
6154 V(Math, tan, MathTan) \
6155 V(Math, acos, MathAcos) \
6156 V(Math, asin, MathAsin) \
6157 V(Math, atan, MathAtan) \
6158 V(Math, atan2, MathAtan2) \
6159 V(Math, imul, MathImul) \
6160 V(Math, clz32, MathClz32) \
6161 V(Math, fround, MathFround)
6163 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6164 V(Atomics, load, AtomicsLoad) \
6165 V(Atomics, store, AtomicsStore)
6167 enum BuiltinFunctionId {
6169 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6171 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6172 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6173 #undef DECLARE_FUNCTION_ID
6174 // Fake id for a special case of Math.pow. Note, it continues the
6175 // list of math functions.
6180 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6181 // that both {code} and {literals} can be NULL to pass search result status.
6182 struct CodeAndLiterals {
6183 Code* code; // Cached optimized code.
6184 FixedArray* literals; // Cached literals array.
6188 // SharedFunctionInfo describes the JSFunction information that can be
6189 // shared by multiple instances of the function.
6190 class SharedFunctionInfo: public HeapObject {
6192 // [name]: Function name.
6193 DECL_ACCESSORS(name, Object)
6195 // [code]: Function code.
6196 DECL_ACCESSORS(code, Code)
6197 inline void ReplaceCode(Code* code);
6199 // [optimized_code_map]: Map from native context to optimized code
6200 // and a shared literals array or Smi(0) if none.
6201 DECL_ACCESSORS(optimized_code_map, Object)
6203 // Returns entry from optimized code map for specified context and OSR entry.
6204 // Note that {code == nullptr} indicates no matching entry has been found,
6205 // whereas {literals == nullptr} indicates the code is context-independent.
6206 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6207 BailoutId osr_ast_id);
6209 // Clear optimized code map.
6210 void ClearOptimizedCodeMap();
6212 // Removed a specific optimized code object from the optimized code map.
6213 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6215 // Trims the optimized code map after entries have been removed.
6216 void TrimOptimizedCodeMap(int shrink_by);
6218 // Add a new entry to the optimized code map for context-independent code.
6219 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6222 // Add a new entry to the optimized code map for context-dependent code.
6223 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6224 Handle<Context> native_context,
6226 Handle<FixedArray> literals,
6227 BailoutId osr_ast_id);
6229 // Set up the link between shared function info and the script. The shared
6230 // function info is added to the list on the script.
6231 static void SetScript(Handle<SharedFunctionInfo> shared,
6232 Handle<Object> script_object);
6234 // Layout description of the optimized code map.
6235 static const int kNextMapIndex = 0;
6236 static const int kSharedCodeIndex = 1;
6237 static const int kEntriesStart = 2;
6238 static const int kContextOffset = 0;
6239 static const int kCachedCodeOffset = 1;
6240 static const int kLiteralsOffset = 2;
6241 static const int kOsrAstIdOffset = 3;
6242 static const int kEntryLength = 4;
6243 static const int kInitialLength = kEntriesStart + kEntryLength;
6245 // [scope_info]: Scope info.
6246 DECL_ACCESSORS(scope_info, ScopeInfo)
6248 // [construct stub]: Code stub for constructing instances of this function.
6249 DECL_ACCESSORS(construct_stub, Code)
6251 // Returns if this function has been compiled to native code yet.
6252 inline bool is_compiled();
6254 // [length]: The function length - usually the number of declared parameters.
6255 // Use up to 2^30 parameters.
6256 inline int length() const;
6257 inline void set_length(int value);
6259 // [internal formal parameter count]: The declared number of parameters.
6260 // For subclass constructors, also includes new.target.
6261 // The size of function's frame is internal_formal_parameter_count + 1.
6262 inline int internal_formal_parameter_count() const;
6263 inline void set_internal_formal_parameter_count(int value);
6265 // Set the formal parameter count so the function code will be
6266 // called without using argument adaptor frames.
6267 inline void DontAdaptArguments();
6269 // [expected_nof_properties]: Expected number of properties for the function.
6270 inline int expected_nof_properties() const;
6271 inline void set_expected_nof_properties(int value);
6273 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6274 // (increasingly) from crankshafted code where sufficient feedback isn't
6276 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6278 // Unconditionally clear the type feedback vector (including vector ICs).
6279 void ClearTypeFeedbackInfo();
6281 // Clear the type feedback vector with a more subtle policy at GC time.
6282 void ClearTypeFeedbackInfoAtGCTime();
6285 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6286 // even if the GC moves this SharedFunctionInfo.
6287 inline int unique_id() const;
6288 inline void set_unique_id(int value);
6291 // [instance class name]: class name for instances.
6292 DECL_ACCESSORS(instance_class_name, Object)
6294 // [function data]: This field holds some additional data for function.
6295 // Currently it has one of:
6296 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6297 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6298 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6299 // In the long run we don't want all functions to have this field but
6300 // we can fix that when we have a better model for storing hidden data
6302 DECL_ACCESSORS(function_data, Object)
6304 inline bool IsApiFunction();
6305 inline FunctionTemplateInfo* get_api_func_data();
6306 inline bool HasBuiltinFunctionId();
6307 inline BuiltinFunctionId builtin_function_id();
6308 inline bool HasBytecodeArray();
6309 inline BytecodeArray* bytecode_array();
6311 // [script info]: Script from which the function originates.
6312 DECL_ACCESSORS(script, Object)
6314 // [num_literals]: Number of literals used by this function.
6315 inline int num_literals() const;
6316 inline void set_num_literals(int value);
6318 // [start_position_and_type]: Field used to store both the source code
6319 // position, whether or not the function is a function expression,
6320 // and whether or not the function is a toplevel function. The two
6321 // least significants bit indicates whether the function is an
6322 // expression and the rest contains the source code position.
6323 inline int start_position_and_type() const;
6324 inline void set_start_position_and_type(int value);
6326 // The function is subject to debugging if a debug info is attached.
6327 inline bool HasDebugInfo();
6328 inline DebugInfo* GetDebugInfo();
6330 // A function has debug code if the compiled code has debug break slots.
6331 inline bool HasDebugCode();
6333 // [debug info]: Debug information.
6334 DECL_ACCESSORS(debug_info, Object)
6336 // [inferred name]: Name inferred from variable or property
6337 // assignment of this function. Used to facilitate debugging and
6338 // profiling of JavaScript code written in OO style, where almost
6339 // all functions are anonymous but are assigned to object
6341 DECL_ACCESSORS(inferred_name, String)
6343 // The function's name if it is non-empty, otherwise the inferred name.
6344 String* DebugName();
6346 // Position of the 'function' token in the script source.
6347 inline int function_token_position() const;
6348 inline void set_function_token_position(int function_token_position);
6350 // Position of this function in the script source.
6351 inline int start_position() const;
6352 inline void set_start_position(int start_position);
6354 // End position of this function in the script source.
6355 inline int end_position() const;
6356 inline void set_end_position(int end_position);
6358 // Is this function a function expression in the source code.
6359 DECL_BOOLEAN_ACCESSORS(is_expression)
6361 // Is this function a top-level function (scripts, evals).
6362 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6364 // Bit field containing various information collected by the compiler to
6365 // drive optimization.
6366 inline int compiler_hints() const;
6367 inline void set_compiler_hints(int value);
6369 inline int ast_node_count() const;
6370 inline void set_ast_node_count(int count);
6372 inline int profiler_ticks() const;
6373 inline void set_profiler_ticks(int ticks);
6375 // Inline cache age is used to infer whether the function survived a context
6376 // disposal or not. In the former case we reset the opt_count.
6377 inline int ic_age();
6378 inline void set_ic_age(int age);
6380 // Indicates if this function can be lazy compiled.
6381 // This is used to determine if we can safely flush code from a function
6382 // when doing GC if we expect that the function will no longer be used.
6383 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6385 // Indicates if this function can be lazy compiled without a context.
6386 // This is used to determine if we can force compilation without reaching
6387 // the function through program execution but through other means (e.g. heap
6388 // iteration by the debugger).
6389 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6391 // Indicates whether optimizations have been disabled for this
6392 // shared function info. If a function is repeatedly optimized or if
6393 // we cannot optimize the function we disable optimization to avoid
6394 // spending time attempting to optimize it again.
6395 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6397 // Indicates the language mode.
6398 inline LanguageMode language_mode();
6399 inline void set_language_mode(LanguageMode language_mode);
6401 // False if the function definitely does not allocate an arguments object.
6402 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6404 // Indicates that this function uses a super property (or an eval that may
6405 // use a super property).
6406 // This is needed to set up the [[HomeObject]] on the function instance.
6407 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6409 // True if the function has any duplicated parameter names.
6410 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6412 // Indicates whether the function is a native function.
6413 // These needs special treatment in .call and .apply since
6414 // null passed as the receiver should not be translated to the
6416 DECL_BOOLEAN_ACCESSORS(native)
6418 // Indicate that this function should always be inlined in optimized code.
6419 DECL_BOOLEAN_ACCESSORS(force_inline)
6421 // Indicates that the function was created by the Function function.
6422 // Though it's anonymous, toString should treat it as if it had the name
6423 // "anonymous". We don't set the name itself so that the system does not
6424 // see a binding for it.
6425 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6427 // Indicates whether the function is a bound function created using
6428 // the bind function.
6429 DECL_BOOLEAN_ACCESSORS(bound)
6431 // Indicates that the function is anonymous (the name field can be set
6432 // through the API, which does not change this flag).
6433 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6435 // Is this a function or top-level/eval code.
6436 DECL_BOOLEAN_ACCESSORS(is_function)
6438 // Indicates that code for this function cannot be compiled with Crankshaft.
6439 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6441 // Indicates that code for this function cannot be flushed.
6442 DECL_BOOLEAN_ACCESSORS(dont_flush)
6444 // Indicates that this function is a generator.
6445 DECL_BOOLEAN_ACCESSORS(is_generator)
6447 // Indicates that this function is an arrow function.
6448 DECL_BOOLEAN_ACCESSORS(is_arrow)
6450 // Indicates that this function is a concise method.
6451 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6453 // Indicates that this function is an accessor (getter or setter).
6454 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6456 // Indicates that this function is a default constructor.
6457 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6459 // Indicates that this function is an asm function.
6460 DECL_BOOLEAN_ACCESSORS(asm_function)
6462 // Indicates that the the shared function info is deserialized from cache.
6463 DECL_BOOLEAN_ACCESSORS(deserialized)
6465 // Indicates that the the shared function info has never been compiled before.
6466 DECL_BOOLEAN_ACCESSORS(never_compiled)
6468 inline FunctionKind kind();
6469 inline void set_kind(FunctionKind kind);
6471 // Indicates whether or not the code in the shared function support
6473 inline bool has_deoptimization_support();
6475 // Enable deoptimization support through recompiled code.
6476 void EnableDeoptimizationSupport(Code* recompiled);
6478 // Disable (further) attempted optimization of all functions sharing this
6479 // shared function info.
6480 void DisableOptimization(BailoutReason reason);
6482 inline BailoutReason disable_optimization_reason();
6484 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6485 // code, returns whether it asserted (i.e., always true if assertions are
6487 bool VerifyBailoutId(BailoutId id);
6489 // [source code]: Source code for the function.
6490 bool HasSourceCode() const;
6491 Handle<Object> GetSourceCode();
6493 // Number of times the function was optimized.
6494 inline int opt_count();
6495 inline void set_opt_count(int opt_count);
6497 // Number of times the function was deoptimized.
6498 inline void set_deopt_count(int value);
6499 inline int deopt_count();
6500 inline void increment_deopt_count();
6502 // Number of time we tried to re-enable optimization after it
6503 // was disabled due to high number of deoptimizations.
6504 inline void set_opt_reenable_tries(int value);
6505 inline int opt_reenable_tries();
6507 inline void TryReenableOptimization();
6509 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6510 inline void set_counters(int value);
6511 inline int counters() const;
6513 // Stores opt_count and bailout_reason as bit-fields.
6514 inline void set_opt_count_and_bailout_reason(int value);
6515 inline int opt_count_and_bailout_reason() const;
6517 inline void set_disable_optimization_reason(BailoutReason reason);
6519 // Tells whether this function should be subject to debugging.
6520 inline bool IsSubjectToDebugging();
6522 // Whether this function is defined in native code or extensions.
6523 inline bool IsBuiltin();
6525 // Check whether or not this function is inlineable.
6526 bool IsInlineable();
6528 // Source size of this function.
6531 // Calculate the instance size.
6532 int CalculateInstanceSize();
6534 // Calculate the number of in-object properties.
6535 int CalculateInObjectProperties();
6537 inline bool has_simple_parameters();
6539 // Initialize a SharedFunctionInfo from a parsed function literal.
6540 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6541 FunctionLiteral* lit);
6543 // Dispatched behavior.
6544 DECLARE_PRINTER(SharedFunctionInfo)
6545 DECLARE_VERIFIER(SharedFunctionInfo)
6547 void ResetForNewContext(int new_ic_age);
6549 // Iterate over all shared function infos that are created from a script.
6550 // That excludes shared function infos created for API functions and C++
6554 explicit Iterator(Isolate* isolate);
6555 SharedFunctionInfo* Next();
6560 Script::Iterator script_iterator_;
6561 WeakFixedArray::Iterator sfi_iterator_;
6562 DisallowHeapAllocation no_gc_;
6563 DISALLOW_COPY_AND_ASSIGN(Iterator);
6566 DECLARE_CAST(SharedFunctionInfo)
6569 static const int kDontAdaptArgumentsSentinel = -1;
6571 // Layout description.
6573 static const int kNameOffset = HeapObject::kHeaderSize;
6574 static const int kCodeOffset = kNameOffset + kPointerSize;
6575 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6576 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6577 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6578 static const int kInstanceClassNameOffset =
6579 kConstructStubOffset + kPointerSize;
6580 static const int kFunctionDataOffset =
6581 kInstanceClassNameOffset + kPointerSize;
6582 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6583 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6584 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6585 static const int kFeedbackVectorOffset =
6586 kInferredNameOffset + kPointerSize;
6588 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6589 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6591 // Just to not break the postmortrem support with conditional offsets
6592 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6593 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6596 #if V8_HOST_ARCH_32_BIT
6598 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6599 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6600 static const int kExpectedNofPropertiesOffset =
6601 kFormalParameterCountOffset + kPointerSize;
6602 static const int kNumLiteralsOffset =
6603 kExpectedNofPropertiesOffset + kPointerSize;
6604 static const int kStartPositionAndTypeOffset =
6605 kNumLiteralsOffset + kPointerSize;
6606 static const int kEndPositionOffset =
6607 kStartPositionAndTypeOffset + kPointerSize;
6608 static const int kFunctionTokenPositionOffset =
6609 kEndPositionOffset + kPointerSize;
6610 static const int kCompilerHintsOffset =
6611 kFunctionTokenPositionOffset + kPointerSize;
6612 static const int kOptCountAndBailoutReasonOffset =
6613 kCompilerHintsOffset + kPointerSize;
6614 static const int kCountersOffset =
6615 kOptCountAndBailoutReasonOffset + kPointerSize;
6616 static const int kAstNodeCountOffset =
6617 kCountersOffset + kPointerSize;
6618 static const int kProfilerTicksOffset =
6619 kAstNodeCountOffset + kPointerSize;
6622 static const int kSize = kProfilerTicksOffset + kPointerSize;
6624 // The only reason to use smi fields instead of int fields
6625 // is to allow iteration without maps decoding during
6626 // garbage collections.
6627 // To avoid wasting space on 64-bit architectures we use
6628 // the following trick: we group integer fields into pairs
6629 // The least significant integer in each pair is shifted left by 1.
6630 // By doing this we guarantee that LSB of each kPointerSize aligned
6631 // word is not set and thus this word cannot be treated as pointer
6632 // to HeapObject during old space traversal.
6633 #if V8_TARGET_LITTLE_ENDIAN
6634 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6635 static const int kFormalParameterCountOffset =
6636 kLengthOffset + kIntSize;
6638 static const int kExpectedNofPropertiesOffset =
6639 kFormalParameterCountOffset + kIntSize;
6640 static const int kNumLiteralsOffset =
6641 kExpectedNofPropertiesOffset + kIntSize;
6643 static const int kEndPositionOffset =
6644 kNumLiteralsOffset + kIntSize;
6645 static const int kStartPositionAndTypeOffset =
6646 kEndPositionOffset + kIntSize;
6648 static const int kFunctionTokenPositionOffset =
6649 kStartPositionAndTypeOffset + kIntSize;
6650 static const int kCompilerHintsOffset =
6651 kFunctionTokenPositionOffset + kIntSize;
6653 static const int kOptCountAndBailoutReasonOffset =
6654 kCompilerHintsOffset + kIntSize;
6655 static const int kCountersOffset =
6656 kOptCountAndBailoutReasonOffset + kIntSize;
6658 static const int kAstNodeCountOffset =
6659 kCountersOffset + kIntSize;
6660 static const int kProfilerTicksOffset =
6661 kAstNodeCountOffset + kIntSize;
6664 static const int kSize = kProfilerTicksOffset + kIntSize;
6666 #elif V8_TARGET_BIG_ENDIAN
6667 static const int kFormalParameterCountOffset =
6668 kLastPointerFieldOffset + kPointerSize;
6669 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6671 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6672 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6674 static const int kStartPositionAndTypeOffset =
6675 kExpectedNofPropertiesOffset + kIntSize;
6676 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6678 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6679 static const int kFunctionTokenPositionOffset =
6680 kCompilerHintsOffset + kIntSize;
6682 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6683 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6685 static const int kProfilerTicksOffset =
6686 kOptCountAndBailoutReasonOffset + kIntSize;
6687 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6690 static const int kSize = kAstNodeCountOffset + kIntSize;
6693 #error Unknown byte ordering
6694 #endif // Big endian
6698 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6700 typedef FixedBodyDescriptor<kNameOffset,
6701 kLastPointerFieldOffset + kPointerSize,
6702 kSize> BodyDescriptor;
6704 // Bit positions in start_position_and_type.
6705 // The source code start position is in the 30 most significant bits of
6706 // the start_position_and_type field.
6707 static const int kIsExpressionBit = 0;
6708 static const int kIsTopLevelBit = 1;
6709 static const int kStartPositionShift = 2;
6710 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6712 // Bit positions in compiler_hints.
6713 enum CompilerHints {
6714 kAllowLazyCompilation,
6715 kAllowLazyCompilationWithoutContext,
6716 kOptimizationDisabled,
6718 kStrictModeFunction,
6719 kStrongModeFunction,
6722 kHasDuplicateParameters,
6726 kNameShouldPrintAsAnonymous,
6733 kIsAccessorFunction,
6734 kIsDefaultConstructor,
6735 kIsSubclassConstructor,
6741 kCompilerHintsCount // Pseudo entry
6743 // Add hints for other modes when they're added.
6744 STATIC_ASSERT(LANGUAGE_END == 3);
6746 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6748 class DeoptCountBits : public BitField<int, 0, 4> {};
6749 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6750 class ICAgeBits : public BitField<int, 22, 8> {};
6752 class OptCountBits : public BitField<int, 0, 22> {};
6753 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6756 #if V8_HOST_ARCH_32_BIT
6757 // On 32 bit platforms, compiler hints is a smi.
6758 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6759 static const int kCompilerHintsSize = kPointerSize;
6761 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6762 static const int kCompilerHintsSmiTagSize = 0;
6763 static const int kCompilerHintsSize = kIntSize;
6766 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6767 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6770 // Constants for optimizing codegen for strict mode function and
6772 // Allows to use byte-width instructions.
6773 static const int kStrictModeBitWithinByte =
6774 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6775 static const int kStrongModeBitWithinByte =
6776 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6778 static const int kNativeBitWithinByte =
6779 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6781 static const int kBoundBitWithinByte =
6782 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6784 #if defined(V8_TARGET_LITTLE_ENDIAN)
6785 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6786 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6787 static const int kStrongModeByteOffset =
6788 kCompilerHintsOffset +
6789 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6790 static const int kNativeByteOffset = kCompilerHintsOffset +
6791 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6792 static const int kBoundByteOffset =
6793 kCompilerHintsOffset +
6794 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6795 #elif defined(V8_TARGET_BIG_ENDIAN)
6796 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6797 (kCompilerHintsSize - 1) -
6798 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6799 static const int kStrongModeByteOffset =
6800 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6801 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6802 static const int kNativeByteOffset = kCompilerHintsOffset +
6803 (kCompilerHintsSize - 1) -
6804 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6805 static const int kBoundByteOffset =
6806 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6807 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6809 #error Unknown byte ordering
6813 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6817 // Printing support.
6818 struct SourceCodeOf {
6819 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6820 : value(v), max_length(max) {}
6821 const SharedFunctionInfo* value;
6826 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6829 class JSGeneratorObject: public JSObject {
6831 // [function]: The function corresponding to this generator object.
6832 DECL_ACCESSORS(function, JSFunction)
6834 // [context]: The context of the suspended computation.
6835 DECL_ACCESSORS(context, Context)
6837 // [receiver]: The receiver of the suspended computation.
6838 DECL_ACCESSORS(receiver, Object)
6840 // [continuation]: Offset into code of continuation.
6842 // A positive offset indicates a suspended generator. The special
6843 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6844 // cannot be resumed.
6845 inline int continuation() const;
6846 inline void set_continuation(int continuation);
6847 inline bool is_closed();
6848 inline bool is_executing();
6849 inline bool is_suspended();
6851 // [operand_stack]: Saved operand stack.
6852 DECL_ACCESSORS(operand_stack, FixedArray)
6854 DECLARE_CAST(JSGeneratorObject)
6856 // Dispatched behavior.
6857 DECLARE_PRINTER(JSGeneratorObject)
6858 DECLARE_VERIFIER(JSGeneratorObject)
6860 // Magic sentinel values for the continuation.
6861 static const int kGeneratorExecuting = -1;
6862 static const int kGeneratorClosed = 0;
6864 // Layout description.
6865 static const int kFunctionOffset = JSObject::kHeaderSize;
6866 static const int kContextOffset = kFunctionOffset + kPointerSize;
6867 static const int kReceiverOffset = kContextOffset + kPointerSize;
6868 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6869 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6870 static const int kSize = kOperandStackOffset + kPointerSize;
6872 // Resume mode, for use by runtime functions.
6873 enum ResumeMode { NEXT, THROW };
6876 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6880 // Representation for module instance objects.
6881 class JSModule: public JSObject {
6883 // [context]: the context holding the module's locals, or undefined if none.
6884 DECL_ACCESSORS(context, Object)
6886 // [scope_info]: Scope info.
6887 DECL_ACCESSORS(scope_info, ScopeInfo)
6889 DECLARE_CAST(JSModule)
6891 // Dispatched behavior.
6892 DECLARE_PRINTER(JSModule)
6893 DECLARE_VERIFIER(JSModule)
6895 // Layout description.
6896 static const int kContextOffset = JSObject::kHeaderSize;
6897 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6898 static const int kSize = kScopeInfoOffset + kPointerSize;
6901 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6905 // JSFunction describes JavaScript functions.
6906 class JSFunction: public JSObject {
6908 // [prototype_or_initial_map]:
6909 DECL_ACCESSORS(prototype_or_initial_map, Object)
6911 // [shared]: The information about the function that
6912 // can be shared by instances.
6913 DECL_ACCESSORS(shared, SharedFunctionInfo)
6915 // [context]: The context for this function.
6916 inline Context* context();
6917 inline void set_context(Object* context);
6918 inline JSObject* global_proxy();
6920 // [code]: The generated code object for this function. Executed
6921 // when the function is invoked, e.g. foo() or new foo(). See
6922 // [[Call]] and [[Construct]] description in ECMA-262, section
6924 inline Code* code();
6925 inline void set_code(Code* code);
6926 inline void set_code_no_write_barrier(Code* code);
6927 inline void ReplaceCode(Code* code);
6929 // Tells whether this function is builtin.
6930 inline bool IsBuiltin();
6932 // Tells whether this function inlines the given shared function info.
6933 bool Inlines(SharedFunctionInfo* candidate);
6935 // Tells whether this function should be subject to debugging.
6936 inline bool IsSubjectToDebugging();
6938 // Tells whether or not the function needs arguments adaption.
6939 inline bool NeedsArgumentsAdaption();
6941 // Tells whether or not this function has been optimized.
6942 inline bool IsOptimized();
6944 // Mark this function for lazy recompilation. The function will be
6945 // recompiled the next time it is executed.
6946 void MarkForOptimization();
6947 void AttemptConcurrentOptimization();
6949 // Tells whether or not the function is already marked for lazy
6951 inline bool IsMarkedForOptimization();
6952 inline bool IsMarkedForConcurrentOptimization();
6954 // Tells whether or not the function is on the concurrent recompilation queue.
6955 inline bool IsInOptimizationQueue();
6957 // Inobject slack tracking is the way to reclaim unused inobject space.
6959 // The instance size is initially determined by adding some slack to
6960 // expected_nof_properties (to allow for a few extra properties added
6961 // after the constructor). There is no guarantee that the extra space
6962 // will not be wasted.
6964 // Here is the algorithm to reclaim the unused inobject space:
6965 // - Detect the first constructor call for this JSFunction.
6966 // When it happens enter the "in progress" state: initialize construction
6967 // counter in the initial_map.
6968 // - While the tracking is in progress create objects filled with
6969 // one_pointer_filler_map instead of undefined_value. This way they can be
6970 // resized quickly and safely.
6971 // - Once enough objects have been created compute the 'slack'
6972 // (traverse the map transition tree starting from the
6973 // initial_map and find the lowest value of unused_property_fields).
6974 // - Traverse the transition tree again and decrease the instance size
6975 // of every map. Existing objects will resize automatically (they are
6976 // filled with one_pointer_filler_map). All further allocations will
6977 // use the adjusted instance size.
6978 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6979 // allocations made using different closures could actually create different
6980 // kind of objects (see prototype inheritance pattern).
6982 // Important: inobject slack tracking is not attempted during the snapshot
6985 // True if the initial_map is set and the object constructions countdown
6986 // counter is not zero.
6987 static const int kGenerousAllocationCount =
6988 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6989 inline bool IsInobjectSlackTrackingInProgress();
6991 // Starts the tracking.
6992 // Initializes object constructions countdown counter in the initial map.
6993 void StartInobjectSlackTracking();
6995 // Completes the tracking.
6996 void CompleteInobjectSlackTracking();
6998 // [literals_or_bindings]: Fixed array holding either
6999 // the materialized literals or the bindings of a bound function.
7001 // If the function contains object, regexp or array literals, the
7002 // literals array prefix contains the object, regexp, and array
7003 // function to be used when creating these literals. This is
7004 // necessary so that we do not dynamically lookup the object, regexp
7005 // or array functions. Performing a dynamic lookup, we might end up
7006 // using the functions from a new context that we should not have
7009 // On bound functions, the array is a (copy-on-write) fixed-array containing
7010 // the function that was bound, bound this-value and any bound
7011 // arguments. Bound functions never contain literals.
7012 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7014 inline FixedArray* literals();
7015 inline void set_literals(FixedArray* literals);
7017 inline FixedArray* function_bindings();
7018 inline void set_function_bindings(FixedArray* bindings);
7020 // The initial map for an object created by this constructor.
7021 inline Map* initial_map();
7022 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7023 Handle<Object> prototype);
7024 inline bool has_initial_map();
7025 static void EnsureHasInitialMap(Handle<JSFunction> function);
7027 // Get and set the prototype property on a JSFunction. If the
7028 // function has an initial map the prototype is set on the initial
7029 // map. Otherwise, the prototype is put in the initial map field
7030 // until an initial map is needed.
7031 inline bool has_prototype();
7032 inline bool has_instance_prototype();
7033 inline Object* prototype();
7034 inline Object* instance_prototype();
7035 static void SetPrototype(Handle<JSFunction> function,
7036 Handle<Object> value);
7037 static void SetInstancePrototype(Handle<JSFunction> function,
7038 Handle<Object> value);
7040 // Creates a new closure for the fucntion with the same bindings,
7041 // bound values, and prototype. An equivalent of spec operations
7042 // ``CloneMethod`` and ``CloneBoundFunction``.
7043 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7045 // After prototype is removed, it will not be created when accessed, and
7046 // [[Construct]] from this function will not be allowed.
7047 bool RemovePrototype();
7048 inline bool should_have_prototype();
7050 // Accessor for this function's initial map's [[class]]
7051 // property. This is primarily used by ECMA native functions. This
7052 // method sets the class_name field of this function's initial map
7053 // to a given value. It creates an initial map if this function does
7054 // not have one. Note that this method does not copy the initial map
7055 // if it has one already, but simply replaces it with the new value.
7056 // Instances created afterwards will have a map whose [[class]] is
7057 // set to 'value', but there is no guarantees on instances created
7059 void SetInstanceClassName(String* name);
7061 // Returns if this function has been compiled to native code yet.
7062 inline bool is_compiled();
7064 // Returns `false` if formal parameters include rest parameters, optional
7065 // parameters, or destructuring parameters.
7066 // TODO(caitp): make this a flag set during parsing
7067 inline bool has_simple_parameters();
7069 // [next_function_link]: Links functions into various lists, e.g. the list
7070 // of optimized functions hanging off the native_context. The CodeFlusher
7071 // uses this link to chain together flushing candidates. Treated weakly
7072 // by the garbage collector.
7073 DECL_ACCESSORS(next_function_link, Object)
7075 // Prints the name of the function using PrintF.
7076 void PrintName(FILE* out = stdout);
7078 DECLARE_CAST(JSFunction)
7080 // Iterates the objects, including code objects indirectly referenced
7081 // through pointers to the first instruction in the code object.
7082 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7084 // Dispatched behavior.
7085 DECLARE_PRINTER(JSFunction)
7086 DECLARE_VERIFIER(JSFunction)
7088 // Returns the number of allocated literals.
7089 inline int NumberOfLiterals();
7091 // Used for flags such as --hydrogen-filter.
7092 bool PassesFilter(const char* raw_filter);
7094 // The function's name if it is configured, otherwise shared function info
7096 static Handle<String> GetDebugName(Handle<JSFunction> function);
7098 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7099 // kSize) is weak and has special handling during garbage collection.
7100 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7101 static const int kPrototypeOrInitialMapOffset =
7102 kCodeEntryOffset + kPointerSize;
7103 static const int kSharedFunctionInfoOffset =
7104 kPrototypeOrInitialMapOffset + kPointerSize;
7105 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7106 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7107 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7108 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7109 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7111 // Layout of the bound-function binding array.
7112 static const int kBoundFunctionIndex = 0;
7113 static const int kBoundThisIndex = 1;
7114 static const int kBoundArgumentsStartIndex = 2;
7117 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7121 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7122 // and the prototype is hidden. JSGlobalProxy always delegates
7123 // property accesses to its prototype if the prototype is not null.
7125 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7127 // Accessing a JSGlobalProxy requires security check.
7129 class JSGlobalProxy : public JSObject {
7131 // [native_context]: the owner native context of this global proxy object.
7132 // It is null value if this object is not used by any context.
7133 DECL_ACCESSORS(native_context, Object)
7135 // [hash]: The hash code property (undefined if not initialized yet).
7136 DECL_ACCESSORS(hash, Object)
7138 DECLARE_CAST(JSGlobalProxy)
7140 inline bool IsDetachedFrom(GlobalObject* global) const;
7142 // Dispatched behavior.
7143 DECLARE_PRINTER(JSGlobalProxy)
7144 DECLARE_VERIFIER(JSGlobalProxy)
7146 // Layout description.
7147 static const int kNativeContextOffset = JSObject::kHeaderSize;
7148 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7149 static const int kSize = kHashOffset + kPointerSize;
7152 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7156 // Common super class for JavaScript global objects and the special
7157 // builtins global objects.
7158 class GlobalObject: public JSObject {
7160 // [builtins]: the object holding the runtime routines written in JS.
7161 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7163 // [native context]: the natives corresponding to this global object.
7164 DECL_ACCESSORS(native_context, Context)
7166 // [global proxy]: the global proxy object of the context
7167 DECL_ACCESSORS(global_proxy, JSObject)
7169 DECLARE_CAST(GlobalObject)
7171 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7173 // Ensure that the global object has a cell for the given property name.
7174 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7177 // Layout description.
7178 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7179 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7180 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7181 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7184 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7188 // JavaScript global object.
7189 class JSGlobalObject: public GlobalObject {
7191 DECLARE_CAST(JSGlobalObject)
7193 inline bool IsDetached();
7195 // Dispatched behavior.
7196 DECLARE_PRINTER(JSGlobalObject)
7197 DECLARE_VERIFIER(JSGlobalObject)
7199 // Layout description.
7200 static const int kSize = GlobalObject::kHeaderSize;
7203 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7207 // Builtins global object which holds the runtime routines written in
7209 class JSBuiltinsObject: public GlobalObject {
7211 DECLARE_CAST(JSBuiltinsObject)
7213 // Dispatched behavior.
7214 DECLARE_PRINTER(JSBuiltinsObject)
7215 DECLARE_VERIFIER(JSBuiltinsObject)
7217 // Layout description.
7218 static const int kSize = GlobalObject::kHeaderSize;
7221 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7225 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7226 class JSValue: public JSObject {
7228 // [value]: the object being wrapped.
7229 DECL_ACCESSORS(value, Object)
7231 DECLARE_CAST(JSValue)
7233 // Dispatched behavior.
7234 DECLARE_PRINTER(JSValue)
7235 DECLARE_VERIFIER(JSValue)
7237 // Layout description.
7238 static const int kValueOffset = JSObject::kHeaderSize;
7239 static const int kSize = kValueOffset + kPointerSize;
7242 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7248 // Representation for JS date objects.
7249 class JSDate: public JSObject {
7251 // If one component is NaN, all of them are, indicating a NaN time value.
7252 // [value]: the time value.
7253 DECL_ACCESSORS(value, Object)
7254 // [year]: caches year. Either undefined, smi, or NaN.
7255 DECL_ACCESSORS(year, Object)
7256 // [month]: caches month. Either undefined, smi, or NaN.
7257 DECL_ACCESSORS(month, Object)
7258 // [day]: caches day. Either undefined, smi, or NaN.
7259 DECL_ACCESSORS(day, Object)
7260 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7261 DECL_ACCESSORS(weekday, Object)
7262 // [hour]: caches hours. Either undefined, smi, or NaN.
7263 DECL_ACCESSORS(hour, Object)
7264 // [min]: caches minutes. Either undefined, smi, or NaN.
7265 DECL_ACCESSORS(min, Object)
7266 // [sec]: caches seconds. Either undefined, smi, or NaN.
7267 DECL_ACCESSORS(sec, Object)
7268 // [cache stamp]: sample of the date cache stamp at the
7269 // moment when chached fields were cached.
7270 DECL_ACCESSORS(cache_stamp, Object)
7272 DECLARE_CAST(JSDate)
7274 // Returns the date field with the specified index.
7275 // See FieldIndex for the list of date fields.
7276 static Object* GetField(Object* date, Smi* index);
7278 void SetValue(Object* value, bool is_value_nan);
7280 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7281 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7282 Handle<JSReceiver> receiver, Handle<Object> hint);
7284 // Dispatched behavior.
7285 DECLARE_PRINTER(JSDate)
7286 DECLARE_VERIFIER(JSDate)
7288 // The order is important. It must be kept in sync with date macros
7299 kFirstUncachedField,
7300 kMillisecond = kFirstUncachedField,
7304 kYearUTC = kFirstUTCField,
7317 // Layout description.
7318 static const int kValueOffset = JSObject::kHeaderSize;
7319 static const int kYearOffset = kValueOffset + kPointerSize;
7320 static const int kMonthOffset = kYearOffset + kPointerSize;
7321 static const int kDayOffset = kMonthOffset + kPointerSize;
7322 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7323 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7324 static const int kMinOffset = kHourOffset + kPointerSize;
7325 static const int kSecOffset = kMinOffset + kPointerSize;
7326 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7327 static const int kSize = kCacheStampOffset + kPointerSize;
7330 inline Object* DoGetField(FieldIndex index);
7332 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7334 // Computes and caches the cacheable fields of the date.
7335 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7338 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7342 // Representation of message objects used for error reporting through
7343 // the API. The messages are formatted in JavaScript so this object is
7344 // a real JavaScript object. The information used for formatting the
7345 // error messages are not directly accessible from JavaScript to
7346 // prevent leaking information to user code called during error
7348 class JSMessageObject: public JSObject {
7350 // [type]: the type of error message.
7351 inline int type() const;
7352 inline void set_type(int value);
7354 // [arguments]: the arguments for formatting the error message.
7355 DECL_ACCESSORS(argument, Object)
7357 // [script]: the script from which the error message originated.
7358 DECL_ACCESSORS(script, Object)
7360 // [stack_frames]: an array of stack frames for this error object.
7361 DECL_ACCESSORS(stack_frames, Object)
7363 // [start_position]: the start position in the script for the error message.
7364 inline int start_position() const;
7365 inline void set_start_position(int value);
7367 // [end_position]: the end position in the script for the error message.
7368 inline int end_position() const;
7369 inline void set_end_position(int value);
7371 DECLARE_CAST(JSMessageObject)
7373 // Dispatched behavior.
7374 DECLARE_PRINTER(JSMessageObject)
7375 DECLARE_VERIFIER(JSMessageObject)
7377 // Layout description.
7378 static const int kTypeOffset = JSObject::kHeaderSize;
7379 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7380 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7381 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7382 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7383 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7384 static const int kSize = kEndPositionOffset + kPointerSize;
7386 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7387 kStackFramesOffset + kPointerSize,
7388 kSize> BodyDescriptor;
7392 // Regular expressions
7393 // The regular expression holds a single reference to a FixedArray in
7394 // the kDataOffset field.
7395 // The FixedArray contains the following data:
7396 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7397 // - reference to the original source string
7398 // - reference to the original flag string
7399 // If it is an atom regexp
7400 // - a reference to a literal string to search for
7401 // If it is an irregexp regexp:
7402 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7403 // used for tracking the last usage (used for code flushing).
7404 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7405 // used for tracking the last usage (used for code flushing)..
7406 // - max number of registers used by irregexp implementations.
7407 // - number of capture registers (output values) of the regexp.
7408 class JSRegExp: public JSObject {
7411 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7412 // ATOM: A simple string to match against using an indexOf operation.
7413 // IRREGEXP: Compiled with Irregexp.
7414 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7415 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7422 UNICODE_ESCAPES = 16
7427 explicit Flags(uint32_t value) : value_(value) { }
7428 bool is_global() { return (value_ & GLOBAL) != 0; }
7429 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7430 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7431 bool is_sticky() { return (value_ & STICKY) != 0; }
7432 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7433 uint32_t value() { return value_; }
7438 DECL_ACCESSORS(data, Object)
7440 inline Type TypeTag();
7441 inline int CaptureCount();
7442 inline Flags GetFlags();
7443 inline String* Pattern();
7444 inline Object* DataAt(int index);
7445 // Set implementation data after the object has been prepared.
7446 inline void SetDataAt(int index, Object* value);
7448 static int code_index(bool is_latin1) {
7450 return kIrregexpLatin1CodeIndex;
7452 return kIrregexpUC16CodeIndex;
7456 static int saved_code_index(bool is_latin1) {
7458 return kIrregexpLatin1CodeSavedIndex;
7460 return kIrregexpUC16CodeSavedIndex;
7464 DECLARE_CAST(JSRegExp)
7466 // Dispatched behavior.
7467 DECLARE_VERIFIER(JSRegExp)
7469 static const int kDataOffset = JSObject::kHeaderSize;
7470 static const int kSize = kDataOffset + kPointerSize;
7472 // Indices in the data array.
7473 static const int kTagIndex = 0;
7474 static const int kSourceIndex = kTagIndex + 1;
7475 static const int kFlagsIndex = kSourceIndex + 1;
7476 static const int kDataIndex = kFlagsIndex + 1;
7477 // The data fields are used in different ways depending on the
7478 // value of the tag.
7479 // Atom regexps (literal strings).
7480 static const int kAtomPatternIndex = kDataIndex;
7482 static const int kAtomDataSize = kAtomPatternIndex + 1;
7484 // Irregexp compiled code or bytecode for Latin1. If compilation
7485 // fails, this fields hold an exception object that should be
7486 // thrown if the regexp is used again.
7487 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7488 // Irregexp compiled code or bytecode for UC16. If compilation
7489 // fails, this fields hold an exception object that should be
7490 // thrown if the regexp is used again.
7491 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7493 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7494 // is a potential candidate for flushing.
7495 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7496 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7497 // a potential candidate for flushing.
7498 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7500 // Maximal number of registers used by either Latin1 or UC16.
7501 // Only used to check that there is enough stack space
7502 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7503 // Number of captures in the compiled regexp.
7504 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7506 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7508 // Offsets directly into the data fixed array.
7509 static const int kDataTagOffset =
7510 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7511 static const int kDataOneByteCodeOffset =
7512 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7513 static const int kDataUC16CodeOffset =
7514 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7515 static const int kIrregexpCaptureCountOffset =
7516 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7518 // In-object fields.
7519 static const int kSourceFieldIndex = 0;
7520 static const int kGlobalFieldIndex = 1;
7521 static const int kIgnoreCaseFieldIndex = 2;
7522 static const int kMultilineFieldIndex = 3;
7523 static const int kLastIndexFieldIndex = 4;
7524 static const int kInObjectFieldCount = 5;
7526 // The uninitialized value for a regexp code object.
7527 static const int kUninitializedValue = -1;
7529 // The compilation error value for the regexp code object. The real error
7530 // object is in the saved code field.
7531 static const int kCompilationErrorValue = -2;
7533 // When we store the sweep generation at which we moved the code from the
7534 // code index to the saved code index we mask it of to be in the [0:255]
7536 static const int kCodeAgeMask = 0xff;
7540 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7542 static inline bool IsMatch(HashTableKey* key, Object* value) {
7543 return key->IsMatch(value);
7546 static inline uint32_t Hash(HashTableKey* key) {
7550 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7551 return key->HashForObject(object);
7554 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7556 static const int kPrefixSize = 0;
7557 static const int kEntrySize = 2;
7561 // This cache is used in two different variants. For regexp caching, it simply
7562 // maps identifying info of the regexp to the cached regexp object. Scripts and
7563 // eval code only gets cached after a second probe for the code object. To do
7564 // so, on first "put" only a hash identifying the source is entered into the
7565 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7566 // such lifetimes get reduced, and removed once they reach zero. If a second put
7567 // is called while such a hash is live in the cache, the hash gets replaced by
7568 // an actual cache entry. Age also removes stale live entries from the cache.
7569 // Such entries are identified by SharedFunctionInfos pointing to either the
7570 // recompilation stub, or to "old" code. This avoids memory leaks due to
7571 // premature caching of scripts and eval strings that are never needed later.
7572 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7573 CompilationCacheShape,
7576 // Find cached value for a string key, otherwise return null.
7577 Handle<Object> Lookup(
7578 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7579 Handle<Object> LookupEval(
7580 Handle<String> src, Handle<SharedFunctionInfo> shared,
7581 LanguageMode language_mode, int scope_position);
7582 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7583 static Handle<CompilationCacheTable> Put(
7584 Handle<CompilationCacheTable> cache, Handle<String> src,
7585 Handle<Context> context, LanguageMode language_mode,
7586 Handle<Object> value);
7587 static Handle<CompilationCacheTable> PutEval(
7588 Handle<CompilationCacheTable> cache, Handle<String> src,
7589 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7590 int scope_position);
7591 static Handle<CompilationCacheTable> PutRegExp(
7592 Handle<CompilationCacheTable> cache, Handle<String> src,
7593 JSRegExp::Flags flags, Handle<FixedArray> value);
7594 void Remove(Object* value);
7596 static const int kHashGenerations = 10;
7598 DECLARE_CAST(CompilationCacheTable)
7601 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7605 class CodeCache: public Struct {
7607 DECL_ACCESSORS(default_cache, FixedArray)
7608 DECL_ACCESSORS(normal_type_cache, Object)
7610 // Add the code object to the cache.
7612 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7614 // Lookup code object in the cache. Returns code object if found and undefined
7616 Object* Lookup(Name* name, Code::Flags flags);
7618 // Get the internal index of a code object in the cache. Returns -1 if the
7619 // code object is not in that cache. This index can be used to later call
7620 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7622 int GetIndex(Object* name, Code* code);
7624 // Remove an object from the cache with the provided internal index.
7625 void RemoveByIndex(Object* name, Code* code, int index);
7627 DECLARE_CAST(CodeCache)
7629 // Dispatched behavior.
7630 DECLARE_PRINTER(CodeCache)
7631 DECLARE_VERIFIER(CodeCache)
7633 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7634 static const int kNormalTypeCacheOffset =
7635 kDefaultCacheOffset + kPointerSize;
7636 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7639 static void UpdateDefaultCache(
7640 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7641 static void UpdateNormalTypeCache(
7642 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7643 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7644 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7646 // Code cache layout of the default cache. Elements are alternating name and
7647 // code objects for non normal load/store/call IC's.
7648 static const int kCodeCacheEntrySize = 2;
7649 static const int kCodeCacheEntryNameOffset = 0;
7650 static const int kCodeCacheEntryCodeOffset = 1;
7652 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7656 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7658 static inline bool IsMatch(HashTableKey* key, Object* value) {
7659 return key->IsMatch(value);
7662 static inline uint32_t Hash(HashTableKey* key) {
7666 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7667 return key->HashForObject(object);
7670 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7672 static const int kPrefixSize = 0;
7673 static const int kEntrySize = 2;
7677 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7678 CodeCacheHashTableShape,
7681 Object* Lookup(Name* name, Code::Flags flags);
7682 static Handle<CodeCacheHashTable> Put(
7683 Handle<CodeCacheHashTable> table,
7687 int GetIndex(Name* name, Code::Flags flags);
7688 void RemoveByIndex(int index);
7690 DECLARE_CAST(CodeCacheHashTable)
7692 // Initial size of the fixed array backing the hash table.
7693 static const int kInitialSize = 64;
7696 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7700 class PolymorphicCodeCache: public Struct {
7702 DECL_ACCESSORS(cache, Object)
7704 static void Update(Handle<PolymorphicCodeCache> cache,
7705 MapHandleList* maps,
7710 // Returns an undefined value if the entry is not found.
7711 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7713 DECLARE_CAST(PolymorphicCodeCache)
7715 // Dispatched behavior.
7716 DECLARE_PRINTER(PolymorphicCodeCache)
7717 DECLARE_VERIFIER(PolymorphicCodeCache)
7719 static const int kCacheOffset = HeapObject::kHeaderSize;
7720 static const int kSize = kCacheOffset + kPointerSize;
7723 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7727 class PolymorphicCodeCacheHashTable
7728 : public HashTable<PolymorphicCodeCacheHashTable,
7729 CodeCacheHashTableShape,
7732 Object* Lookup(MapHandleList* maps, int code_kind);
7734 static Handle<PolymorphicCodeCacheHashTable> Put(
7735 Handle<PolymorphicCodeCacheHashTable> hash_table,
7736 MapHandleList* maps,
7740 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7742 static const int kInitialSize = 64;
7744 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7748 class TypeFeedbackInfo: public Struct {
7750 inline int ic_total_count();
7751 inline void set_ic_total_count(int count);
7753 inline int ic_with_type_info_count();
7754 inline void change_ic_with_type_info_count(int delta);
7756 inline int ic_generic_count();
7757 inline void change_ic_generic_count(int delta);
7759 inline void initialize_storage();
7761 inline void change_own_type_change_checksum();
7762 inline int own_type_change_checksum();
7764 inline void set_inlined_type_change_checksum(int checksum);
7765 inline bool matches_inlined_type_change_checksum(int checksum);
7767 DECLARE_CAST(TypeFeedbackInfo)
7769 // Dispatched behavior.
7770 DECLARE_PRINTER(TypeFeedbackInfo)
7771 DECLARE_VERIFIER(TypeFeedbackInfo)
7773 static const int kStorage1Offset = HeapObject::kHeaderSize;
7774 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7775 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7776 static const int kSize = kStorage3Offset + kPointerSize;
7779 static const int kTypeChangeChecksumBits = 7;
7781 class ICTotalCountField: public BitField<int, 0,
7782 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7783 class OwnTypeChangeChecksum: public BitField<int,
7784 kSmiValueSize - kTypeChangeChecksumBits,
7785 kTypeChangeChecksumBits> {}; // NOLINT
7786 class ICsWithTypeInfoCountField: public BitField<int, 0,
7787 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7788 class InlinedTypeChangeChecksum: public BitField<int,
7789 kSmiValueSize - kTypeChangeChecksumBits,
7790 kTypeChangeChecksumBits> {}; // NOLINT
7792 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7796 enum AllocationSiteMode {
7797 DONT_TRACK_ALLOCATION_SITE,
7798 TRACK_ALLOCATION_SITE,
7799 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7803 class AllocationSite: public Struct {
7805 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7806 static const double kPretenureRatio;
7807 static const int kPretenureMinimumCreated = 100;
7809 // Values for pretenure decision field.
7810 enum PretenureDecision {
7816 kLastPretenureDecisionValue = kZombie
7819 const char* PretenureDecisionName(PretenureDecision decision);
7821 DECL_ACCESSORS(transition_info, Object)
7822 // nested_site threads a list of sites that represent nested literals
7823 // walked in a particular order. So [[1, 2], 1, 2] will have one
7824 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7825 DECL_ACCESSORS(nested_site, Object)
7826 DECL_ACCESSORS(pretenure_data, Smi)
7827 DECL_ACCESSORS(pretenure_create_count, Smi)
7828 DECL_ACCESSORS(dependent_code, DependentCode)
7829 DECL_ACCESSORS(weak_next, Object)
7831 inline void Initialize();
7833 // This method is expensive, it should only be called for reporting.
7834 bool IsNestedSite();
7836 // transition_info bitfields, for constructed array transition info.
7837 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7838 class UnusedBits: public BitField<int, 15, 14> {};
7839 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7841 // Bitfields for pretenure_data
7842 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7843 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7844 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7845 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7847 // Increments the mementos found counter and returns true when the first
7848 // memento was found for a given allocation site.
7849 inline bool IncrementMementoFoundCount();
7851 inline void IncrementMementoCreateCount();
7853 PretenureFlag GetPretenureMode();
7855 void ResetPretenureDecision();
7857 inline PretenureDecision pretenure_decision();
7858 inline void set_pretenure_decision(PretenureDecision decision);
7860 inline bool deopt_dependent_code();
7861 inline void set_deopt_dependent_code(bool deopt);
7863 inline int memento_found_count();
7864 inline void set_memento_found_count(int count);
7866 inline int memento_create_count();
7867 inline void set_memento_create_count(int count);
7869 // The pretenuring decision is made during gc, and the zombie state allows
7870 // us to recognize when an allocation site is just being kept alive because
7871 // a later traversal of new space may discover AllocationMementos that point
7872 // to this AllocationSite.
7873 inline bool IsZombie();
7875 inline bool IsMaybeTenure();
7877 inline void MarkZombie();
7879 inline bool MakePretenureDecision(PretenureDecision current_decision,
7881 bool maximum_size_scavenge);
7883 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7885 inline ElementsKind GetElementsKind();
7886 inline void SetElementsKind(ElementsKind kind);
7888 inline bool CanInlineCall();
7889 inline void SetDoNotInlineCall();
7891 inline bool SitePointsToLiteral();
7893 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7894 ElementsKind to_kind);
7896 DECLARE_PRINTER(AllocationSite)
7897 DECLARE_VERIFIER(AllocationSite)
7899 DECLARE_CAST(AllocationSite)
7900 static inline AllocationSiteMode GetMode(
7901 ElementsKind boilerplate_elements_kind);
7902 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7903 static inline bool CanTrack(InstanceType type);
7905 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7906 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7907 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7908 static const int kPretenureCreateCountOffset =
7909 kPretenureDataOffset + kPointerSize;
7910 static const int kDependentCodeOffset =
7911 kPretenureCreateCountOffset + kPointerSize;
7912 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7913 static const int kSize = kWeakNextOffset + kPointerSize;
7915 // During mark compact we need to take special care for the dependent code
7917 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7918 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7920 // For other visitors, use the fixed body descriptor below.
7921 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7922 kDependentCodeOffset + kPointerSize,
7923 kSize> BodyDescriptor;
7926 inline bool PretenuringDecisionMade();
7928 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7932 class AllocationMemento: public Struct {
7934 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7935 static const int kSize = kAllocationSiteOffset + kPointerSize;
7937 DECL_ACCESSORS(allocation_site, Object)
7939 inline bool IsValid();
7940 inline AllocationSite* GetAllocationSite();
7942 DECLARE_PRINTER(AllocationMemento)
7943 DECLARE_VERIFIER(AllocationMemento)
7945 DECLARE_CAST(AllocationMemento)
7948 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7952 // Representation of a slow alias as part of a sloppy arguments objects.
7953 // For fast aliases (if HasSloppyArgumentsElements()):
7954 // - the parameter map contains an index into the context
7955 // - all attributes of the element have default values
7956 // For slow aliases (if HasDictionaryArgumentsElements()):
7957 // - the parameter map contains no fast alias mapping (i.e. the hole)
7958 // - this struct (in the slow backing store) contains an index into the context
7959 // - all attributes are available as part if the property details
7960 class AliasedArgumentsEntry: public Struct {
7962 inline int aliased_context_slot() const;
7963 inline void set_aliased_context_slot(int count);
7965 DECLARE_CAST(AliasedArgumentsEntry)
7967 // Dispatched behavior.
7968 DECLARE_PRINTER(AliasedArgumentsEntry)
7969 DECLARE_VERIFIER(AliasedArgumentsEntry)
7971 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7972 static const int kSize = kAliasedContextSlot + kPointerSize;
7975 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7979 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7980 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7983 class StringHasher {
7985 explicit inline StringHasher(int length, uint32_t seed);
7987 template <typename schar>
7988 static inline uint32_t HashSequentialString(const schar* chars,
7992 // Reads all the data, even for long strings and computes the utf16 length.
7993 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7995 int* utf16_length_out);
7997 // Calculated hash value for a string consisting of 1 to
7998 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7999 // value is represented decimal value.
8000 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8002 // No string is allowed to have a hash of zero. That value is reserved
8003 // for internal properties. If the hash calculation yields zero then we
8005 static const int kZeroHash = 27;
8007 // Reusable parts of the hashing algorithm.
8008 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8009 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8010 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8011 const uc16* chars, int length));
8012 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8017 // Returns the value to store in the hash field of a string with
8018 // the given length and contents.
8019 uint32_t GetHashField();
8020 // Returns true if the hash of this string can be computed without
8021 // looking at the contents.
8022 inline bool has_trivial_hash();
8023 // Adds a block of characters to the hash.
8024 template<typename Char>
8025 inline void AddCharacters(const Char* chars, int len);
8028 // Add a character to the hash.
8029 inline void AddCharacter(uint16_t c);
8030 // Update index. Returns true if string is still an index.
8031 inline bool UpdateIndex(uint16_t c);
8034 uint32_t raw_running_hash_;
8035 uint32_t array_index_;
8036 bool is_array_index_;
8037 bool is_first_char_;
8038 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8042 class IteratingStringHasher : public StringHasher {
8044 static inline uint32_t Hash(String* string, uint32_t seed);
8045 inline void VisitOneByteString(const uint8_t* chars, int length);
8046 inline void VisitTwoByteString(const uint16_t* chars, int length);
8049 inline IteratingStringHasher(int len, uint32_t seed);
8050 void VisitConsString(ConsString* cons_string);
8051 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8055 // The characteristics of a string are stored in its map. Retrieving these
8056 // few bits of information is moderately expensive, involving two memory
8057 // loads where the second is dependent on the first. To improve efficiency
8058 // the shape of the string is given its own class so that it can be retrieved
8059 // once and used for several string operations. A StringShape is small enough
8060 // to be passed by value and is immutable, but be aware that flattening a
8061 // string can potentially alter its shape. Also be aware that a GC caused by
8062 // something else can alter the shape of a string due to ConsString
8063 // shortcutting. Keeping these restrictions in mind has proven to be error-
8064 // prone and so we no longer put StringShapes in variables unless there is a
8065 // concrete performance benefit at that particular point in the code.
8066 class StringShape BASE_EMBEDDED {
8068 inline explicit StringShape(const String* s);
8069 inline explicit StringShape(Map* s);
8070 inline explicit StringShape(InstanceType t);
8071 inline bool IsSequential();
8072 inline bool IsExternal();
8073 inline bool IsCons();
8074 inline bool IsSliced();
8075 inline bool IsIndirect();
8076 inline bool IsExternalOneByte();
8077 inline bool IsExternalTwoByte();
8078 inline bool IsSequentialOneByte();
8079 inline bool IsSequentialTwoByte();
8080 inline bool IsInternalized();
8081 inline StringRepresentationTag representation_tag();
8082 inline uint32_t encoding_tag();
8083 inline uint32_t full_representation_tag();
8084 inline uint32_t size_tag();
8086 inline uint32_t type() { return type_; }
8087 inline void invalidate() { valid_ = false; }
8088 inline bool valid() { return valid_; }
8090 inline void invalidate() { }
8096 inline void set_valid() { valid_ = true; }
8099 inline void set_valid() { }
8104 // The Name abstract class captures anything that can be used as a property
8105 // name, i.e., strings and symbols. All names store a hash value.
8106 class Name: public HeapObject {
8108 // Get and set the hash field of the name.
8109 inline uint32_t hash_field();
8110 inline void set_hash_field(uint32_t value);
8112 // Tells whether the hash code has been computed.
8113 inline bool HasHashCode();
8115 // Returns a hash value used for the property table
8116 inline uint32_t Hash();
8118 // Equality operations.
8119 inline bool Equals(Name* other);
8120 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8123 inline bool AsArrayIndex(uint32_t* index);
8125 // If the name is private, it can only name own properties.
8126 inline bool IsPrivate();
8128 // If the name is a non-flat string, this method returns a flat version of the
8129 // string. Otherwise it'll just return the input.
8130 static inline Handle<Name> Flatten(Handle<Name> name,
8131 PretenureFlag pretenure = NOT_TENURED);
8133 // Return a string version of this name that is converted according to the
8134 // rules described in ES6 section 9.2.11.
8135 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8139 DECLARE_PRINTER(Name)
8141 void NameShortPrint();
8142 int NameShortPrint(Vector<char> str);
8145 // Layout description.
8146 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8147 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8148 static const int kHashFieldOffset = kHashFieldSlot;
8150 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8152 static const int kSize = kHashFieldSlot + kPointerSize;
8154 // Mask constant for checking if a name has a computed hash code
8155 // and if it is a string that is an array index. The least significant bit
8156 // indicates whether a hash code has been computed. If the hash code has
8157 // been computed the 2nd bit tells whether the string can be used as an
8159 static const int kHashNotComputedMask = 1;
8160 static const int kIsNotArrayIndexMask = 1 << 1;
8161 static const int kNofHashBitFields = 2;
8163 // Shift constant retrieving hash code from hash field.
8164 static const int kHashShift = kNofHashBitFields;
8166 // Only these bits are relevant in the hash, since the top two are shifted
8168 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8170 // Array index strings this short can keep their index in the hash field.
8171 static const int kMaxCachedArrayIndexLength = 7;
8173 // For strings which are array indexes the hash value has the string length
8174 // mixed into the hash, mainly to avoid a hash value of zero which would be
8175 // the case for the string '0'. 24 bits are used for the array index value.
8176 static const int kArrayIndexValueBits = 24;
8177 static const int kArrayIndexLengthBits =
8178 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8180 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8182 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8183 kArrayIndexValueBits> {}; // NOLINT
8184 class ArrayIndexLengthBits : public BitField<unsigned int,
8185 kNofHashBitFields + kArrayIndexValueBits,
8186 kArrayIndexLengthBits> {}; // NOLINT
8188 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8189 // could use a mask to test if the length of string is less than or equal to
8190 // kMaxCachedArrayIndexLength.
8191 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8193 static const unsigned int kContainsCachedArrayIndexMask =
8194 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8195 << ArrayIndexLengthBits::kShift) |
8196 kIsNotArrayIndexMask;
8198 // Value of empty hash field indicating that the hash is not computed.
8199 static const int kEmptyHashField =
8200 kIsNotArrayIndexMask | kHashNotComputedMask;
8203 static inline bool IsHashFieldComputed(uint32_t field);
8206 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8211 class Symbol: public Name {
8213 // [name]: The print name of a symbol, or undefined if none.
8214 DECL_ACCESSORS(name, Object)
8216 DECL_ACCESSORS(flags, Smi)
8218 // [is_private]: Whether this is a private symbol. Private symbols can only
8219 // be used to designate own properties of objects.
8220 DECL_BOOLEAN_ACCESSORS(is_private)
8222 DECLARE_CAST(Symbol)
8224 // Dispatched behavior.
8225 DECLARE_PRINTER(Symbol)
8226 DECLARE_VERIFIER(Symbol)
8228 // Layout description.
8229 static const int kNameOffset = Name::kSize;
8230 static const int kFlagsOffset = kNameOffset + kPointerSize;
8231 static const int kSize = kFlagsOffset + kPointerSize;
8233 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8235 void SymbolShortPrint(std::ostream& os);
8238 static const int kPrivateBit = 0;
8240 const char* PrivateSymbolToName() const;
8243 friend class Name; // For PrivateSymbolToName.
8246 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8252 // The String abstract class captures JavaScript string values:
8255 // 4.3.16 String Value
8256 // A string value is a member of the type String and is a finite
8257 // ordered sequence of zero or more 16-bit unsigned integer values.
8259 // All string values have a length field.
8260 class String: public Name {
8262 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8264 // Array index strings this short can keep their index in the hash field.
8265 static const int kMaxCachedArrayIndexLength = 7;
8267 // For strings which are array indexes the hash value has the string length
8268 // mixed into the hash, mainly to avoid a hash value of zero which would be
8269 // the case for the string '0'. 24 bits are used for the array index value.
8270 static const int kArrayIndexValueBits = 24;
8271 static const int kArrayIndexLengthBits =
8272 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8274 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8276 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8277 kArrayIndexValueBits> {}; // NOLINT
8278 class ArrayIndexLengthBits : public BitField<unsigned int,
8279 kNofHashBitFields + kArrayIndexValueBits,
8280 kArrayIndexLengthBits> {}; // NOLINT
8282 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8283 // could use a mask to test if the length of string is less than or equal to
8284 // kMaxCachedArrayIndexLength.
8285 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8287 static const unsigned int kContainsCachedArrayIndexMask =
8288 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8289 << ArrayIndexLengthBits::kShift) |
8290 kIsNotArrayIndexMask;
8292 class SubStringRange {
8294 explicit inline SubStringRange(String* string, int first = 0,
8297 inline iterator begin();
8298 inline iterator end();
8306 // Representation of the flat content of a String.
8307 // A non-flat string doesn't have flat content.
8308 // A flat string has content that's encoded as a sequence of either
8309 // one-byte chars or two-byte UC16.
8310 // Returned by String::GetFlatContent().
8313 // Returns true if the string is flat and this structure contains content.
8314 bool IsFlat() { return state_ != NON_FLAT; }
8315 // Returns true if the structure contains one-byte content.
8316 bool IsOneByte() { return state_ == ONE_BYTE; }
8317 // Returns true if the structure contains two-byte content.
8318 bool IsTwoByte() { return state_ == TWO_BYTE; }
8320 // Return the one byte content of the string. Only use if IsOneByte()
8322 Vector<const uint8_t> ToOneByteVector() {
8323 DCHECK_EQ(ONE_BYTE, state_);
8324 return Vector<const uint8_t>(onebyte_start, length_);
8326 // Return the two-byte content of the string. Only use if IsTwoByte()
8328 Vector<const uc16> ToUC16Vector() {
8329 DCHECK_EQ(TWO_BYTE, state_);
8330 return Vector<const uc16>(twobyte_start, length_);
8334 DCHECK(i < length_);
8335 DCHECK(state_ != NON_FLAT);
8336 if (state_ == ONE_BYTE) return onebyte_start[i];
8337 return twobyte_start[i];
8340 bool UsesSameString(const FlatContent& other) const {
8341 return onebyte_start == other.onebyte_start;
8345 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8347 // Constructors only used by String::GetFlatContent().
8348 explicit FlatContent(const uint8_t* start, int length)
8349 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8350 explicit FlatContent(const uc16* start, int length)
8351 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8352 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8355 const uint8_t* onebyte_start;
8356 const uc16* twobyte_start;
8361 friend class String;
8362 friend class IterableSubString;
8365 template <typename Char>
8366 INLINE(Vector<const Char> GetCharVector());
8368 // Get and set the length of the string.
8369 inline int length() const;
8370 inline void set_length(int value);
8372 // Get and set the length of the string using acquire loads and release
8374 inline int synchronized_length() const;
8375 inline void synchronized_set_length(int value);
8377 // Returns whether this string has only one-byte chars, i.e. all of them can
8378 // be one-byte encoded. This might be the case even if the string is
8379 // two-byte. Such strings may appear when the embedder prefers
8380 // two-byte external representations even for one-byte data.
8381 inline bool IsOneByteRepresentation() const;
8382 inline bool IsTwoByteRepresentation() const;
8384 // Cons and slices have an encoding flag that may not represent the actual
8385 // encoding of the underlying string. This is taken into account here.
8386 // Requires: this->IsFlat()
8387 inline bool IsOneByteRepresentationUnderneath();
8388 inline bool IsTwoByteRepresentationUnderneath();
8390 // NOTE: this should be considered only a hint. False negatives are
8392 inline bool HasOnlyOneByteChars();
8394 // Get and set individual two byte chars in the string.
8395 inline void Set(int index, uint16_t value);
8396 // Get individual two byte char in the string. Repeated calls
8397 // to this method are not efficient unless the string is flat.
8398 INLINE(uint16_t Get(int index));
8400 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8401 static Handle<Object> ToNumber(Handle<String> subject);
8403 // Flattens the string. Checks first inline to see if it is
8404 // necessary. Does nothing if the string is not a cons string.
8405 // Flattening allocates a sequential string with the same data as
8406 // the given string and mutates the cons string to a degenerate
8407 // form, where the first component is the new sequential string and
8408 // the second component is the empty string. If allocation fails,
8409 // this function returns a failure. If flattening succeeds, this
8410 // function returns the sequential string that is now the first
8411 // component of the cons string.
8413 // Degenerate cons strings are handled specially by the garbage
8414 // collector (see IsShortcutCandidate).
8416 static inline Handle<String> Flatten(Handle<String> string,
8417 PretenureFlag pretenure = NOT_TENURED);
8419 // Tries to return the content of a flat string as a structure holding either
8420 // a flat vector of char or of uc16.
8421 // If the string isn't flat, and therefore doesn't have flat content, the
8422 // returned structure will report so, and can't provide a vector of either
8424 FlatContent GetFlatContent();
8426 // Returns the parent of a sliced string or first part of a flat cons string.
8427 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8428 inline String* GetUnderlying();
8430 // String equality operations.
8431 inline bool Equals(String* other);
8432 inline static bool Equals(Handle<String> one, Handle<String> two);
8433 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8434 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8435 bool IsTwoByteEqualTo(Vector<const uc16> str);
8437 // Return a UTF8 representation of the string. The string is null
8438 // terminated but may optionally contain nulls. Length is returned
8439 // in length_output if length_output is not a null pointer The string
8440 // should be nearly flat, otherwise the performance of this method may
8441 // be very slow (quadratic in the length). Setting robustness_flag to
8442 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8443 // handles unexpected data without causing assert failures and it does not
8444 // do any heap allocations. This is useful when printing stack traces.
8445 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8446 RobustnessFlag robustness_flag,
8447 int offset, int length,
8448 int* length_output = 0);
8449 base::SmartArrayPointer<char> ToCString(
8450 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8451 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8452 int* length_output = 0);
8454 // Return a 16 bit Unicode representation of the string.
8455 // The string should be nearly flat, otherwise the performance of
8456 // of this method may be very bad. Setting robustness_flag to
8457 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8458 // handles unexpected data without causing assert failures and it does not
8459 // do any heap allocations. This is useful when printing stack traces.
8460 base::SmartArrayPointer<uc16> ToWideCString(
8461 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8463 bool ComputeArrayIndex(uint32_t* index);
8466 bool MakeExternal(v8::String::ExternalStringResource* resource);
8467 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8470 inline bool AsArrayIndex(uint32_t* index);
8472 DECLARE_CAST(String)
8474 void PrintOn(FILE* out);
8476 // For use during stack traces. Performs rudimentary sanity check.
8479 // Dispatched behavior.
8480 void StringShortPrint(StringStream* accumulator);
8481 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8482 #if defined(DEBUG) || defined(OBJECT_PRINT)
8483 char* ToAsciiArray();
8485 DECLARE_PRINTER(String)
8486 DECLARE_VERIFIER(String)
8488 inline bool IsFlat();
8490 // Layout description.
8491 static const int kLengthOffset = Name::kSize;
8492 static const int kSize = kLengthOffset + kPointerSize;
8494 // Maximum number of characters to consider when trying to convert a string
8495 // value into an array index.
8496 static const int kMaxArrayIndexSize = 10;
8497 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8500 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8501 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8502 static const int kMaxUtf16CodeUnit = 0xffff;
8503 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8505 // Value of hash field containing computed hash equal to zero.
8506 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8508 // Maximal string length.
8509 static const int kMaxLength = (1 << 28) - 16;
8511 // Max length for computing hash. For strings longer than this limit the
8512 // string length is used as the hash value.
8513 static const int kMaxHashCalcLength = 16383;
8515 // Limit for truncation in short printing.
8516 static const int kMaxShortPrintLength = 1024;
8518 // Support for regular expressions.
8519 const uc16* GetTwoByteData(unsigned start);
8521 // Helper function for flattening strings.
8522 template <typename sinkchar>
8523 static void WriteToFlat(String* source,
8528 // The return value may point to the first aligned word containing the first
8529 // non-one-byte character, rather than directly to the non-one-byte character.
8530 // If the return value is >= the passed length, the entire string was
8532 static inline int NonAsciiStart(const char* chars, int length) {
8533 const char* start = chars;
8534 const char* limit = chars + length;
8536 if (length >= kIntptrSize) {
8537 // Check unaligned bytes.
8538 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8539 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8540 return static_cast<int>(chars - start);
8544 // Check aligned words.
8545 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8546 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8547 while (chars + sizeof(uintptr_t) <= limit) {
8548 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8549 return static_cast<int>(chars - start);
8551 chars += sizeof(uintptr_t);
8554 // Check remaining unaligned bytes.
8555 while (chars < limit) {
8556 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8557 return static_cast<int>(chars - start);
8562 return static_cast<int>(chars - start);
8565 static inline bool IsAscii(const char* chars, int length) {
8566 return NonAsciiStart(chars, length) >= length;
8569 static inline bool IsAscii(const uint8_t* chars, int length) {
8571 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8574 static inline int NonOneByteStart(const uc16* chars, int length) {
8575 const uc16* limit = chars + length;
8576 const uc16* start = chars;
8577 while (chars < limit) {
8578 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8581 return static_cast<int>(chars - start);
8584 static inline bool IsOneByte(const uc16* chars, int length) {
8585 return NonOneByteStart(chars, length) >= length;
8588 template<class Visitor>
8589 static inline ConsString* VisitFlat(Visitor* visitor,
8593 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8594 bool include_ending_line);
8596 // Use the hash field to forward to the canonical internalized string
8597 // when deserializing an internalized string.
8598 inline void SetForwardedInternalizedString(String* string);
8599 inline String* GetForwardedInternalizedString();
8603 friend class StringTableInsertionKey;
8605 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8606 PretenureFlag tenure);
8608 // Slow case of String::Equals. This implementation works on any strings
8609 // but it is most efficient on strings that are almost flat.
8610 bool SlowEquals(String* other);
8612 static bool SlowEquals(Handle<String> one, Handle<String> two);
8614 // Slow case of AsArrayIndex.
8615 bool SlowAsArrayIndex(uint32_t* index);
8617 // Compute and set the hash code.
8618 uint32_t ComputeAndSetHash();
8620 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8624 // The SeqString abstract class captures sequential string values.
8625 class SeqString: public String {
8627 DECLARE_CAST(SeqString)
8629 // Layout description.
8630 static const int kHeaderSize = String::kSize;
8632 // Truncate the string in-place if possible and return the result.
8633 // In case of new_length == 0, the empty string is returned without
8634 // truncating the original string.
8635 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8638 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8642 // The OneByteString class captures sequential one-byte string objects.
8643 // Each character in the OneByteString is an one-byte character.
8644 class SeqOneByteString: public SeqString {
8646 static const bool kHasOneByteEncoding = true;
8648 // Dispatched behavior.
8649 inline uint16_t SeqOneByteStringGet(int index);
8650 inline void SeqOneByteStringSet(int index, uint16_t value);
8652 // Get the address of the characters in this string.
8653 inline Address GetCharsAddress();
8655 inline uint8_t* GetChars();
8657 DECLARE_CAST(SeqOneByteString)
8659 // Garbage collection support. This method is called by the
8660 // garbage collector to compute the actual size of an OneByteString
8662 inline int SeqOneByteStringSize(InstanceType instance_type);
8664 // Computes the size for an OneByteString instance of a given length.
8665 static int SizeFor(int length) {
8666 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8669 // Maximal memory usage for a single sequential one-byte string.
8670 static const int kMaxSize = 512 * MB - 1;
8671 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8674 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8678 // The TwoByteString class captures sequential unicode string objects.
8679 // Each character in the TwoByteString is a two-byte uint16_t.
8680 class SeqTwoByteString: public SeqString {
8682 static const bool kHasOneByteEncoding = false;
8684 // Dispatched behavior.
8685 inline uint16_t SeqTwoByteStringGet(int index);
8686 inline void SeqTwoByteStringSet(int index, uint16_t value);
8688 // Get the address of the characters in this string.
8689 inline Address GetCharsAddress();
8691 inline uc16* GetChars();
8694 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8696 DECLARE_CAST(SeqTwoByteString)
8698 // Garbage collection support. This method is called by the
8699 // garbage collector to compute the actual size of a TwoByteString
8701 inline int SeqTwoByteStringSize(InstanceType instance_type);
8703 // Computes the size for a TwoByteString instance of a given length.
8704 static int SizeFor(int length) {
8705 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8708 // Maximal memory usage for a single sequential two-byte string.
8709 static const int kMaxSize = 512 * MB - 1;
8710 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8711 String::kMaxLength);
8714 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8718 // The ConsString class describes string values built by using the
8719 // addition operator on strings. A ConsString is a pair where the
8720 // first and second components are pointers to other string values.
8721 // One or both components of a ConsString can be pointers to other
8722 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8723 // are non-ConsString string values. The string value represented by
8724 // a ConsString can be obtained by concatenating the leaf string
8725 // values in a left-to-right depth-first traversal of the tree.
8726 class ConsString: public String {
8728 // First string of the cons cell.
8729 inline String* first();
8730 // Doesn't check that the result is a string, even in debug mode. This is
8731 // useful during GC where the mark bits confuse the checks.
8732 inline Object* unchecked_first();
8733 inline void set_first(String* first,
8734 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8736 // Second string of the cons cell.
8737 inline String* second();
8738 // Doesn't check that the result is a string, even in debug mode. This is
8739 // useful during GC where the mark bits confuse the checks.
8740 inline Object* unchecked_second();
8741 inline void set_second(String* second,
8742 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8744 // Dispatched behavior.
8745 uint16_t ConsStringGet(int index);
8747 DECLARE_CAST(ConsString)
8749 // Layout description.
8750 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8751 static const int kSecondOffset = kFirstOffset + kPointerSize;
8752 static const int kSize = kSecondOffset + kPointerSize;
8754 // Minimum length for a cons string.
8755 static const int kMinLength = 13;
8757 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8760 DECLARE_VERIFIER(ConsString)
8763 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8767 // The Sliced String class describes strings that are substrings of another
8768 // sequential string. The motivation is to save time and memory when creating
8769 // a substring. A Sliced String is described as a pointer to the parent,
8770 // the offset from the start of the parent string and the length. Using
8771 // a Sliced String therefore requires unpacking of the parent string and
8772 // adding the offset to the start address. A substring of a Sliced String
8773 // are not nested since the double indirection is simplified when creating
8774 // such a substring.
8775 // Currently missing features are:
8776 // - handling externalized parent strings
8777 // - external strings as parent
8778 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8779 class SlicedString: public String {
8781 inline String* parent();
8782 inline void set_parent(String* parent,
8783 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8784 inline int offset() const;
8785 inline void set_offset(int offset);
8787 // Dispatched behavior.
8788 uint16_t SlicedStringGet(int index);
8790 DECLARE_CAST(SlicedString)
8792 // Layout description.
8793 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8794 static const int kOffsetOffset = kParentOffset + kPointerSize;
8795 static const int kSize = kOffsetOffset + kPointerSize;
8797 // Minimum length for a sliced string.
8798 static const int kMinLength = 13;
8800 typedef FixedBodyDescriptor<kParentOffset,
8801 kOffsetOffset + kPointerSize, kSize>
8804 DECLARE_VERIFIER(SlicedString)
8807 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8811 // The ExternalString class describes string values that are backed by
8812 // a string resource that lies outside the V8 heap. ExternalStrings
8813 // consist of the length field common to all strings, a pointer to the
8814 // external resource. It is important to ensure (externally) that the
8815 // resource is not deallocated while the ExternalString is live in the
8818 // The API expects that all ExternalStrings are created through the
8819 // API. Therefore, ExternalStrings should not be used internally.
8820 class ExternalString: public String {
8822 DECLARE_CAST(ExternalString)
8824 // Layout description.
8825 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8826 static const int kShortSize = kResourceOffset + kPointerSize;
8827 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8828 static const int kSize = kResourceDataOffset + kPointerSize;
8830 static const int kMaxShortLength =
8831 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8833 // Return whether external string is short (data pointer is not cached).
8834 inline bool is_short();
8836 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8839 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8843 // The ExternalOneByteString class is an external string backed by an
8845 class ExternalOneByteString : public ExternalString {
8847 static const bool kHasOneByteEncoding = true;
8849 typedef v8::String::ExternalOneByteStringResource Resource;
8851 // The underlying resource.
8852 inline const Resource* resource();
8853 inline void set_resource(const Resource* buffer);
8855 // Update the pointer cache to the external character array.
8856 // The cached pointer is always valid, as the external character array does =
8857 // not move during lifetime. Deserialization is the only exception, after
8858 // which the pointer cache has to be refreshed.
8859 inline void update_data_cache();
8861 inline const uint8_t* GetChars();
8863 // Dispatched behavior.
8864 inline uint16_t ExternalOneByteStringGet(int index);
8866 DECLARE_CAST(ExternalOneByteString)
8868 // Garbage collection support.
8869 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8871 template <typename StaticVisitor>
8872 inline void ExternalOneByteStringIterateBody();
8875 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8879 // The ExternalTwoByteString class is an external string backed by a UTF-16
8881 class ExternalTwoByteString: public ExternalString {
8883 static const bool kHasOneByteEncoding = false;
8885 typedef v8::String::ExternalStringResource Resource;
8887 // The underlying string resource.
8888 inline const Resource* resource();
8889 inline void set_resource(const Resource* buffer);
8891 // Update the pointer cache to the external character array.
8892 // The cached pointer is always valid, as the external character array does =
8893 // not move during lifetime. Deserialization is the only exception, after
8894 // which the pointer cache has to be refreshed.
8895 inline void update_data_cache();
8897 inline const uint16_t* GetChars();
8899 // Dispatched behavior.
8900 inline uint16_t ExternalTwoByteStringGet(int index);
8903 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8905 DECLARE_CAST(ExternalTwoByteString)
8907 // Garbage collection support.
8908 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8910 template<typename StaticVisitor>
8911 inline void ExternalTwoByteStringIterateBody();
8914 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8918 // Utility superclass for stack-allocated objects that must be updated
8919 // on gc. It provides two ways for the gc to update instances, either
8920 // iterating or updating after gc.
8921 class Relocatable BASE_EMBEDDED {
8923 explicit inline Relocatable(Isolate* isolate);
8924 inline virtual ~Relocatable();
8925 virtual void IterateInstance(ObjectVisitor* v) { }
8926 virtual void PostGarbageCollection() { }
8928 static void PostGarbageCollectionProcessing(Isolate* isolate);
8929 static int ArchiveSpacePerThread();
8930 static char* ArchiveState(Isolate* isolate, char* to);
8931 static char* RestoreState(Isolate* isolate, char* from);
8932 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8933 static void Iterate(ObjectVisitor* v, Relocatable* top);
8934 static char* Iterate(ObjectVisitor* v, char* t);
8942 // A flat string reader provides random access to the contents of a
8943 // string independent of the character width of the string. The handle
8944 // must be valid as long as the reader is being used.
8945 class FlatStringReader : public Relocatable {
8947 FlatStringReader(Isolate* isolate, Handle<String> str);
8948 FlatStringReader(Isolate* isolate, Vector<const char> input);
8949 void PostGarbageCollection();
8950 inline uc32 Get(int index);
8951 template <typename Char>
8952 inline Char Get(int index);
8953 int length() { return length_; }
8962 // This maintains an off-stack representation of the stack frames required
8963 // to traverse a ConsString, allowing an entirely iterative and restartable
8964 // traversal of the entire string
8965 class ConsStringIterator {
8967 inline ConsStringIterator() {}
8968 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8969 Reset(cons_string, offset);
8971 inline void Reset(ConsString* cons_string, int offset = 0) {
8973 // Next will always return NULL.
8974 if (cons_string == NULL) return;
8975 Initialize(cons_string, offset);
8977 // Returns NULL when complete.
8978 inline String* Next(int* offset_out) {
8980 if (depth_ == 0) return NULL;
8981 return Continue(offset_out);
8985 static const int kStackSize = 32;
8986 // Use a mask instead of doing modulo operations for stack wrapping.
8987 static const int kDepthMask = kStackSize-1;
8988 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8989 static inline int OffsetForDepth(int depth);
8991 inline void PushLeft(ConsString* string);
8992 inline void PushRight(ConsString* string);
8993 inline void AdjustMaximumDepth();
8995 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8996 void Initialize(ConsString* cons_string, int offset);
8997 String* Continue(int* offset_out);
8998 String* NextLeaf(bool* blew_stack);
8999 String* Search(int* offset_out);
9001 // Stack must always contain only frames for which right traversal
9002 // has not yet been performed.
9003 ConsString* frames_[kStackSize];
9008 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9012 class StringCharacterStream {
9014 inline StringCharacterStream(String* string,
9016 inline uint16_t GetNext();
9017 inline bool HasMore();
9018 inline void Reset(String* string, int offset = 0);
9019 inline void VisitOneByteString(const uint8_t* chars, int length);
9020 inline void VisitTwoByteString(const uint16_t* chars, int length);
9023 ConsStringIterator iter_;
9026 const uint8_t* buffer8_;
9027 const uint16_t* buffer16_;
9029 const uint8_t* end_;
9030 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9034 template <typename T>
9035 class VectorIterator {
9037 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9038 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9039 T GetNext() { return data_[index_++]; }
9040 bool has_more() { return index_ < data_.length(); }
9042 Vector<const T> data_;
9047 // The Oddball describes objects null, undefined, true, and false.
9048 class Oddball: public HeapObject {
9050 // [to_string]: Cached to_string computed at startup.
9051 DECL_ACCESSORS(to_string, String)
9053 // [to_number]: Cached to_number computed at startup.
9054 DECL_ACCESSORS(to_number, Object)
9056 // [typeof]: Cached type_of computed at startup.
9057 DECL_ACCESSORS(type_of, String)
9059 inline byte kind() const;
9060 inline void set_kind(byte kind);
9062 DECLARE_CAST(Oddball)
9064 // Dispatched behavior.
9065 DECLARE_VERIFIER(Oddball)
9067 // Initialize the fields.
9068 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9069 const char* to_string, Handle<Object> to_number,
9070 const char* type_of, byte kind);
9072 // Layout description.
9073 static const int kToStringOffset = HeapObject::kHeaderSize;
9074 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9075 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9076 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9077 static const int kSize = kKindOffset + kPointerSize;
9079 static const byte kFalse = 0;
9080 static const byte kTrue = 1;
9081 static const byte kNotBooleanMask = ~1;
9082 static const byte kTheHole = 2;
9083 static const byte kNull = 3;
9084 static const byte kArgumentMarker = 4;
9085 static const byte kUndefined = 5;
9086 static const byte kUninitialized = 6;
9087 static const byte kOther = 7;
9088 static const byte kException = 8;
9090 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9091 kSize> BodyDescriptor;
9093 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9094 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9095 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9098 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9102 class Cell: public HeapObject {
9104 // [value]: value of the cell.
9105 DECL_ACCESSORS(value, Object)
9109 static inline Cell* FromValueAddress(Address value) {
9110 Object* result = FromAddress(value - kValueOffset);
9111 return static_cast<Cell*>(result);
9114 inline Address ValueAddress() {
9115 return address() + kValueOffset;
9118 // Dispatched behavior.
9119 DECLARE_PRINTER(Cell)
9120 DECLARE_VERIFIER(Cell)
9122 // Layout description.
9123 static const int kValueOffset = HeapObject::kHeaderSize;
9124 static const int kSize = kValueOffset + kPointerSize;
9126 typedef FixedBodyDescriptor<kValueOffset,
9127 kValueOffset + kPointerSize,
9128 kSize> BodyDescriptor;
9131 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9135 class PropertyCell : public HeapObject {
9137 // [property_details]: details of the global property.
9138 DECL_ACCESSORS(property_details_raw, Object)
9139 // [value]: value of the global property.
9140 DECL_ACCESSORS(value, Object)
9141 // [dependent_code]: dependent code that depends on the type of the global
9143 DECL_ACCESSORS(dependent_code, DependentCode)
9145 inline PropertyDetails property_details();
9146 inline void set_property_details(PropertyDetails details);
9148 PropertyCellConstantType GetConstantType();
9150 // Computes the new type of the cell's contents for the given value, but
9151 // without actually modifying the details.
9152 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9153 Handle<Object> value,
9154 PropertyDetails details);
9155 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9156 Handle<Object> value, PropertyDetails details);
9158 static Handle<PropertyCell> InvalidateEntry(
9159 Handle<GlobalDictionary> dictionary, int entry);
9161 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9162 Handle<Object> new_value);
9164 DECLARE_CAST(PropertyCell)
9166 // Dispatched behavior.
9167 DECLARE_PRINTER(PropertyCell)
9168 DECLARE_VERIFIER(PropertyCell)
9170 // Layout description.
9171 static const int kDetailsOffset = HeapObject::kHeaderSize;
9172 static const int kValueOffset = kDetailsOffset + kPointerSize;
9173 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9174 static const int kSize = kDependentCodeOffset + kPointerSize;
9176 static const int kPointerFieldsBeginOffset = kValueOffset;
9177 static const int kPointerFieldsEndOffset = kSize;
9179 typedef FixedBodyDescriptor<kValueOffset,
9181 kSize> BodyDescriptor;
9184 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9188 class WeakCell : public HeapObject {
9190 inline Object* value() const;
9192 // This should not be called by anyone except GC.
9193 inline void clear();
9195 // This should not be called by anyone except allocator.
9196 inline void initialize(HeapObject* value);
9198 inline bool cleared() const;
9200 DECL_ACCESSORS(next, Object)
9202 inline void clear_next(Heap* heap);
9204 inline bool next_cleared();
9206 DECLARE_CAST(WeakCell)
9208 DECLARE_PRINTER(WeakCell)
9209 DECLARE_VERIFIER(WeakCell)
9211 // Layout description.
9212 static const int kValueOffset = HeapObject::kHeaderSize;
9213 static const int kNextOffset = kValueOffset + kPointerSize;
9214 static const int kSize = kNextOffset + kPointerSize;
9216 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9219 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9223 // The JSProxy describes EcmaScript Harmony proxies
9224 class JSProxy: public JSReceiver {
9226 // [handler]: The handler property.
9227 DECL_ACCESSORS(handler, Object)
9229 // [hash]: The hash code property (undefined if not initialized yet).
9230 DECL_ACCESSORS(hash, Object)
9232 DECLARE_CAST(JSProxy)
9234 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9235 Handle<JSProxy> proxy,
9236 Handle<Object> receiver,
9239 // If the handler defines an accessor property with a setter, invoke it.
9240 // If it defines an accessor property without a setter, or a data property
9241 // that is read-only, throw. In all these cases set '*done' to true,
9242 // otherwise set it to false.
9244 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9245 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9246 Handle<Object> value, LanguageMode language_mode, bool* done);
9248 MUST_USE_RESULT static Maybe<PropertyAttributes>
9249 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9250 Handle<Object> receiver,
9252 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9253 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9254 Handle<Object> value, LanguageMode language_mode);
9256 // Turn the proxy into an (empty) JSObject.
9257 static void Fix(Handle<JSProxy> proxy);
9259 // Initializes the body after the handler slot.
9260 inline void InitializeBody(int object_size, Object* value);
9262 // Invoke a trap by name. If the trap does not exist on this's handler,
9263 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9264 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9265 Handle<JSProxy> proxy,
9267 Handle<Object> derived_trap,
9269 Handle<Object> args[]);
9271 // Dispatched behavior.
9272 DECLARE_PRINTER(JSProxy)
9273 DECLARE_VERIFIER(JSProxy)
9275 // Layout description. We add padding so that a proxy has the same
9276 // size as a virgin JSObject. This is essential for becoming a JSObject
9278 static const int kHandlerOffset = HeapObject::kHeaderSize;
9279 static const int kHashOffset = kHandlerOffset + kPointerSize;
9280 static const int kPaddingOffset = kHashOffset + kPointerSize;
9281 static const int kSize = JSObject::kHeaderSize;
9282 static const int kHeaderSize = kPaddingOffset;
9283 static const int kPaddingSize = kSize - kPaddingOffset;
9285 STATIC_ASSERT(kPaddingSize >= 0);
9287 typedef FixedBodyDescriptor<kHandlerOffset,
9289 kSize> BodyDescriptor;
9292 friend class JSReceiver;
9294 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9295 Handle<JSProxy> proxy, Handle<Name> name);
9297 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9298 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9300 MUST_USE_RESULT Object* GetIdentityHash();
9302 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9304 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9308 class JSFunctionProxy: public JSProxy {
9310 // [call_trap]: The call trap.
9311 DECL_ACCESSORS(call_trap, JSReceiver)
9313 // [construct_trap]: The construct trap.
9314 DECL_ACCESSORS(construct_trap, Object)
9316 DECLARE_CAST(JSFunctionProxy)
9318 // Dispatched behavior.
9319 DECLARE_PRINTER(JSFunctionProxy)
9320 DECLARE_VERIFIER(JSFunctionProxy)
9322 // Layout description.
9323 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9324 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9325 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9326 static const int kSize = JSFunction::kSize;
9327 static const int kPaddingSize = kSize - kPaddingOffset;
9329 STATIC_ASSERT(kPaddingSize >= 0);
9331 typedef FixedBodyDescriptor<kHandlerOffset,
9332 kConstructTrapOffset + kPointerSize,
9333 kSize> BodyDescriptor;
9336 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9340 class JSCollection : public JSObject {
9342 // [table]: the backing hash table
9343 DECL_ACCESSORS(table, Object)
9345 static const int kTableOffset = JSObject::kHeaderSize;
9346 static const int kSize = kTableOffset + kPointerSize;
9349 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9353 // The JSSet describes EcmaScript Harmony sets
9354 class JSSet : public JSCollection {
9358 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9359 static void Clear(Handle<JSSet> set);
9361 // Dispatched behavior.
9362 DECLARE_PRINTER(JSSet)
9363 DECLARE_VERIFIER(JSSet)
9366 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9370 // The JSMap describes EcmaScript Harmony maps
9371 class JSMap : public JSCollection {
9375 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9376 static void Clear(Handle<JSMap> map);
9378 // Dispatched behavior.
9379 DECLARE_PRINTER(JSMap)
9380 DECLARE_VERIFIER(JSMap)
9383 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9387 // OrderedHashTableIterator is an iterator that iterates over the keys and
9388 // values of an OrderedHashTable.
9390 // The iterator has a reference to the underlying OrderedHashTable data,
9391 // [table], as well as the current [index] the iterator is at.
9393 // When the OrderedHashTable is rehashed it adds a reference from the old table
9394 // to the new table as well as storing enough data about the changes so that the
9395 // iterator [index] can be adjusted accordingly.
9397 // When the [Next] result from the iterator is requested, the iterator checks if
9398 // there is a newer table that it needs to transition to.
9399 template<class Derived, class TableType>
9400 class OrderedHashTableIterator: public JSObject {
9402 // [table]: the backing hash table mapping keys to values.
9403 DECL_ACCESSORS(table, Object)
9405 // [index]: The index into the data table.
9406 DECL_ACCESSORS(index, Object)
9408 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9409 DECL_ACCESSORS(kind, Object)
9412 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9415 static const int kTableOffset = JSObject::kHeaderSize;
9416 static const int kIndexOffset = kTableOffset + kPointerSize;
9417 static const int kKindOffset = kIndexOffset + kPointerSize;
9418 static const int kSize = kKindOffset + kPointerSize;
9426 // Whether the iterator has more elements. This needs to be called before
9427 // calling |CurrentKey| and/or |CurrentValue|.
9430 // Move the index forward one.
9432 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9435 // Populates the array with the next key and value and then moves the iterator
9437 // This returns the |kind| or 0 if the iterator is already at the end.
9438 Smi* Next(JSArray* value_array);
9440 // Returns the current key of the iterator. This should only be called when
9441 // |HasMore| returns true.
9442 inline Object* CurrentKey();
9445 // Transitions the iterator to the non obsolete backing store. This is a NOP
9446 // if the [table] is not obsolete.
9449 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9453 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9456 // Dispatched behavior.
9457 DECLARE_PRINTER(JSSetIterator)
9458 DECLARE_VERIFIER(JSSetIterator)
9460 DECLARE_CAST(JSSetIterator)
9462 // Called by |Next| to populate the array. This allows the subclasses to
9463 // populate the array differently.
9464 inline void PopulateValueArray(FixedArray* array);
9467 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9471 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9474 // Dispatched behavior.
9475 DECLARE_PRINTER(JSMapIterator)
9476 DECLARE_VERIFIER(JSMapIterator)
9478 DECLARE_CAST(JSMapIterator)
9480 // Called by |Next| to populate the array. This allows the subclasses to
9481 // populate the array differently.
9482 inline void PopulateValueArray(FixedArray* array);
9485 // Returns the current value of the iterator. This should only be called when
9486 // |HasMore| returns true.
9487 inline Object* CurrentValue();
9489 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9493 // ES6 section 25.1.1.3 The IteratorResult Interface
9494 class JSIteratorResult final : public JSObject {
9496 // [done]: This is the result status of an iterator next method call. If the
9497 // end of the iterator was reached done is true. If the end was not reached
9498 // done is false and a [value] is available.
9499 DECL_ACCESSORS(done, Object)
9501 // [value]: If [done] is false, this is the current iteration element value.
9502 // If [done] is true, this is the return value of the iterator, if it supplied
9503 // one. If the iterator does not have a return value, value is undefined.
9504 // In that case, the value property may be absent from the conforming object
9505 // if it does not inherit an explicit value property.
9506 DECL_ACCESSORS(value, Object)
9508 // Dispatched behavior.
9509 DECLARE_PRINTER(JSIteratorResult)
9510 DECLARE_VERIFIER(JSIteratorResult)
9512 DECLARE_CAST(JSIteratorResult)
9514 static const int kValueOffset = JSObject::kHeaderSize;
9515 static const int kDoneOffset = kValueOffset + kPointerSize;
9516 static const int kSize = kDoneOffset + kPointerSize;
9518 // Indices of in-object properties.
9519 static const int kValueIndex = 0;
9520 static const int kDoneIndex = 1;
9523 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9527 // Base class for both JSWeakMap and JSWeakSet
9528 class JSWeakCollection: public JSObject {
9530 // [table]: the backing hash table mapping keys to values.
9531 DECL_ACCESSORS(table, Object)
9533 // [next]: linked list of encountered weak maps during GC.
9534 DECL_ACCESSORS(next, Object)
9536 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9537 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9538 Handle<Object> value, int32_t hash);
9539 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9542 static const int kTableOffset = JSObject::kHeaderSize;
9543 static const int kNextOffset = kTableOffset + kPointerSize;
9544 static const int kSize = kNextOffset + kPointerSize;
9547 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9551 // The JSWeakMap describes EcmaScript Harmony weak maps
9552 class JSWeakMap: public JSWeakCollection {
9554 DECLARE_CAST(JSWeakMap)
9556 // Dispatched behavior.
9557 DECLARE_PRINTER(JSWeakMap)
9558 DECLARE_VERIFIER(JSWeakMap)
9561 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9565 // The JSWeakSet describes EcmaScript Harmony weak sets
9566 class JSWeakSet: public JSWeakCollection {
9568 DECLARE_CAST(JSWeakSet)
9570 // Dispatched behavior.
9571 DECLARE_PRINTER(JSWeakSet)
9572 DECLARE_VERIFIER(JSWeakSet)
9575 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9579 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9580 enum class SharedFlag { kNotShared, kShared };
9583 class JSArrayBuffer: public JSObject {
9585 // [backing_store]: backing memory for this array
9586 DECL_ACCESSORS(backing_store, void)
9588 // [byte_length]: length in bytes
9589 DECL_ACCESSORS(byte_length, Object)
9591 inline uint32_t bit_field() const;
9592 inline void set_bit_field(uint32_t bits);
9594 inline bool is_external();
9595 inline void set_is_external(bool value);
9597 inline bool is_neuterable();
9598 inline void set_is_neuterable(bool value);
9600 inline bool was_neutered();
9601 inline void set_was_neutered(bool value);
9603 inline bool is_shared();
9604 inline void set_is_shared(bool value);
9606 DECLARE_CAST(JSArrayBuffer)
9610 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9611 bool is_external, void* data, size_t allocated_length,
9612 SharedFlag shared = SharedFlag::kNotShared);
9614 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9615 Isolate* isolate, size_t allocated_length,
9616 bool initialize = true,
9617 SharedFlag shared = SharedFlag::kNotShared);
9619 // Dispatched behavior.
9620 DECLARE_PRINTER(JSArrayBuffer)
9621 DECLARE_VERIFIER(JSArrayBuffer)
9623 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9624 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9625 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9626 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9627 static const int kBitFieldOffset = kBitFieldSlot;
9629 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9631 static const int kSize = kBitFieldSlot + kPointerSize;
9633 static const int kSizeWithInternalFields =
9634 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9636 class IsExternal : public BitField<bool, 1, 1> {};
9637 class IsNeuterable : public BitField<bool, 2, 1> {};
9638 class WasNeutered : public BitField<bool, 3, 1> {};
9639 class IsShared : public BitField<bool, 4, 1> {};
9642 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9646 class JSArrayBufferView: public JSObject {
9648 // [buffer]: ArrayBuffer that this typed array views.
9649 DECL_ACCESSORS(buffer, Object)
9651 // [byte_offset]: offset of typed array in bytes.
9652 DECL_ACCESSORS(byte_offset, Object)
9654 // [byte_length]: length of typed array in bytes.
9655 DECL_ACCESSORS(byte_length, Object)
9657 DECLARE_CAST(JSArrayBufferView)
9659 DECLARE_VERIFIER(JSArrayBufferView)
9661 inline bool WasNeutered() const;
9663 static const int kBufferOffset = JSObject::kHeaderSize;
9664 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9665 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9666 static const int kViewSize = kByteLengthOffset + kPointerSize;
9670 DECL_ACCESSORS(raw_byte_offset, Object)
9671 DECL_ACCESSORS(raw_byte_length, Object)
9674 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9678 class JSTypedArray: public JSArrayBufferView {
9680 // [length]: length of typed array in elements.
9681 DECL_ACCESSORS(length, Object)
9682 inline uint32_t length_value() const;
9684 DECLARE_CAST(JSTypedArray)
9686 ExternalArrayType type();
9687 size_t element_size();
9689 Handle<JSArrayBuffer> GetBuffer();
9691 // Dispatched behavior.
9692 DECLARE_PRINTER(JSTypedArray)
9693 DECLARE_VERIFIER(JSTypedArray)
9695 static const int kLengthOffset = kViewSize + kPointerSize;
9696 static const int kSize = kLengthOffset + kPointerSize;
9698 static const int kSizeWithInternalFields =
9699 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9702 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9703 Handle<JSTypedArray> typed_array);
9705 DECL_ACCESSORS(raw_length, Object)
9708 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9712 class JSDataView: public JSArrayBufferView {
9714 DECLARE_CAST(JSDataView)
9716 // Dispatched behavior.
9717 DECLARE_PRINTER(JSDataView)
9718 DECLARE_VERIFIER(JSDataView)
9720 static const int kSize = kViewSize;
9722 static const int kSizeWithInternalFields =
9723 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9726 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9730 // Foreign describes objects pointing from JavaScript to C structures.
9731 class Foreign: public HeapObject {
9733 // [address]: field containing the address.
9734 inline Address foreign_address();
9735 inline void set_foreign_address(Address value);
9737 DECLARE_CAST(Foreign)
9739 // Dispatched behavior.
9740 inline void ForeignIterateBody(ObjectVisitor* v);
9742 template<typename StaticVisitor>
9743 inline void ForeignIterateBody();
9745 // Dispatched behavior.
9746 DECLARE_PRINTER(Foreign)
9747 DECLARE_VERIFIER(Foreign)
9749 // Layout description.
9751 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9752 static const int kSize = kForeignAddressOffset + kPointerSize;
9754 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9757 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9761 // The JSArray describes JavaScript Arrays
9762 // Such an array can be in one of two modes:
9763 // - fast, backing storage is a FixedArray and length <= elements.length();
9764 // Please note: push and pop can be used to grow and shrink the array.
9765 // - slow, backing storage is a HashTable with numbers as keys.
9766 class JSArray: public JSObject {
9768 // [length]: The length property.
9769 DECL_ACCESSORS(length, Object)
9771 // Overload the length setter to skip write barrier when the length
9772 // is set to a smi. This matches the set function on FixedArray.
9773 inline void set_length(Smi* length);
9775 static bool HasReadOnlyLength(Handle<JSArray> array);
9776 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9777 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9779 // Initialize the array with the given capacity. The function may
9780 // fail due to out-of-memory situations, but only if the requested
9781 // capacity is non-zero.
9782 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9784 // If the JSArray has fast elements, and new_length would result in
9785 // normalization, returns true.
9786 bool SetLengthWouldNormalize(uint32_t new_length);
9787 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9789 // Initializes the array to a certain length.
9790 inline bool AllowsSetLength();
9792 static void SetLength(Handle<JSArray> array, uint32_t length);
9793 // Same as above but will also queue splice records if |array| is observed.
9794 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9797 // Set the content of the array to the content of storage.
9798 static inline void SetContent(Handle<JSArray> array,
9799 Handle<FixedArrayBase> storage);
9801 DECLARE_CAST(JSArray)
9803 // Dispatched behavior.
9804 DECLARE_PRINTER(JSArray)
9805 DECLARE_VERIFIER(JSArray)
9807 // Number of element slots to pre-allocate for an empty array.
9808 static const int kPreallocatedArrayElements = 4;
9810 // Layout description.
9811 static const int kLengthOffset = JSObject::kHeaderSize;
9812 static const int kSize = kLengthOffset + kPointerSize;
9815 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9819 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9820 Handle<Map> initial_map);
9823 // JSRegExpResult is just a JSArray with a specific initial map.
9824 // This initial map adds in-object properties for "index" and "input"
9825 // properties, as assigned by RegExp.prototype.exec, which allows
9826 // faster creation of RegExp exec results.
9827 // This class just holds constants used when creating the result.
9828 // After creation the result must be treated as a JSArray in all regards.
9829 class JSRegExpResult: public JSArray {
9831 // Offsets of object fields.
9832 static const int kIndexOffset = JSArray::kSize;
9833 static const int kInputOffset = kIndexOffset + kPointerSize;
9834 static const int kSize = kInputOffset + kPointerSize;
9835 // Indices of in-object properties.
9836 static const int kIndexIndex = 0;
9837 static const int kInputIndex = 1;
9839 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9843 class AccessorInfo: public Struct {
9845 DECL_ACCESSORS(name, Object)
9846 DECL_ACCESSORS(flag, Smi)
9847 DECL_ACCESSORS(expected_receiver_type, Object)
9849 inline bool all_can_read();
9850 inline void set_all_can_read(bool value);
9852 inline bool all_can_write();
9853 inline void set_all_can_write(bool value);
9855 inline bool is_special_data_property();
9856 inline void set_is_special_data_property(bool value);
9858 inline PropertyAttributes property_attributes();
9859 inline void set_property_attributes(PropertyAttributes attributes);
9861 // Checks whether the given receiver is compatible with this accessor.
9862 static bool IsCompatibleReceiverMap(Isolate* isolate,
9863 Handle<AccessorInfo> info,
9865 inline bool IsCompatibleReceiver(Object* receiver);
9867 DECLARE_CAST(AccessorInfo)
9869 // Dispatched behavior.
9870 DECLARE_VERIFIER(AccessorInfo)
9872 // Append all descriptors to the array that are not already there.
9873 // Return number added.
9874 static int AppendUnique(Handle<Object> descriptors,
9875 Handle<FixedArray> array,
9876 int valid_descriptors);
9878 static const int kNameOffset = HeapObject::kHeaderSize;
9879 static const int kFlagOffset = kNameOffset + kPointerSize;
9880 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9881 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9884 inline bool HasExpectedReceiverType();
9886 // Bit positions in flag.
9887 static const int kAllCanReadBit = 0;
9888 static const int kAllCanWriteBit = 1;
9889 static const int kSpecialDataProperty = 2;
9890 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9892 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9896 // An accessor must have a getter, but can have no setter.
9898 // When setting a property, V8 searches accessors in prototypes.
9899 // If an accessor was found and it does not have a setter,
9900 // the request is ignored.
9902 // If the accessor in the prototype has the READ_ONLY property attribute, then
9903 // a new value is added to the derived object when the property is set.
9904 // This shadows the accessor in the prototype.
9905 class ExecutableAccessorInfo: public AccessorInfo {
9907 DECL_ACCESSORS(getter, Object)
9908 DECL_ACCESSORS(setter, Object)
9909 DECL_ACCESSORS(data, Object)
9911 DECLARE_CAST(ExecutableAccessorInfo)
9913 // Dispatched behavior.
9914 DECLARE_PRINTER(ExecutableAccessorInfo)
9915 DECLARE_VERIFIER(ExecutableAccessorInfo)
9917 static const int kGetterOffset = AccessorInfo::kSize;
9918 static const int kSetterOffset = kGetterOffset + kPointerSize;
9919 static const int kDataOffset = kSetterOffset + kPointerSize;
9920 static const int kSize = kDataOffset + kPointerSize;
9922 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9925 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9929 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9930 // accessor can either be
9931 // * a pointer to a JavaScript function or proxy: a real accessor
9932 // * undefined: considered an accessor by the spec, too, strangely enough
9933 // * the hole: an accessor which has not been set
9934 // * a pointer to a map: a transition used to ensure map sharing
9935 class AccessorPair: public Struct {
9937 DECL_ACCESSORS(getter, Object)
9938 DECL_ACCESSORS(setter, Object)
9940 DECLARE_CAST(AccessorPair)
9942 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9944 inline Object* get(AccessorComponent component);
9945 inline void set(AccessorComponent component, Object* value);
9947 // Note: Returns undefined instead in case of a hole.
9948 Object* GetComponent(AccessorComponent component);
9950 // Set both components, skipping arguments which are a JavaScript null.
9951 inline void SetComponents(Object* getter, Object* setter);
9953 inline bool Equals(AccessorPair* pair);
9954 inline bool Equals(Object* getter_value, Object* setter_value);
9956 inline bool ContainsAccessor();
9958 // Dispatched behavior.
9959 DECLARE_PRINTER(AccessorPair)
9960 DECLARE_VERIFIER(AccessorPair)
9962 static const int kGetterOffset = HeapObject::kHeaderSize;
9963 static const int kSetterOffset = kGetterOffset + kPointerSize;
9964 static const int kSize = kSetterOffset + kPointerSize;
9967 // Strangely enough, in addition to functions and harmony proxies, the spec
9968 // requires us to consider undefined as a kind of accessor, too:
9970 // Object.defineProperty(obj, "foo", {get: undefined});
9971 // assertTrue("foo" in obj);
9972 inline bool IsJSAccessor(Object* obj);
9974 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9978 class AccessCheckInfo: public Struct {
9980 DECL_ACCESSORS(named_callback, Object)
9981 DECL_ACCESSORS(indexed_callback, Object)
9982 DECL_ACCESSORS(data, Object)
9984 DECLARE_CAST(AccessCheckInfo)
9986 // Dispatched behavior.
9987 DECLARE_PRINTER(AccessCheckInfo)
9988 DECLARE_VERIFIER(AccessCheckInfo)
9990 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9991 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9992 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9993 static const int kSize = kDataOffset + kPointerSize;
9996 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10000 class InterceptorInfo: public Struct {
10002 DECL_ACCESSORS(getter, Object)
10003 DECL_ACCESSORS(setter, Object)
10004 DECL_ACCESSORS(query, Object)
10005 DECL_ACCESSORS(deleter, Object)
10006 DECL_ACCESSORS(enumerator, Object)
10007 DECL_ACCESSORS(data, Object)
10008 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10009 DECL_BOOLEAN_ACCESSORS(all_can_read)
10010 DECL_BOOLEAN_ACCESSORS(non_masking)
10012 inline int flags() const;
10013 inline void set_flags(int flags);
10015 DECLARE_CAST(InterceptorInfo)
10017 // Dispatched behavior.
10018 DECLARE_PRINTER(InterceptorInfo)
10019 DECLARE_VERIFIER(InterceptorInfo)
10021 static const int kGetterOffset = HeapObject::kHeaderSize;
10022 static const int kSetterOffset = kGetterOffset + kPointerSize;
10023 static const int kQueryOffset = kSetterOffset + kPointerSize;
10024 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10025 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10026 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10027 static const int kFlagsOffset = kDataOffset + kPointerSize;
10028 static const int kSize = kFlagsOffset + kPointerSize;
10030 static const int kCanInterceptSymbolsBit = 0;
10031 static const int kAllCanReadBit = 1;
10032 static const int kNonMasking = 2;
10035 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10039 class CallHandlerInfo: public Struct {
10041 DECL_ACCESSORS(callback, Object)
10042 DECL_ACCESSORS(data, Object)
10044 DECLARE_CAST(CallHandlerInfo)
10046 // Dispatched behavior.
10047 DECLARE_PRINTER(CallHandlerInfo)
10048 DECLARE_VERIFIER(CallHandlerInfo)
10050 static const int kCallbackOffset = HeapObject::kHeaderSize;
10051 static const int kDataOffset = kCallbackOffset + kPointerSize;
10052 static const int kSize = kDataOffset + kPointerSize;
10055 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10059 class TemplateInfo: public Struct {
10061 DECL_ACCESSORS(tag, Object)
10062 inline int number_of_properties() const;
10063 inline void set_number_of_properties(int value);
10064 DECL_ACCESSORS(property_list, Object)
10065 DECL_ACCESSORS(property_accessors, Object)
10067 DECLARE_VERIFIER(TemplateInfo)
10069 static const int kTagOffset = HeapObject::kHeaderSize;
10070 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10071 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10072 static const int kPropertyAccessorsOffset =
10073 kPropertyListOffset + kPointerSize;
10074 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10077 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10081 class FunctionTemplateInfo: public TemplateInfo {
10083 DECL_ACCESSORS(serial_number, Object)
10084 DECL_ACCESSORS(call_code, Object)
10085 DECL_ACCESSORS(prototype_template, Object)
10086 DECL_ACCESSORS(parent_template, Object)
10087 DECL_ACCESSORS(named_property_handler, Object)
10088 DECL_ACCESSORS(indexed_property_handler, Object)
10089 DECL_ACCESSORS(instance_template, Object)
10090 DECL_ACCESSORS(class_name, Object)
10091 DECL_ACCESSORS(signature, Object)
10092 DECL_ACCESSORS(instance_call_handler, Object)
10093 DECL_ACCESSORS(access_check_info, Object)
10094 DECL_ACCESSORS(flag, Smi)
10096 inline int length() const;
10097 inline void set_length(int value);
10099 // Following properties use flag bits.
10100 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10101 DECL_BOOLEAN_ACCESSORS(undetectable)
10102 // If the bit is set, object instances created by this function
10103 // requires access check.
10104 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10105 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10106 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10107 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10108 DECL_BOOLEAN_ACCESSORS(instantiated)
10109 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10111 DECLARE_CAST(FunctionTemplateInfo)
10113 // Dispatched behavior.
10114 DECLARE_PRINTER(FunctionTemplateInfo)
10115 DECLARE_VERIFIER(FunctionTemplateInfo)
10117 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10118 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10119 static const int kPrototypeTemplateOffset =
10120 kCallCodeOffset + kPointerSize;
10121 static const int kParentTemplateOffset =
10122 kPrototypeTemplateOffset + kPointerSize;
10123 static const int kNamedPropertyHandlerOffset =
10124 kParentTemplateOffset + kPointerSize;
10125 static const int kIndexedPropertyHandlerOffset =
10126 kNamedPropertyHandlerOffset + kPointerSize;
10127 static const int kInstanceTemplateOffset =
10128 kIndexedPropertyHandlerOffset + kPointerSize;
10129 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10130 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10131 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10132 static const int kAccessCheckInfoOffset =
10133 kInstanceCallHandlerOffset + kPointerSize;
10134 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10135 static const int kLengthOffset = kFlagOffset + kPointerSize;
10136 static const int kSize = kLengthOffset + kPointerSize;
10138 // Returns true if |object| is an instance of this function template.
10139 bool IsTemplateFor(Object* object);
10140 bool IsTemplateFor(Map* map);
10142 // Returns the holder JSObject if the function can legally be called with this
10143 // receiver. Returns Heap::null_value() if the call is illegal.
10144 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10147 // Bit position in the flag, from least significant bit position.
10148 static const int kHiddenPrototypeBit = 0;
10149 static const int kUndetectableBit = 1;
10150 static const int kNeedsAccessCheckBit = 2;
10151 static const int kReadOnlyPrototypeBit = 3;
10152 static const int kRemovePrototypeBit = 4;
10153 static const int kDoNotCacheBit = 5;
10154 static const int kInstantiatedBit = 6;
10155 static const int kAcceptAnyReceiver = 7;
10157 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10161 class ObjectTemplateInfo: public TemplateInfo {
10163 DECL_ACCESSORS(constructor, Object)
10164 DECL_ACCESSORS(internal_field_count, Object)
10166 DECLARE_CAST(ObjectTemplateInfo)
10168 // Dispatched behavior.
10169 DECLARE_PRINTER(ObjectTemplateInfo)
10170 DECLARE_VERIFIER(ObjectTemplateInfo)
10172 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10173 static const int kInternalFieldCountOffset =
10174 kConstructorOffset + kPointerSize;
10175 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10179 class TypeSwitchInfo: public Struct {
10181 DECL_ACCESSORS(types, Object)
10183 DECLARE_CAST(TypeSwitchInfo)
10185 // Dispatched behavior.
10186 DECLARE_PRINTER(TypeSwitchInfo)
10187 DECLARE_VERIFIER(TypeSwitchInfo)
10189 static const int kTypesOffset = Struct::kHeaderSize;
10190 static const int kSize = kTypesOffset + kPointerSize;
10194 // The DebugInfo class holds additional information for a function being
10196 class DebugInfo: public Struct {
10198 // The shared function info for the source being debugged.
10199 DECL_ACCESSORS(shared, SharedFunctionInfo)
10200 // Code object for the patched code. This code object is the code object
10201 // currently active for the function.
10202 DECL_ACCESSORS(code, Code)
10203 // Fixed array holding status information for each active break point.
10204 DECL_ACCESSORS(break_points, FixedArray)
10206 // Check if there is a break point at a code position.
10207 bool HasBreakPoint(int code_position);
10208 // Get the break point info object for a code position.
10209 Object* GetBreakPointInfo(int code_position);
10210 // Clear a break point.
10211 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10213 Handle<Object> break_point_object);
10214 // Set a break point.
10215 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10216 int source_position, int statement_position,
10217 Handle<Object> break_point_object);
10218 // Get the break point objects for a code position.
10219 Handle<Object> GetBreakPointObjects(int code_position);
10220 // Find the break point info holding this break point object.
10221 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10222 Handle<Object> break_point_object);
10223 // Get the number of break points for this function.
10224 int GetBreakPointCount();
10226 DECLARE_CAST(DebugInfo)
10228 // Dispatched behavior.
10229 DECLARE_PRINTER(DebugInfo)
10230 DECLARE_VERIFIER(DebugInfo)
10232 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10233 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10234 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10235 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10237 static const int kEstimatedNofBreakPointsInFunction = 16;
10240 static const int kNoBreakPointInfo = -1;
10242 // Lookup the index in the break_points array for a code position.
10243 int GetBreakPointInfoIndex(int code_position);
10245 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10249 // The BreakPointInfo class holds information for break points set in a
10250 // function. The DebugInfo object holds a BreakPointInfo object for each code
10251 // position with one or more break points.
10252 class BreakPointInfo: public Struct {
10254 // The position in the code for the break point.
10255 DECL_ACCESSORS(code_position, Smi)
10256 // The position in the source for the break position.
10257 DECL_ACCESSORS(source_position, Smi)
10258 // The position in the source for the last statement before this break
10260 DECL_ACCESSORS(statement_position, Smi)
10261 // List of related JavaScript break points.
10262 DECL_ACCESSORS(break_point_objects, Object)
10264 // Removes a break point.
10265 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10266 Handle<Object> break_point_object);
10267 // Set a break point.
10268 static void SetBreakPoint(Handle<BreakPointInfo> info,
10269 Handle<Object> break_point_object);
10270 // Check if break point info has this break point object.
10271 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10272 Handle<Object> break_point_object);
10273 // Get the number of break points for this code position.
10274 int GetBreakPointCount();
10276 DECLARE_CAST(BreakPointInfo)
10278 // Dispatched behavior.
10279 DECLARE_PRINTER(BreakPointInfo)
10280 DECLARE_VERIFIER(BreakPointInfo)
10282 static const int kCodePositionIndex = Struct::kHeaderSize;
10283 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10284 static const int kStatementPositionIndex =
10285 kSourcePositionIndex + kPointerSize;
10286 static const int kBreakPointObjectsIndex =
10287 kStatementPositionIndex + kPointerSize;
10288 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10291 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10295 #undef DECL_BOOLEAN_ACCESSORS
10296 #undef DECL_ACCESSORS
10297 #undef DECLARE_CAST
10298 #undef DECLARE_VERIFIER
10300 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10301 V(kStringTable, "string_table", "(Internalized strings)") \
10302 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10303 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10304 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10305 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10306 V(kTop, "top", "(Isolate)") \
10307 V(kRelocatable, "relocatable", "(Relocatable)") \
10308 V(kDebug, "debug", "(Debugger)") \
10309 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10310 V(kHandleScope, "handlescope", "(Handle scope)") \
10311 V(kBuiltins, "builtins", "(Builtins)") \
10312 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10313 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10314 V(kThreadManager, "threadmanager", "(Thread manager)") \
10315 V(kStrongRoots, "strong roots", "(Strong roots)") \
10316 V(kExtensions, "Extensions", "(Extensions)")
10318 class VisitorSynchronization : public AllStatic {
10320 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10322 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10325 #undef DECLARE_ENUM
10327 static const char* const kTags[kNumberOfSyncTags];
10328 static const char* const kTagNames[kNumberOfSyncTags];
10331 // Abstract base class for visiting, and optionally modifying, the
10332 // pointers contained in Objects. Used in GC and serialization/deserialization.
10333 class ObjectVisitor BASE_EMBEDDED {
10335 virtual ~ObjectVisitor() {}
10337 // Visits a contiguous arrays of pointers in the half-open range
10338 // [start, end). Any or all of the values may be modified on return.
10339 virtual void VisitPointers(Object** start, Object** end) = 0;
10341 // Handy shorthand for visiting a single pointer.
10342 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10344 // Visit weak next_code_link in Code object.
10345 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10347 // To allow lazy clearing of inline caches the visitor has
10348 // a rich interface for iterating over Code objects..
10350 // Visits a code target in the instruction stream.
10351 virtual void VisitCodeTarget(RelocInfo* rinfo);
10353 // Visits a code entry in a JS function.
10354 virtual void VisitCodeEntry(Address entry_address);
10356 // Visits a global property cell reference in the instruction stream.
10357 virtual void VisitCell(RelocInfo* rinfo);
10359 // Visits a runtime entry in the instruction stream.
10360 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10362 // Visits the resource of an one-byte or two-byte string.
10363 virtual void VisitExternalOneByteString(
10364 v8::String::ExternalOneByteStringResource** resource) {}
10365 virtual void VisitExternalTwoByteString(
10366 v8::String::ExternalStringResource** resource) {}
10368 // Visits a debug call target in the instruction stream.
10369 virtual void VisitDebugTarget(RelocInfo* rinfo);
10371 // Visits the byte sequence in a function's prologue that contains information
10372 // about the code's age.
10373 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10375 // Visit pointer embedded into a code object.
10376 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10378 // Visits an external reference embedded into a code object.
10379 virtual void VisitExternalReference(RelocInfo* rinfo);
10381 // Visits an external reference.
10382 virtual void VisitExternalReference(Address* p) {}
10384 // Visits an (encoded) internal reference.
10385 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10387 // Visits a handle that has an embedder-assigned class ID.
10388 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10390 // Intended for serialization/deserialization checking: insert, or
10391 // check for the presence of, a tag at this position in the stream.
10392 // Also used for marking up GC roots in heap snapshots.
10393 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10397 class StructBodyDescriptor : public
10398 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10400 static inline int SizeOf(Map* map, HeapObject* object);
10404 // BooleanBit is a helper class for setting and getting a bit in an
10406 class BooleanBit : public AllStatic {
10408 static inline bool get(Smi* smi, int bit_position) {
10409 return get(smi->value(), bit_position);
10412 static inline bool get(int value, int bit_position) {
10413 return (value & (1 << bit_position)) != 0;
10416 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10417 return Smi::FromInt(set(smi->value(), bit_position, v));
10420 static inline int set(int value, int bit_position, bool v) {
10422 value |= (1 << bit_position);
10424 value &= ~(1 << bit_position);
10430 } } // namespace v8::internal
10432 #endif // V8_OBJECTS_H_