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