[runtime] Move binary operator fallbacks into the runtime.
[platform/upstream/v8.git] / src / objects.h
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.
4
5 #ifndef V8_OBJECTS_H_
6 #define V8_OBJECTS_H_
7
8 #include <iosfwd>
9
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"
20 #include "src/list.h"
21 #include "src/property-details.h"
22 #include "src/unicode.h"
23 #include "src/unicode-decoder.h"
24 #include "src/zone.h"
25
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
36 #endif
37
38
39 //
40 // Most object types in the V8 JavaScript are described in this file.
41 //
42 // Inheritance hierarchy:
43 // - Object
44 //   - Smi          (immediate small integer)
45 //   - HeapObject   (superclass for everything allocated in the heap)
46 //     - JSReceiver  (suitable for property access)
47 //       - JSObject
48 //         - JSArray
49 //         - JSArrayBuffer
50 //         - JSArrayBufferView
51 //           - JSTypedArray
52 //           - JSDataView
53 //         - JSCollection
54 //           - JSSet
55 //           - JSMap
56 //         - JSSetIterator
57 //         - JSMapIterator
58 //         - JSWeakCollection
59 //           - JSWeakMap
60 //           - JSWeakSet
61 //         - JSRegExp
62 //         - JSFunction
63 //         - JSGeneratorObject
64 //         - JSModule
65 //         - GlobalObject
66 //           - JSGlobalObject
67 //           - JSBuiltinsObject
68 //         - JSGlobalProxy
69 //         - JSValue
70 //           - JSDate
71 //         - JSMessageObject
72 //       - JSProxy
73 //         - JSFunctionProxy
74 //     - FixedArrayBase
75 //       - ByteArray
76 //       - BytecodeArray
77 //       - FixedArray
78 //         - DescriptorArray
79 //         - HashTable
80 //           - Dictionary
81 //           - StringTable
82 //           - CompilationCacheTable
83 //           - CodeCacheHashTable
84 //           - MapCache
85 //         - OrderedHashTable
86 //           - OrderedHashSet
87 //           - OrderedHashMap
88 //         - Context
89 //         - TypeFeedbackVector
90 //         - ScopeInfo
91 //         - TransitionArray
92 //         - ScriptContextTable
93 //         - WeakFixedArray
94 //       - FixedDoubleArray
95 //     - Name
96 //       - String
97 //         - SeqString
98 //           - SeqOneByteString
99 //           - SeqTwoByteString
100 //         - SlicedString
101 //         - ConsString
102 //         - ExternalString
103 //           - ExternalOneByteString
104 //           - ExternalTwoByteString
105 //         - InternalizedString
106 //           - SeqInternalizedString
107 //             - SeqOneByteInternalizedString
108 //             - SeqTwoByteInternalizedString
109 //           - ConsInternalizedString
110 //           - ExternalInternalizedString
111 //             - ExternalOneByteInternalizedString
112 //             - ExternalTwoByteInternalizedString
113 //       - Symbol
114 //     - HeapNumber
115 //     - Simd128Value
116 //       - Float32x4
117 //       - Int32x4
118 //       - Uint32x4
119 //       - Bool32x4
120 //       - Int16x8
121 //       - Uint16x8
122 //       - Bool16x8
123 //       - Int8x16
124 //       - Uint8x16
125 //       - Bool8x16
126 //     - Cell
127 //     - PropertyCell
128 //     - Code
129 //     - Map
130 //     - Oddball
131 //     - Foreign
132 //     - SharedFunctionInfo
133 //     - Struct
134 //       - Box
135 //       - AccessorInfo
136 //         - ExecutableAccessorInfo
137 //       - AccessorPair
138 //       - AccessCheckInfo
139 //       - InterceptorInfo
140 //       - CallHandlerInfo
141 //       - TemplateInfo
142 //         - FunctionTemplateInfo
143 //         - ObjectTemplateInfo
144 //       - Script
145 //       - TypeSwitchInfo
146 //       - DebugInfo
147 //       - BreakPointInfo
148 //       - CodeCache
149 //       - PrototypeInfo
150 //     - WeakCell
151 //
152 // Formats of Object*:
153 //  Smi:        [31 bit signed int] 0
154 //  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
155
156 namespace v8 {
157 namespace internal {
158
159 enum KeyedAccessStoreMode {
160   STANDARD_STORE,
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
168 };
169
170
171 // Valid hints for the abstract operation ToPrimitive,
172 // implemented according to ES6, section 7.1.1.
173 enum class ToPrimitiveHint { kDefault, kNumber, kString };
174
175
176 // Valid hints for the abstract operation OrdinaryToPrimitive,
177 // implemented according to ES6, section 7.1.1.
178 enum class OrdinaryToPrimitiveHint { kNumber, kString };
179
180
181 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
182
183
184 enum MutableMode {
185   MUTABLE,
186   IMMUTABLE
187 };
188
189
190 enum ExternalArrayType {
191   kExternalInt8Array = 1,
192   kExternalUint8Array,
193   kExternalInt16Array,
194   kExternalUint16Array,
195   kExternalInt32Array,
196   kExternalUint32Array,
197   kExternalFloat32Array,
198   kExternalFloat64Array,
199   kExternalUint8ClampedArray,
200 };
201
202
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;
208 }
209
210
211 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
212     KeyedAccessStoreMode store_mode) {
213   if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
214     return store_mode;
215   }
216   if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
217     return STORE_AND_GROW_NO_TRANSITION;
218   }
219   return STANDARD_STORE;
220 }
221
222
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;
226 }
227
228
229 enum IcCheckType { ELEMENT, PROPERTY };
230
231
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 {
237   SKIP_WRITE_BARRIER,
238   UPDATE_WEAK_WRITE_BARRIER,
239   UPDATE_WRITE_BARRIER
240 };
241
242
243 // Indicates whether a value can be loaded as a constant.
244 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
245
246
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
252 };
253
254
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 };
261
262
263 // Indicates whether transitions can be added to a source map or not.
264 enum TransitionFlag {
265   INSERT_TRANSITION,
266   OMIT_TRANSITION
267 };
268
269
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,
275   PROPERTY_TRANSITION,
276   SPECIAL_TRANSITION
277 };
278
279
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 {
283   ALL_DESCRIPTORS,
284   OWN_DESCRIPTORS
285 };
286
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.
294 enum MarkingParity {
295   NO_MARKING_PARITY,
296   ODD_MARKING_PARITY,
297   EVEN_MARKING_PARITY
298 };
299
300 // ICs store extra state in a Code object. The default extra state is
301 // kNoExtraICState.
302 typedef int ExtraICState;
303 static const ExtraICState kNoExtraICState = 0;
304
305 // Instance size sentinel for objects of variable size.
306 const int kVariableSizeSentinel = 0;
307
308 // We may store the unsigned bit field as signed Smi value and do not
309 // use the sign bit.
310 const int kStubMajorKeyBits = 7;
311 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
312
313 // All Maps have a field instance_type containing a InstanceType.
314 // It describes the type of the instances.
315 //
316 // As an example, a JavaScript object is a heap object and its map
317 // instance_type is JS_OBJECT_TYPE.
318 //
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).
327 //
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
331 // Object::IsString.
332 //
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)                                   \
337   V(STRING_TYPE)                                                \
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)              \
349                                                                 \
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) \
358                                                                 \
359   V(SYMBOL_TYPE)                                                \
360   V(SIMD128_VALUE_TYPE)                                         \
361                                                                 \
362   V(MAP_TYPE)                                                   \
363   V(CODE_TYPE)                                                  \
364   V(ODDBALL_TYPE)                                               \
365   V(CELL_TYPE)                                                  \
366   V(PROPERTY_CELL_TYPE)                                         \
367                                                                 \
368   V(HEAP_NUMBER_TYPE)                                           \
369   V(MUTABLE_HEAP_NUMBER_TYPE)                                   \
370   V(FOREIGN_TYPE)                                               \
371   V(BYTE_ARRAY_TYPE)                                            \
372   V(BYTECODE_ARRAY_TYPE)                                        \
373   V(FREE_SPACE_TYPE)                                            \
374                                                                 \
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)                             \
384                                                                 \
385   V(FILLER_TYPE)                                                \
386                                                                 \
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)                                       \
400   V(SCRIPT_TYPE)                                                \
401   V(CODE_CACHE_TYPE)                                            \
402   V(POLYMORPHIC_CODE_CACHE_TYPE)                                \
403   V(TYPE_FEEDBACK_INFO_TYPE)                                    \
404   V(ALIASED_ARGUMENTS_ENTRY_TYPE)                               \
405   V(BOX_TYPE)                                                   \
406   V(PROTOTYPE_INFO_TYPE)                                        \
407   V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE)              \
408                                                                 \
409   V(FIXED_ARRAY_TYPE)                                           \
410   V(FIXED_DOUBLE_ARRAY_TYPE)                                    \
411   V(SHARED_FUNCTION_INFO_TYPE)                                  \
412   V(WEAK_CELL_TYPE)                                             \
413                                                                 \
414   V(JS_MESSAGE_OBJECT_TYPE)                                     \
415                                                                 \
416   V(JS_VALUE_TYPE)                                              \
417   V(JS_DATE_TYPE)                                               \
418   V(JS_OBJECT_TYPE)                                             \
419   V(JS_CONTEXT_EXTENSION_OBJECT_TYPE)                           \
420   V(JS_GENERATOR_OBJECT_TYPE)                                   \
421   V(JS_MODULE_TYPE)                                             \
422   V(JS_GLOBAL_OBJECT_TYPE)                                      \
423   V(JS_BUILTINS_OBJECT_TYPE)                                    \
424   V(JS_GLOBAL_PROXY_TYPE)                                       \
425   V(JS_ARRAY_TYPE)                                              \
426   V(JS_ARRAY_BUFFER_TYPE)                                       \
427   V(JS_TYPED_ARRAY_TYPE)                                        \
428   V(JS_DATA_VIEW_TYPE)                                          \
429   V(JS_PROXY_TYPE)                                              \
430   V(JS_SET_TYPE)                                                \
431   V(JS_MAP_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)                                           \
437   V(JS_REGEXP_TYPE)                                             \
438                                                                 \
439   V(JS_FUNCTION_TYPE)                                           \
440   V(JS_FUNCTION_PROXY_TYPE)                                     \
441   V(DEBUG_INFO_TYPE)                                            \
442   V(BREAK_POINT_INFO_TYPE)
443
444
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,             \
450     OneByteString)                                                            \
451   V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString)             \
452   V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string,       \
453     ConsOneByteString)                                                        \
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,      \
458     ExternalString)                                                           \
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)                                       \
471                                                                               \
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)
495
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?
501 //
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
504 // manually.
505 #define STRUCT_LIST(V)                                                       \
506   V(BOX, Box, box)                                                           \
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)
529
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;
536
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;
542
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;
548
549 // If bit 7 is clear, the low-order 2 bits indicate the representation
550 // of the string.
551 const uint32_t kStringRepresentationMask = 0x03;
552 enum StringRepresentationTag {
553   kSeqStringTag = 0x0,
554   kConsStringTag = 0x1,
555   kExternalStringTag = 0x2,
556   kSlicedStringTag = 0x3
557 };
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
566
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));
571
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;
576
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;
581
582
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 =
590     kIsNotStringMask |
591     kIsNotInternalizedMask |
592     kStringRepresentationMask;
593 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
594
595 static inline bool IsShortcutCandidate(int type) {
596   return ((type & kShortcutTypeMask) == kShortcutTypeTag);
597 }
598
599
600 enum InstanceType {
601   // String types.
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 |
612       kInternalizedTag,
613   SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
614                                             kShortExternalStringTag |
615                                             kInternalizedTag,
616   SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
617       EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
618       kInternalizedTag,
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,
628   SLICED_STRING_TYPE =
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 |
638       kNotInternalizedTag,
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 |
645       kNotInternalizedTag,
646
647   // Non-string names
648   SYMBOL_TYPE = kNotStringTag,  // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
649
650   // Other primitives (cannot contain non-map-word pointers to heap objects).
651   HEAP_NUMBER_TYPE,
652   SIMD128_VALUE_TYPE,
653   ODDBALL_TYPE,  // LAST_PRIMITIVE_TYPE
654
655   // Objects allocated in their own spaces (never in new space).
656   MAP_TYPE,
657   CODE_TYPE,
658
659   // "Data", objects that cannot contain non-map-word pointers to heap
660   // objects.
661   MUTABLE_HEAP_NUMBER_TYPE,
662   FOREIGN_TYPE,
663   BYTE_ARRAY_TYPE,
664   BYTECODE_ARRAY_TYPE,
665   FREE_SPACE_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
677
678   // Structs.
679   DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
680   DECLARED_ACCESSOR_INFO_TYPE,
681   EXECUTABLE_ACCESSOR_INFO_TYPE,
682   ACCESSOR_PAIR_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,
688   SIGNATURE_INFO_TYPE,
689   TYPE_SWITCH_INFO_TYPE,
690   ALLOCATION_SITE_TYPE,
691   ALLOCATION_MEMENTO_TYPE,
692   SCRIPT_TYPE,
693   CODE_CACHE_TYPE,
694   POLYMORPHIC_CODE_CACHE_TYPE,
695   TYPE_FEEDBACK_INFO_TYPE,
696   ALIASED_ARGUMENTS_ENTRY_TYPE,
697   BOX_TYPE,
698   DEBUG_INFO_TYPE,
699   BREAK_POINT_INFO_TYPE,
700   FIXED_ARRAY_TYPE,
701   SHARED_FUNCTION_INFO_TYPE,
702   CELL_TYPE,
703   WEAK_CELL_TYPE,
704   PROPERTY_CELL_TYPE,
705   PROTOTYPE_INFO_TYPE,
706   SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
707
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,
717   JS_DATE_TYPE,
718   JS_OBJECT_TYPE,
719   JS_CONTEXT_EXTENSION_OBJECT_TYPE,
720   JS_GENERATOR_OBJECT_TYPE,
721   JS_MODULE_TYPE,
722   JS_GLOBAL_OBJECT_TYPE,
723   JS_BUILTINS_OBJECT_TYPE,
724   JS_GLOBAL_PROXY_TYPE,
725   JS_ARRAY_TYPE,
726   JS_ARRAY_BUFFER_TYPE,
727   JS_TYPED_ARRAY_TYPE,
728   JS_DATA_VIEW_TYPE,
729   JS_SET_TYPE,
730   JS_MAP_TYPE,
731   JS_SET_ITERATOR_TYPE,
732   JS_MAP_ITERATOR_TYPE,
733   JS_ITERATOR_RESULT_TYPE,
734   JS_WEAK_MAP_TYPE,
735   JS_WEAK_SET_TYPE,
736   JS_REGEXP_TYPE,
737   JS_FUNCTION_TYPE,  // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
738
739   // Pseudo-types
740   FIRST_TYPE = 0x0,
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,
758   // or functions.
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
776 };
777
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);
782
783
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)
794
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
800 };
801
802
803 enum CompareResult {
804   LESS      = -1,
805   EQUAL     =  0,
806   GREATER   =  1,
807
808   NOT_EQUAL = GREATER
809 };
810
811
812 #define DECL_BOOLEAN_ACCESSORS(name)   \
813   inline bool name() const;            \
814   inline void set_##name(bool value);  \
815
816
817 #define DECL_ACCESSORS(name, type)                                      \
818   inline type* name() const;                                            \
819   inline void set_##name(type* value,                                   \
820                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
821
822
823 #define DECLARE_CAST(type)                              \
824   INLINE(static type* cast(Object* object));            \
825   INLINE(static const type* cast(const Object* object));
826
827
828 class AccessorPair;
829 class AllocationSite;
830 class AllocationSiteCreationContext;
831 class AllocationSiteUsageContext;
832 class Cell;
833 class ConsString;
834 class ElementsAccessor;
835 class FixedArrayBase;
836 class FunctionLiteral;
837 class GlobalObject;
838 class JSBuiltinsObject;
839 class LayoutDescriptor;
840 class LookupIterator;
841 class ObjectHashTable;
842 class ObjectVisitor;
843 class PropertyCell;
844 class SafepointEntry;
845 class SharedFunctionInfo;
846 class StringStream;
847 class TypeFeedbackInfo;
848 class TypeFeedbackVector;
849 class WeakCell;
850
851 // We cannot just say "class HeapType;" if it is created from a template... =8-?
852 template<class> class TypeImpl;
853 struct HeapTypeConfig;
854 typedef TypeImpl<HeapTypeConfig> HeapType;
855
856
857 // A template-ized version of the IsXXX functions.
858 template <class C> inline bool Is(Object* obj);
859
860 #ifdef VERIFY_HEAP
861 #define DECLARE_VERIFIER(Name) void Name##Verify();
862 #else
863 #define DECLARE_VERIFIER(Name)
864 #endif
865
866 #ifdef OBJECT_PRINT
867 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os);  // NOLINT
868 #else
869 #define DECLARE_PRINTER(Name)
870 #endif
871
872
873 #define OBJECT_TYPE_LIST(V) \
874   V(Smi)                    \
875   V(HeapObject)             \
876   V(Number)
877
878 #define HEAP_OBJECT_TYPE_LIST(V)   \
879   V(HeapNumber)                    \
880   V(MutableHeapNumber)             \
881   V(Simd128Value)                  \
882   V(Float32x4)                     \
883   V(Int32x4)                       \
884   V(Uint32x4)                      \
885   V(Bool32x4)                      \
886   V(Int16x8)                       \
887   V(Uint16x8)                      \
888   V(Bool16x8)                      \
889   V(Int8x16)                       \
890   V(Uint8x16)                      \
891   V(Bool8x16)                      \
892   V(Name)                          \
893   V(UniqueName)                    \
894   V(String)                        \
895   V(SeqString)                     \
896   V(ExternalString)                \
897   V(ConsString)                    \
898   V(SlicedString)                  \
899   V(ExternalTwoByteString)         \
900   V(ExternalOneByteString)         \
901   V(SeqTwoByteString)              \
902   V(SeqOneByteString)              \
903   V(InternalizedString)            \
904   V(Symbol)                        \
905                                    \
906   V(FixedTypedArrayBase)           \
907   V(FixedUint8Array)               \
908   V(FixedInt8Array)                \
909   V(FixedUint16Array)              \
910   V(FixedInt16Array)               \
911   V(FixedUint32Array)              \
912   V(FixedInt32Array)               \
913   V(FixedFloat32Array)             \
914   V(FixedFloat64Array)             \
915   V(FixedUint8ClampedArray)        \
916   V(ByteArray)                     \
917   V(BytecodeArray)                 \
918   V(FreeSpace)                     \
919   V(JSReceiver)                    \
920   V(JSObject)                      \
921   V(JSContextExtensionObject)      \
922   V(JSGeneratorObject)             \
923   V(JSModule)                      \
924   V(LayoutDescriptor)              \
925   V(Map)                           \
926   V(DescriptorArray)               \
927   V(TransitionArray)               \
928   V(TypeFeedbackVector)            \
929   V(DeoptimizationInputData)       \
930   V(DeoptimizationOutputData)      \
931   V(DependentCode)                 \
932   V(HandlerTable)                  \
933   V(FixedArray)                    \
934   V(FixedDoubleArray)              \
935   V(WeakFixedArray)                \
936   V(ArrayList)                     \
937   V(Context)                       \
938   V(ScriptContextTable)            \
939   V(NativeContext)                 \
940   V(ScopeInfo)                     \
941   V(JSFunction)                    \
942   V(Code)                          \
943   V(Oddball)                       \
944   V(SharedFunctionInfo)            \
945   V(JSValue)                       \
946   V(JSDate)                        \
947   V(JSMessageObject)               \
948   V(StringWrapper)                 \
949   V(Foreign)                       \
950   V(Boolean)                       \
951   V(JSArray)                       \
952   V(JSArrayBuffer)                 \
953   V(JSArrayBufferView)             \
954   V(JSTypedArray)                  \
955   V(JSDataView)                    \
956   V(JSProxy)                       \
957   V(JSFunctionProxy)               \
958   V(JSSet)                         \
959   V(JSMap)                         \
960   V(JSSetIterator)                 \
961   V(JSMapIterator)                 \
962   V(JSIteratorResult)              \
963   V(JSWeakCollection)              \
964   V(JSWeakMap)                     \
965   V(JSWeakSet)                     \
966   V(JSRegExp)                      \
967   V(HashTable)                     \
968   V(Dictionary)                    \
969   V(StringTable)                   \
970   V(NormalizedMapCache)            \
971   V(CompilationCacheTable)         \
972   V(CodeCacheHashTable)            \
973   V(PolymorphicCodeCacheHashTable) \
974   V(MapCache)                      \
975   V(Primitive)                     \
976   V(GlobalObject)                  \
977   V(JSGlobalObject)                \
978   V(JSBuiltinsObject)              \
979   V(JSGlobalProxy)                 \
980   V(UndetectableObject)            \
981   V(AccessCheckNeeded)             \
982   V(Cell)                          \
983   V(PropertyCell)                  \
984   V(WeakCell)                      \
985   V(ObjectHashTable)               \
986   V(WeakHashTable)                 \
987   V(OrderedHashTable)
988
989 // Object is the abstract superclass for all classes in the
990 // object hierarchy.
991 // Object does not use any virtual functions to avoid the
992 // allocation of the C++ vtable.
993 // Since both Smi and HeapObject are subclasses of Object no
994 // data members can be present in Object.
995 class Object {
996  public:
997   // Type testing.
998   bool IsObject() const { return true; }
999
1000 #define IS_TYPE_FUNCTION_DECL(type_)  INLINE(bool Is##type_() const);
1001   OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1002   HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1003 #undef IS_TYPE_FUNCTION_DECL
1004
1005   // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1006   // a keyed store is of the form a[expression] = foo.
1007   enum StoreFromKeyed {
1008     MAY_BE_STORE_FROM_KEYED,
1009     CERTAINLY_NOT_STORE_FROM_KEYED
1010   };
1011
1012   INLINE(bool IsFixedArrayBase() const);
1013   INLINE(bool IsExternal() const);
1014   INLINE(bool IsAccessorInfo() const);
1015
1016   INLINE(bool IsStruct() const);
1017 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1018   INLINE(bool Is##Name() const);
1019   STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1020 #undef DECLARE_STRUCT_PREDICATE
1021
1022   // ES6, section 7.2.3 IsCallable.
1023   INLINE(bool IsCallable() const);
1024
1025   INLINE(bool IsSpecObject()) const;
1026   // TODO(rossberg): IsSpecFunction should be removed in favor of IsCallable.
1027   INLINE(bool IsSpecFunction()) const;
1028   INLINE(bool IsTemplateInfo()) const;
1029   INLINE(bool IsNameDictionary() const);
1030   INLINE(bool IsGlobalDictionary() const);
1031   INLINE(bool IsSeededNumberDictionary() const);
1032   INLINE(bool IsUnseededNumberDictionary() const);
1033   INLINE(bool IsOrderedHashSet() const);
1034   INLINE(bool IsOrderedHashMap() const);
1035   static bool IsPromise(Handle<Object> object);
1036
1037   // Oddball testing.
1038   INLINE(bool IsUndefined() const);
1039   INLINE(bool IsNull() const);
1040   INLINE(bool IsTheHole() const);
1041   INLINE(bool IsException() const);
1042   INLINE(bool IsUninitialized() const);
1043   INLINE(bool IsTrue() const);
1044   INLINE(bool IsFalse() const);
1045   INLINE(bool IsArgumentsMarker() const);
1046
1047   // Filler objects (fillers and free space objects).
1048   INLINE(bool IsFiller() const);
1049
1050   // Extract the number.
1051   inline double Number();
1052   INLINE(bool IsNaN() const);
1053   INLINE(bool IsMinusZero() const);
1054   bool ToInt32(int32_t* value);
1055   bool ToUint32(uint32_t* value);
1056
1057   inline Representation OptimalRepresentation();
1058
1059   inline ElementsKind OptimalElementsKind();
1060
1061   inline bool FitsRepresentation(Representation representation);
1062
1063   // Checks whether two valid primitive encodings of a property name resolve to
1064   // the same logical property. E.g., the smi 1, the string "1" and the double
1065   // 1 all refer to the same property, so this helper will return true.
1066   inline bool KeyEquals(Object* other);
1067
1068   Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1069
1070   inline static Handle<Object> NewStorageFor(Isolate* isolate,
1071                                              Handle<Object> object,
1072                                              Representation representation);
1073
1074   inline static Handle<Object> WrapForRead(Isolate* isolate,
1075                                            Handle<Object> object,
1076                                            Representation representation);
1077
1078   // Returns true if the object is of the correct type to be used as a
1079   // implementation of a JSObject's elements.
1080   inline bool HasValidElements();
1081
1082   inline bool HasSpecificClassOf(String* name);
1083
1084   bool BooleanValue();                                      // ECMA-262 9.2.
1085
1086   // ES6 section 7.2.13 Strict Equality Comparison
1087   bool StrictEquals(Object* that);
1088
1089   // Convert to a JSObject if needed.
1090   // native_context is used when creating wrapper object.
1091   static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1092                                                  Handle<Object> object);
1093   MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1094       Isolate* isolate, Handle<Object> object, Handle<Context> context);
1095
1096   // ES6 section 7.1.14 ToPropertyKey
1097   MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1098                                                          Handle<Object> input);
1099
1100   // ES6 section 7.1.1 ToPrimitive
1101   MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1102       Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1103
1104   // ES6 section 7.1.3 ToNumber
1105   MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1106
1107   // ES6 section 7.1.12 ToString
1108   MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1109                                                       Handle<Object> input);
1110
1111   // ES6 section 7.3.9 GetMethod
1112   MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1113       Handle<JSReceiver> receiver, Handle<Name> name);
1114
1115   // ES6 section 12.5.6 The typeof Operator
1116   static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1117
1118   // ES6 section 12.6 Multiplicative Operators
1119   MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1120       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1121       Strength strength = Strength::WEAK);
1122   MUST_USE_RESULT static MaybeHandle<Object> Divide(
1123       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1124       Strength strength = Strength::WEAK);
1125   MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1126       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1127       Strength strength = Strength::WEAK);
1128
1129   // ES6 section 12.7 Additive Operators
1130   MUST_USE_RESULT static MaybeHandle<Object> Add(
1131       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1132       Strength strength = Strength::WEAK);
1133   MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1134       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1135       Strength strength = Strength::WEAK);
1136
1137   // ES6 section 12.8 Bitwise Shift Operators
1138   MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1139       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1140       Strength strength = Strength::WEAK);
1141   MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1142       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1143       Strength strength = Strength::WEAK);
1144   MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1145       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1146       Strength strength = Strength::WEAK);
1147
1148   // ES6 section 12.11 Binary Bitwise Operators
1149   MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1150       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1151       Strength strength = Strength::WEAK);
1152   MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1153       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1154       Strength strength = Strength::WEAK);
1155   MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1156       Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1157       Strength strength = Strength::WEAK);
1158
1159   MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1160       LookupIterator* it, LanguageMode language_mode = SLOPPY);
1161
1162   // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1163   MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1164       Handle<Object> object, Handle<Name> name, Handle<Object> value,
1165       LanguageMode language_mode,
1166       StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1167
1168   MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1169       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1170       StoreFromKeyed store_mode);
1171
1172   MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1173       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1174       StoreFromKeyed store_mode);
1175
1176   MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1177       LookupIterator* it, LanguageMode language_mode);
1178   MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1179       Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1180       LanguageMode language_mode);
1181   MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1182       LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1183   MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1184       Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1185       Handle<Object> value, LanguageMode language_mode);
1186   MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1187       Isolate* isolate, Handle<Object> name, Handle<Object> value,
1188       LanguageMode language_mode);
1189   MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1190       LookupIterator* it, Handle<Object> value);
1191   MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1192       LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1193       LanguageMode language_mode, StoreFromKeyed store_mode);
1194   MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1195       Handle<Object> object, Handle<Name> name,
1196       LanguageMode language_mode = SLOPPY);
1197   MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1198       Isolate* isolate, Handle<Object> object, const char* key,
1199       LanguageMode language_mode = SLOPPY);
1200   MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1201       Handle<Object> object, Handle<Name> name,
1202       LanguageMode language_mode = SLOPPY);
1203
1204   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1205       LookupIterator* it, LanguageMode language_mode);
1206   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1207       LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1208
1209   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1210       Handle<Object> receiver,
1211       Handle<JSReceiver> getter);
1212   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1213       Handle<Object> receiver,
1214       Handle<JSReceiver> setter,
1215       Handle<Object> value);
1216
1217   MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1218       Isolate* isolate, Handle<Object> object, uint32_t index,
1219       LanguageMode language_mode = SLOPPY);
1220
1221   MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1222       Isolate* isolate, Handle<Object> object, uint32_t index,
1223       Handle<Object> value, LanguageMode language_mode);
1224
1225   static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1226       Isolate* isolate, Handle<Object> receiver);
1227
1228   bool HasInPrototypeChain(Isolate* isolate, Object* object);
1229
1230   // Returns the permanent hash code associated with this object. May return
1231   // undefined if not yet created.
1232   Object* GetHash();
1233
1234   // Returns undefined for JSObjects, but returns the hash code for simple
1235   // objects.  This avoids a double lookup in the cases where we know we will
1236   // add the hash to the JSObject if it does not already exist.
1237   Object* GetSimpleHash();
1238
1239   // Returns the permanent hash code associated with this object depending on
1240   // the actual object type. May create and store a hash code if needed and none
1241   // exists.
1242   static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1243
1244   // Checks whether this object has the same value as the given one.  This
1245   // function is implemented according to ES5, section 9.12 and can be used
1246   // to implement the Harmony "egal" function.
1247   bool SameValue(Object* other);
1248
1249   // Checks whether this object has the same value as the given one.
1250   // +0 and -0 are treated equal. Everything else is the same as SameValue.
1251   // This function is implemented according to ES6, section 7.2.4 and is used
1252   // by ES6 Map and Set.
1253   bool SameValueZero(Object* other);
1254
1255   // Tries to convert an object to an array length. Returns true and sets the
1256   // output parameter if it succeeds.
1257   inline bool ToArrayLength(uint32_t* index);
1258
1259   // Tries to convert an object to an array index. Returns true and sets the
1260   // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1261   // allow kMaxUInt32.
1262   inline bool ToArrayIndex(uint32_t* index);
1263
1264   // Returns true if this is a JSValue containing a string and the index is
1265   // < the length of the string.  Used to implement [] on strings.
1266   inline bool IsStringObjectWithCharacterAt(uint32_t index);
1267
1268   DECLARE_VERIFIER(Object)
1269 #ifdef VERIFY_HEAP
1270   // Verify a pointer is a valid object pointer.
1271   static void VerifyPointer(Object* p);
1272 #endif
1273
1274   inline void VerifyApiCallResultType();
1275
1276   // Prints this object without details.
1277   void ShortPrint(FILE* out = stdout);
1278
1279   // Prints this object without details to a message accumulator.
1280   void ShortPrint(StringStream* accumulator);
1281
1282   void ShortPrint(std::ostream& os);  // NOLINT
1283
1284   DECLARE_CAST(Object)
1285
1286   // Layout description.
1287   static const int kHeaderSize = 0;  // Object does not take up any space.
1288
1289 #ifdef OBJECT_PRINT
1290   // For our gdb macros, we should perhaps change these in the future.
1291   void Print();
1292
1293   // Prints this object with details.
1294   void Print(std::ostream& os);  // NOLINT
1295 #else
1296   void Print() { ShortPrint(); }
1297   void Print(std::ostream& os) { ShortPrint(os); }  // NOLINT
1298 #endif
1299
1300  private:
1301   friend class LookupIterator;
1302   friend class PrototypeIterator;
1303
1304   // Return the map of the root of object's prototype chain.
1305   Map* GetRootMap(Isolate* isolate);
1306
1307   // Helper for SetProperty and SetSuperProperty.
1308   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1309       LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1310       StoreFromKeyed store_mode, bool* found);
1311
1312   DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1313 };
1314
1315
1316 // In objects.h to be usable without objects-inl.h inclusion.
1317 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1318 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1319
1320
1321 struct Brief {
1322   explicit Brief(const Object* const v) : value(v) {}
1323   const Object* value;
1324 };
1325
1326
1327 std::ostream& operator<<(std::ostream& os, const Brief& v);
1328
1329
1330 // Smi represents integer Numbers that can be stored in 31 bits.
1331 // Smis are immediate which means they are NOT allocated in the heap.
1332 // The this pointer has the following format: [31 bit signed int] 0
1333 // For long smis it has the following format:
1334 //     [32 bit signed int] [31 bits zero padding] 0
1335 // Smi stands for small integer.
1336 class Smi: public Object {
1337  public:
1338   // Returns the integer value.
1339   inline int value() const { return Internals::SmiValue(this); }
1340
1341   // Convert a value to a Smi object.
1342   static inline Smi* FromInt(int value) {
1343     DCHECK(Smi::IsValid(value));
1344     return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1345   }
1346
1347   static inline Smi* FromIntptr(intptr_t value) {
1348     DCHECK(Smi::IsValid(value));
1349     int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1350     return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1351   }
1352
1353   // Returns whether value can be represented in a Smi.
1354   static inline bool IsValid(intptr_t value) {
1355     bool result = Internals::IsValidSmi(value);
1356     DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1357     return result;
1358   }
1359
1360   DECLARE_CAST(Smi)
1361
1362   // Dispatched behavior.
1363   void SmiPrint(std::ostream& os) const;  // NOLINT
1364   DECLARE_VERIFIER(Smi)
1365
1366   static const int kMinValue =
1367       (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1368   static const int kMaxValue = -(kMinValue + 1);
1369
1370  private:
1371   DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1372 };
1373
1374
1375 // Heap objects typically have a map pointer in their first word.  However,
1376 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1377 // encoded in the first word.  The class MapWord is an abstraction of the
1378 // value in a heap object's first word.
1379 class MapWord BASE_EMBEDDED {
1380  public:
1381   // Normal state: the map word contains a map pointer.
1382
1383   // Create a map word from a map pointer.
1384   static inline MapWord FromMap(const Map* map);
1385
1386   // View this map word as a map pointer.
1387   inline Map* ToMap();
1388
1389
1390   // Scavenge collection: the map word of live objects in the from space
1391   // contains a forwarding address (a heap object pointer in the to space).
1392
1393   // True if this map word is a forwarding address for a scavenge
1394   // collection.  Only valid during a scavenge collection (specifically,
1395   // when all map words are heap object pointers, i.e. not during a full GC).
1396   inline bool IsForwardingAddress();
1397
1398   // Create a map word from a forwarding address.
1399   static inline MapWord FromForwardingAddress(HeapObject* object);
1400
1401   // View this map word as a forwarding address.
1402   inline HeapObject* ToForwardingAddress();
1403
1404   static inline MapWord FromRawValue(uintptr_t value) {
1405     return MapWord(value);
1406   }
1407
1408   inline uintptr_t ToRawValue() {
1409     return value_;
1410   }
1411
1412  private:
1413   // HeapObject calls the private constructor and directly reads the value.
1414   friend class HeapObject;
1415
1416   explicit MapWord(uintptr_t value) : value_(value) {}
1417
1418   uintptr_t value_;
1419 };
1420
1421
1422 // The content of an heap object (except for the map pointer). kTaggedValues
1423 // objects can contain both heap pointers and Smis, kMixedValues can contain
1424 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1425 // objects can contain raw values and Smis.
1426 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1427
1428
1429 // HeapObject is the superclass for all classes describing heap allocated
1430 // objects.
1431 class HeapObject: public Object {
1432  public:
1433   // [map]: Contains a map which contains the object's reflective
1434   // information.
1435   inline Map* map() const;
1436   inline void set_map(Map* value);
1437   // The no-write-barrier version.  This is OK if the object is white and in
1438   // new space, or if the value is an immortal immutable object, like the maps
1439   // of primitive (non-JS) objects like strings, heap numbers etc.
1440   inline void set_map_no_write_barrier(Map* value);
1441
1442   // Get the map using acquire load.
1443   inline Map* synchronized_map();
1444   inline MapWord synchronized_map_word() const;
1445
1446   // Set the map using release store
1447   inline void synchronized_set_map(Map* value);
1448   inline void synchronized_set_map_no_write_barrier(Map* value);
1449   inline void synchronized_set_map_word(MapWord map_word);
1450
1451   // During garbage collection, the map word of a heap object does not
1452   // necessarily contain a map pointer.
1453   inline MapWord map_word() const;
1454   inline void set_map_word(MapWord map_word);
1455
1456   // The Heap the object was allocated in. Used also to access Isolate.
1457   inline Heap* GetHeap() const;
1458
1459   // Convenience method to get current isolate.
1460   inline Isolate* GetIsolate() const;
1461
1462   // Converts an address to a HeapObject pointer.
1463   static inline HeapObject* FromAddress(Address address) {
1464     DCHECK_TAG_ALIGNED(address);
1465     return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1466   }
1467
1468   // Returns the address of this HeapObject.
1469   inline Address address() {
1470     return reinterpret_cast<Address>(this) - kHeapObjectTag;
1471   }
1472
1473   // Iterates over pointers contained in the object (including the Map)
1474   void Iterate(ObjectVisitor* v);
1475
1476   // Iterates over all pointers contained in the object except the
1477   // first map pointer.  The object type is given in the first
1478   // parameter. This function does not access the map pointer in the
1479   // object, and so is safe to call while the map pointer is modified.
1480   void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1481
1482   // Returns the heap object's size in bytes
1483   inline int Size();
1484
1485   // Indicates what type of values this heap object may contain.
1486   inline HeapObjectContents ContentType();
1487
1488   // Given a heap object's map pointer, returns the heap size in bytes
1489   // Useful when the map pointer field is used for other purposes.
1490   // GC internal.
1491   inline int SizeFromMap(Map* map);
1492
1493   // Returns the field at offset in obj, as a read/write Object* reference.
1494   // Does no checking, and is safe to use during GC, while maps are invalid.
1495   // Does not invoke write barrier, so should only be assigned to
1496   // during marking GC.
1497   static inline Object** RawField(HeapObject* obj, int offset);
1498
1499   // Adds the |code| object related to |name| to the code cache of this map. If
1500   // this map is a dictionary map that is shared, the map copied and installed
1501   // onto the object.
1502   static void UpdateMapCodeCache(Handle<HeapObject> object,
1503                                  Handle<Name> name,
1504                                  Handle<Code> code);
1505
1506   DECLARE_CAST(HeapObject)
1507
1508   // Return the write barrier mode for this. Callers of this function
1509   // must be able to present a reference to an DisallowHeapAllocation
1510   // object as a sign that they are not going to use this function
1511   // from code that allocates and thus invalidates the returned write
1512   // barrier mode.
1513   inline WriteBarrierMode GetWriteBarrierMode(
1514       const DisallowHeapAllocation& promise);
1515
1516   // Dispatched behavior.
1517   void HeapObjectShortPrint(std::ostream& os);  // NOLINT
1518 #ifdef OBJECT_PRINT
1519   void PrintHeader(std::ostream& os, const char* id);  // NOLINT
1520 #endif
1521   DECLARE_PRINTER(HeapObject)
1522   DECLARE_VERIFIER(HeapObject)
1523 #ifdef VERIFY_HEAP
1524   inline void VerifyObjectField(int offset);
1525   inline void VerifySmiField(int offset);
1526
1527   // Verify a pointer is a valid HeapObject pointer that points to object
1528   // areas in the heap.
1529   static void VerifyHeapPointer(Object* p);
1530 #endif
1531
1532   inline AllocationAlignment RequiredAlignment();
1533
1534   // Layout description.
1535   // First field in a heap object is map.
1536   static const int kMapOffset = Object::kHeaderSize;
1537   static const int kHeaderSize = kMapOffset + kPointerSize;
1538
1539   STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1540
1541  protected:
1542   // helpers for calling an ObjectVisitor to iterate over pointers in the
1543   // half-open range [start, end) specified as integer offsets
1544   inline void IteratePointers(ObjectVisitor* v, int start, int end);
1545   // as above, for the single element at "offset"
1546   inline void IteratePointer(ObjectVisitor* v, int offset);
1547   // as above, for the next code link of a code object.
1548   inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1549
1550  private:
1551   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1552 };
1553
1554
1555 // This class describes a body of an object of a fixed size
1556 // in which all pointer fields are located in the [start_offset, end_offset)
1557 // interval.
1558 template<int start_offset, int end_offset, int size>
1559 class FixedBodyDescriptor {
1560  public:
1561   static const int kStartOffset = start_offset;
1562   static const int kEndOffset = end_offset;
1563   static const int kSize = size;
1564
1565   static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1566
1567   template<typename StaticVisitor>
1568   static inline void IterateBody(HeapObject* obj) {
1569     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1570                                  HeapObject::RawField(obj, end_offset));
1571   }
1572 };
1573
1574
1575 // This class describes a body of an object of a variable size
1576 // in which all pointer fields are located in the [start_offset, object_size)
1577 // interval.
1578 template<int start_offset>
1579 class FlexibleBodyDescriptor {
1580  public:
1581   static const int kStartOffset = start_offset;
1582
1583   static inline void IterateBody(HeapObject* obj,
1584                                  int object_size,
1585                                  ObjectVisitor* v);
1586
1587   template<typename StaticVisitor>
1588   static inline void IterateBody(HeapObject* obj, int object_size) {
1589     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1590                                  HeapObject::RawField(obj, object_size));
1591   }
1592 };
1593
1594
1595 // The HeapNumber class describes heap allocated numbers that cannot be
1596 // represented in a Smi (small integer)
1597 class HeapNumber: public HeapObject {
1598  public:
1599   // [value]: number value.
1600   inline double value() const;
1601   inline void set_value(double value);
1602
1603   DECLARE_CAST(HeapNumber)
1604
1605   // Dispatched behavior.
1606   bool HeapNumberBooleanValue();
1607
1608   void HeapNumberPrint(std::ostream& os);  // NOLINT
1609   DECLARE_VERIFIER(HeapNumber)
1610
1611   inline int get_exponent();
1612   inline int get_sign();
1613
1614   // Layout description.
1615   static const int kValueOffset = HeapObject::kHeaderSize;
1616   // IEEE doubles are two 32 bit words.  The first is just mantissa, the second
1617   // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1618   // words within double numbers are endian dependent and they are set
1619   // accordingly.
1620 #if defined(V8_TARGET_LITTLE_ENDIAN)
1621   static const int kMantissaOffset = kValueOffset;
1622   static const int kExponentOffset = kValueOffset + 4;
1623 #elif defined(V8_TARGET_BIG_ENDIAN)
1624   static const int kMantissaOffset = kValueOffset + 4;
1625   static const int kExponentOffset = kValueOffset;
1626 #else
1627 #error Unknown byte ordering
1628 #endif
1629
1630   static const int kSize = kValueOffset + kDoubleSize;
1631   static const uint32_t kSignMask = 0x80000000u;
1632   static const uint32_t kExponentMask = 0x7ff00000u;
1633   static const uint32_t kMantissaMask = 0xfffffu;
1634   static const int kMantissaBits = 52;
1635   static const int kExponentBits = 11;
1636   static const int kExponentBias = 1023;
1637   static const int kExponentShift = 20;
1638   static const int kInfinityOrNanExponent =
1639       (kExponentMask >> kExponentShift) - kExponentBias;
1640   static const int kMantissaBitsInTopWord = 20;
1641   static const int kNonMantissaBitsInTopWord = 12;
1642
1643  private:
1644   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1645 };
1646
1647
1648 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1649 class Simd128Value : public HeapObject {
1650  public:
1651   DECLARE_CAST(Simd128Value)
1652
1653   DECLARE_PRINTER(Simd128Value)
1654   DECLARE_VERIFIER(Simd128Value)
1655
1656   static Handle<String> ToString(Handle<Simd128Value> input);
1657
1658   // Equality operations.
1659   inline bool Equals(Simd128Value* that);
1660
1661   // Checks that another instance is bit-wise equal.
1662   bool BitwiseEquals(const Simd128Value* other) const;
1663   // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1664   uint32_t Hash() const;
1665   // Copies the 16 bytes of SIMD data to the destination address.
1666   void CopyBits(void* destination) const;
1667
1668   // Layout description.
1669   static const int kValueOffset = HeapObject::kHeaderSize;
1670   static const int kSize = kValueOffset + kSimd128Size;
1671
1672  private:
1673   DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1674 };
1675
1676
1677 // V has parameters (TYPE, Type, type, lane count, lane type)
1678 #define SIMD128_TYPES(V)                       \
1679   V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1680   V(INT32X4, Int32x4, int32x4, 4, int32_t)     \
1681   V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1682   V(BOOL32X4, Bool32x4, bool32x4, 4, bool)     \
1683   V(INT16X8, Int16x8, int16x8, 8, int16_t)     \
1684   V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1685   V(BOOL16X8, Bool16x8, bool16x8, 8, bool)     \
1686   V(INT8X16, Int8x16, int8x16, 16, int8_t)     \
1687   V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1688   V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1689
1690 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1691   class Type final : public Simd128Value {                           \
1692    public:                                                           \
1693     inline lane_type get_lane(int lane) const;                       \
1694     inline void set_lane(int lane, lane_type value);                 \
1695                                                                      \
1696     DECLARE_CAST(Type)                                               \
1697                                                                      \
1698     DECLARE_PRINTER(Type)                                            \
1699                                                                      \
1700     static Handle<String> ToString(Handle<Type> input);              \
1701                                                                      \
1702     inline bool Equals(Type* that);                                  \
1703                                                                      \
1704    private:                                                          \
1705     DISALLOW_IMPLICIT_CONSTRUCTORS(Type);                            \
1706   };
1707 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1708 #undef SIMD128_VALUE_CLASS
1709
1710
1711 enum EnsureElementsMode {
1712   DONT_ALLOW_DOUBLE_ELEMENTS,
1713   ALLOW_COPIED_DOUBLE_ELEMENTS,
1714   ALLOW_CONVERTED_DOUBLE_ELEMENTS
1715 };
1716
1717
1718 // Indicator for one component of an AccessorPair.
1719 enum AccessorComponent {
1720   ACCESSOR_GETTER,
1721   ACCESSOR_SETTER
1722 };
1723
1724
1725 // JSReceiver includes types on which properties can be defined, i.e.,
1726 // JSObject and JSProxy.
1727 class JSReceiver: public HeapObject {
1728  public:
1729   DECLARE_CAST(JSReceiver)
1730
1731   // ES6 section 7.1.1 ToPrimitive
1732   MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1733       Handle<JSReceiver> receiver,
1734       ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1735   MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1736       Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1737
1738   // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1739   MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1740       Handle<JSReceiver> object, Handle<Name> name);
1741   MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1742                                                            Handle<Name> name);
1743   MUST_USE_RESULT static inline Maybe<bool> HasElement(
1744       Handle<JSReceiver> object, uint32_t index);
1745   MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1746       Handle<JSReceiver> object, uint32_t index);
1747
1748   // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1749   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1750       Handle<JSReceiver> object, Handle<Name> name,
1751       LanguageMode language_mode = SLOPPY);
1752   MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1753       Handle<JSReceiver> object, Handle<Name> name,
1754       LanguageMode language_mode = SLOPPY);
1755   MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1756       LookupIterator* it, LanguageMode language_mode);
1757   MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1758       Handle<JSReceiver> object, uint32_t index,
1759       LanguageMode language_mode = SLOPPY);
1760
1761   // Tests for the fast common case for property enumeration.
1762   bool IsSimpleEnum();
1763
1764   // Returns the class name ([[Class]] property in the specification).
1765   String* class_name();
1766
1767   // Returns the constructor name (the name (possibly, inferred name) of the
1768   // function that was used to instantiate the object).
1769   String* constructor_name();
1770
1771   MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1772       Handle<JSReceiver> object, Handle<Name> name);
1773   MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1774   GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1775
1776   MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1777       Handle<JSReceiver> object, uint32_t index);
1778   MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1779   GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1780
1781   MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1782       LookupIterator* it);
1783
1784
1785   static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1786                                         Handle<Name> name);
1787   static Handle<Object> GetDataProperty(LookupIterator* it);
1788
1789
1790   // Retrieves a permanent object identity hash code. The undefined value might
1791   // be returned in case no hash was created yet.
1792   inline Object* GetIdentityHash();
1793
1794   // Retrieves a permanent object identity hash code. May create and store a
1795   // hash code if needed and none exists.
1796   inline static Handle<Smi> GetOrCreateIdentityHash(
1797       Handle<JSReceiver> object);
1798
1799   enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1800
1801   // Computes the enumerable keys for a JSObject. Used for implementing
1802   // "for (n in object) { }".
1803   MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1804       Handle<JSReceiver> object,
1805       KeyCollectionType type);
1806
1807  private:
1808   DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1809 };
1810
1811
1812 // The JSObject describes real heap allocated JavaScript objects with
1813 // properties.
1814 // Note that the map of JSObject changes during execution to enable inline
1815 // caching.
1816 class JSObject: public JSReceiver {
1817  public:
1818   // [properties]: Backing storage for properties.
1819   // properties is a FixedArray in the fast case and a Dictionary in the
1820   // slow case.
1821   DECL_ACCESSORS(properties, FixedArray)  // Get and set fast properties.
1822   inline void initialize_properties();
1823   inline bool HasFastProperties();
1824   // Gets slow properties for non-global objects.
1825   inline NameDictionary* property_dictionary();
1826   // Gets global object properties.
1827   inline GlobalDictionary* global_dictionary();
1828
1829   // [elements]: The elements (properties with names that are integers).
1830   //
1831   // Elements can be in two general modes: fast and slow. Each mode
1832   // corrensponds to a set of object representations of elements that
1833   // have something in common.
1834   //
1835   // In the fast mode elements is a FixedArray and so each element can
1836   // be quickly accessed. This fact is used in the generated code. The
1837   // elements array can have one of three maps in this mode:
1838   // fixed_array_map, sloppy_arguments_elements_map or
1839   // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1840   // the elements array may be shared by a few objects and so before
1841   // writing to any element the array must be copied. Use
1842   // EnsureWritableFastElements in this case.
1843   //
1844   // In the slow mode the elements is either a NumberDictionary, a
1845   // FixedArray parameter map for a (sloppy) arguments object.
1846   DECL_ACCESSORS(elements, FixedArrayBase)
1847   inline void initialize_elements();
1848   static void ResetElements(Handle<JSObject> object);
1849   static inline void SetMapAndElements(Handle<JSObject> object,
1850                                        Handle<Map> map,
1851                                        Handle<FixedArrayBase> elements);
1852   inline ElementsKind GetElementsKind();
1853   ElementsAccessor* GetElementsAccessor();
1854   // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1855   inline bool HasFastSmiElements();
1856   // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1857   inline bool HasFastObjectElements();
1858   // Returns true if an object has elements of FAST_ELEMENTS or
1859   // FAST_SMI_ONLY_ELEMENTS.
1860   inline bool HasFastSmiOrObjectElements();
1861   // Returns true if an object has any of the fast elements kinds.
1862   inline bool HasFastElements();
1863   // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1864   // ElementsKind.
1865   inline bool HasFastDoubleElements();
1866   // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1867   // ElementsKind.
1868   inline bool HasFastHoleyElements();
1869   inline bool HasSloppyArgumentsElements();
1870   inline bool HasDictionaryElements();
1871
1872   inline bool HasFixedTypedArrayElements();
1873
1874   inline bool HasFixedUint8ClampedElements();
1875   inline bool HasFixedArrayElements();
1876   inline bool HasFixedInt8Elements();
1877   inline bool HasFixedUint8Elements();
1878   inline bool HasFixedInt16Elements();
1879   inline bool HasFixedUint16Elements();
1880   inline bool HasFixedInt32Elements();
1881   inline bool HasFixedUint32Elements();
1882   inline bool HasFixedFloat32Elements();
1883   inline bool HasFixedFloat64Elements();
1884
1885   inline bool HasFastArgumentsElements();
1886   inline bool HasSlowArgumentsElements();
1887   inline SeededNumberDictionary* element_dictionary();  // Gets slow elements.
1888
1889   // Requires: HasFastElements().
1890   static Handle<FixedArray> EnsureWritableFastElements(
1891       Handle<JSObject> object);
1892
1893   // Collects elements starting at index 0.
1894   // Undefined values are placed after non-undefined values.
1895   // Returns the number of non-undefined values.
1896   static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1897                                                uint32_t limit);
1898   // As PrepareElementsForSort, but only on objects where elements is
1899   // a dictionary, and it will stay a dictionary.  Collates undefined and
1900   // unexisting elements below limit from position zero of the elements.
1901   static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1902                                                    uint32_t limit);
1903
1904   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1905       LookupIterator* it, Handle<Object> value);
1906
1907   // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1908   // grant an exemption to ExecutableAccessor callbacks in some cases.
1909   enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1910
1911   MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1912       LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1913       ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1914
1915   MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1916       Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1917       PropertyAttributes attributes,
1918       ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1919
1920   MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1921       Handle<JSObject> object, uint32_t index, Handle<Object> value,
1922       PropertyAttributes attributes,
1923       ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1924
1925   // Equivalent to one of the above depending on whether |name| can be converted
1926   // to an array index.
1927   MUST_USE_RESULT static MaybeHandle<Object>
1928   DefinePropertyOrElementIgnoreAttributes(
1929       Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1930       PropertyAttributes attributes = NONE,
1931       ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1932
1933   // Adds or reconfigures a property to attributes NONE. It will fail when it
1934   // cannot.
1935   MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1936                                                         Handle<Object> value);
1937
1938   static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1939                           Handle<Object> value, PropertyAttributes attributes);
1940
1941   MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1942       Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1943       PropertyAttributes attributes);
1944
1945   // Extend the receiver with a single fast property appeared first in the
1946   // passed map. This also extends the property backing store if necessary.
1947   static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1948
1949   // Migrates the given object to a map whose field representations are the
1950   // lowest upper bound of all known representations for that field.
1951   static void MigrateInstance(Handle<JSObject> instance);
1952
1953   // Migrates the given object only if the target map is already available,
1954   // or returns false if such a map is not yet available.
1955   static bool TryMigrateInstance(Handle<JSObject> instance);
1956
1957   // Sets the property value in a normalized object given (key, value, details).
1958   // Handles the special representation of JS global objects.
1959   static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1960                                     Handle<Object> value,
1961                                     PropertyDetails details);
1962   static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1963                                    Handle<Object> value,
1964                                    PropertyAttributes attributes);
1965   static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1966                                             uint32_t index,
1967                                             Handle<Object> value,
1968                                             PropertyAttributes attributes);
1969
1970   static void OptimizeAsPrototype(Handle<JSObject> object,
1971                                   PrototypeOptimizationMode mode);
1972   static void ReoptimizeIfPrototype(Handle<JSObject> object);
1973   static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1974   static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1975   static void InvalidatePrototypeChains(Map* map);
1976
1977   // Alternative implementation of WeakFixedArray::NullCallback.
1978   class PrototypeRegistryCompactionCallback {
1979    public:
1980     static void Callback(Object* value, int old_index, int new_index);
1981   };
1982
1983   // Retrieve interceptors.
1984   InterceptorInfo* GetNamedInterceptor();
1985   InterceptorInfo* GetIndexedInterceptor();
1986
1987   // Used from JSReceiver.
1988   MUST_USE_RESULT static Maybe<PropertyAttributes>
1989   GetPropertyAttributesWithInterceptor(LookupIterator* it);
1990   MUST_USE_RESULT static Maybe<PropertyAttributes>
1991       GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1992
1993   // Retrieves an AccessorPair property from the given object. Might return
1994   // undefined if the property doesn't exist or is of a different kind.
1995   MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1996       Handle<JSObject> object,
1997       Handle<Name> name,
1998       AccessorComponent component);
1999
2000   // Defines an AccessorPair property on the given object.
2001   // TODO(mstarzinger): Rename to SetAccessor().
2002   static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2003                                             Handle<Name> name,
2004                                             Handle<Object> getter,
2005                                             Handle<Object> setter,
2006                                             PropertyAttributes attributes);
2007
2008   // Defines an AccessorInfo property on the given object.
2009   MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2010       Handle<JSObject> object,
2011       Handle<AccessorInfo> info);
2012
2013   // The result must be checked first for exceptions. If there's no exception,
2014   // the output parameter |done| indicates whether the interceptor has a result
2015   // or not.
2016   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2017       LookupIterator* it, bool* done);
2018
2019   // Accessors for hidden properties object.
2020   //
2021   // Hidden properties are not own properties of the object itself.
2022   // Instead they are stored in an auxiliary structure kept as an own
2023   // property with a special name Heap::hidden_string(). But if the
2024   // receiver is a JSGlobalProxy then the auxiliary object is a property
2025   // of its prototype, and if it's a detached proxy, then you can't have
2026   // hidden properties.
2027
2028   // Sets a hidden property on this object. Returns this object if successful,
2029   // undefined if called on a detached proxy.
2030   static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2031                                           Handle<Name> key,
2032                                           Handle<Object> value);
2033   // Gets the value of a hidden property with the given key. Returns the hole
2034   // if the property doesn't exist (or if called on a detached proxy),
2035   // otherwise returns the value set for the key.
2036   Object* GetHiddenProperty(Handle<Name> key);
2037   // Deletes a hidden property. Deleting a non-existing property is
2038   // considered successful.
2039   static void DeleteHiddenProperty(Handle<JSObject> object,
2040                                    Handle<Name> key);
2041   // Returns true if the object has a property with the hidden string as name.
2042   static bool HasHiddenProperties(Handle<JSObject> object);
2043
2044   static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2045
2046   static void ValidateElements(Handle<JSObject> object);
2047
2048   // Makes sure that this object can contain HeapObject as elements.
2049   static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2050
2051   // Makes sure that this object can contain the specified elements.
2052   static inline void EnsureCanContainElements(
2053       Handle<JSObject> object,
2054       Object** elements,
2055       uint32_t count,
2056       EnsureElementsMode mode);
2057   static inline void EnsureCanContainElements(
2058       Handle<JSObject> object,
2059       Handle<FixedArrayBase> elements,
2060       uint32_t length,
2061       EnsureElementsMode mode);
2062   static void EnsureCanContainElements(
2063       Handle<JSObject> object,
2064       Arguments* arguments,
2065       uint32_t first_arg,
2066       uint32_t arg_count,
2067       EnsureElementsMode mode);
2068
2069   // Would we convert a fast elements array to dictionary mode given
2070   // an access at key?
2071   bool WouldConvertToSlowElements(uint32_t index);
2072
2073   // Computes the new capacity when expanding the elements of a JSObject.
2074   static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2075     // (old_capacity + 50%) + 16
2076     return old_capacity + (old_capacity >> 1) + 16;
2077   }
2078
2079   // These methods do not perform access checks!
2080   static void UpdateAllocationSite(Handle<JSObject> object,
2081                                    ElementsKind to_kind);
2082
2083   // Lookup interceptors are used for handling properties controlled by host
2084   // objects.
2085   inline bool HasNamedInterceptor();
2086   inline bool HasIndexedInterceptor();
2087
2088   // Computes the enumerable keys from interceptors. Used for debug mirrors and
2089   // by JSReceiver::GetKeys.
2090   MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2091       Handle<JSObject> object,
2092       Handle<JSReceiver> receiver);
2093   MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2094       Handle<JSObject> object,
2095       Handle<JSReceiver> receiver);
2096
2097   // Support functions for v8 api (needed for correct interceptor behavior).
2098   MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2099       Handle<JSObject> object, Handle<Name> name);
2100   MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2101       Handle<JSObject> object, uint32_t index);
2102   MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2103       Handle<JSObject> object, Handle<Name> name);
2104
2105   // Get the header size for a JSObject.  Used to compute the index of
2106   // internal fields as well as the number of internal fields.
2107   inline int GetHeaderSize();
2108
2109   inline int GetInternalFieldCount();
2110   inline int GetInternalFieldOffset(int index);
2111   inline Object* GetInternalField(int index);
2112   inline void SetInternalField(int index, Object* value);
2113   inline void SetInternalField(int index, Smi* value);
2114
2115   // Returns the number of properties on this object filtering out properties
2116   // with the specified attributes (ignoring interceptors).
2117   int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2118   // Fill in details for properties into storage starting at the specified
2119   // index. Returns the number of properties added.
2120   int GetOwnPropertyNames(FixedArray* storage, int index,
2121                           PropertyAttributes filter = NONE);
2122
2123   // Returns the number of properties on this object filtering out properties
2124   // with the specified attributes (ignoring interceptors).
2125   int NumberOfOwnElements(PropertyAttributes filter);
2126   // Returns the number of enumerable elements (ignoring interceptors).
2127   int NumberOfEnumElements();
2128   // Returns the number of elements on this object filtering out elements
2129   // with the specified attributes (ignoring interceptors).
2130   int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2131   // Count and fill in the enumerable elements into storage.
2132   // (storage->length() == NumberOfEnumElements()).
2133   // If storage is NULL, will count the elements without adding
2134   // them to any storage.
2135   // Returns the number of enumerable elements.
2136   int GetEnumElementKeys(FixedArray* storage);
2137
2138   static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2139                                                 bool cache_result);
2140
2141   // Returns a new map with all transitions dropped from the object's current
2142   // map and the ElementsKind set.
2143   static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2144                                               ElementsKind to_kind);
2145   static void TransitionElementsKind(Handle<JSObject> object,
2146                                      ElementsKind to_kind);
2147
2148   // Always use this to migrate an object to a new map.
2149   // |expected_additional_properties| is only used for fast-to-slow transitions
2150   // and ignored otherwise.
2151   static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2152                            int expected_additional_properties = 0);
2153
2154   // Convert the object to use the canonical dictionary
2155   // representation. If the object is expected to have additional properties
2156   // added this number can be indicated to have the backing store allocated to
2157   // an initial capacity for holding these properties.
2158   static void NormalizeProperties(Handle<JSObject> object,
2159                                   PropertyNormalizationMode mode,
2160                                   int expected_additional_properties,
2161                                   const char* reason);
2162
2163   // Convert and update the elements backing store to be a
2164   // SeededNumberDictionary dictionary.  Returns the backing after conversion.
2165   static Handle<SeededNumberDictionary> NormalizeElements(
2166       Handle<JSObject> object);
2167
2168   void RequireSlowElements(SeededNumberDictionary* dictionary);
2169
2170   // Transform slow named properties to fast variants.
2171   static void MigrateSlowToFast(Handle<JSObject> object,
2172                                 int unused_property_fields, const char* reason);
2173
2174   inline bool IsUnboxedDoubleField(FieldIndex index);
2175
2176   // Access fast-case object properties at index.
2177   static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2178                                        Representation representation,
2179                                        FieldIndex index);
2180   inline Object* RawFastPropertyAt(FieldIndex index);
2181   inline double RawFastDoublePropertyAt(FieldIndex index);
2182
2183   inline void FastPropertyAtPut(FieldIndex index, Object* value);
2184   inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2185   inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2186   inline void WriteToField(int descriptor, Object* value);
2187
2188   // Access to in object properties.
2189   inline int GetInObjectPropertyOffset(int index);
2190   inline Object* InObjectPropertyAt(int index);
2191   inline Object* InObjectPropertyAtPut(int index,
2192                                        Object* value,
2193                                        WriteBarrierMode mode
2194                                        = UPDATE_WRITE_BARRIER);
2195
2196   // Set the object's prototype (only JSReceiver and null are allowed values).
2197   MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2198       Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2199
2200   // Initializes the body after properties slot, properties slot is
2201   // initialized by set_properties.  Fill the pre-allocated fields with
2202   // pre_allocated_value and the rest with filler_value.
2203   // Note: this call does not update write barrier, the caller is responsible
2204   // to ensure that |filler_value| can be collected without WB here.
2205   inline void InitializeBody(Map* map,
2206                              Object* pre_allocated_value,
2207                              Object* filler_value);
2208
2209   // Check whether this object references another object
2210   bool ReferencesObject(Object* obj);
2211
2212   // Disalow further properties to be added to the oject.
2213   MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2214       Handle<JSObject> object);
2215
2216   bool IsExtensible();
2217
2218   // ES5 Object.seal
2219   MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2220
2221   // ES5 Object.freeze
2222   MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2223
2224   // Called the first time an object is observed with ES7 Object.observe.
2225   static void SetObserved(Handle<JSObject> object);
2226
2227   // Copy object.
2228   enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2229
2230   MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2231       Handle<JSObject> object,
2232       AllocationSiteUsageContext* site_context,
2233       DeepCopyHints hints = kNoHints);
2234   MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2235       Handle<JSObject> object,
2236       AllocationSiteCreationContext* site_context);
2237
2238   DECLARE_CAST(JSObject)
2239
2240   // Dispatched behavior.
2241   void JSObjectShortPrint(StringStream* accumulator);
2242   DECLARE_PRINTER(JSObject)
2243   DECLARE_VERIFIER(JSObject)
2244 #ifdef OBJECT_PRINT
2245   void PrintProperties(std::ostream& os);   // NOLINT
2246   void PrintElements(std::ostream& os);     // NOLINT
2247 #endif
2248 #if defined(DEBUG) || defined(OBJECT_PRINT)
2249   void PrintTransitions(std::ostream& os);  // NOLINT
2250 #endif
2251
2252   static void PrintElementsTransition(
2253       FILE* file, Handle<JSObject> object,
2254       ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2255       ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2256
2257   void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2258
2259 #ifdef DEBUG
2260   // Structure for collecting spill information about JSObjects.
2261   class SpillInformation {
2262    public:
2263     void Clear();
2264     void Print();
2265     int number_of_objects_;
2266     int number_of_objects_with_fast_properties_;
2267     int number_of_objects_with_fast_elements_;
2268     int number_of_fast_used_fields_;
2269     int number_of_fast_unused_fields_;
2270     int number_of_slow_used_properties_;
2271     int number_of_slow_unused_properties_;
2272     int number_of_fast_used_elements_;
2273     int number_of_fast_unused_elements_;
2274     int number_of_slow_used_elements_;
2275     int number_of_slow_unused_elements_;
2276   };
2277
2278   void IncrementSpillStatistics(SpillInformation* info);
2279 #endif
2280
2281 #ifdef VERIFY_HEAP
2282   // If a GC was caused while constructing this object, the elements pointer
2283   // may point to a one pointer filler map. The object won't be rooted, but
2284   // our heap verification code could stumble across it.
2285   bool ElementsAreSafeToExamine();
2286 #endif
2287
2288   Object* SlowReverseLookup(Object* value);
2289
2290   // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2291   // Also maximal value of JSArray's length property.
2292   static const uint32_t kMaxElementCount = 0xffffffffu;
2293
2294   // Constants for heuristics controlling conversion of fast elements
2295   // to slow elements.
2296
2297   // Maximal gap that can be introduced by adding an element beyond
2298   // the current elements length.
2299   static const uint32_t kMaxGap = 1024;
2300
2301   // Maximal length of fast elements array that won't be checked for
2302   // being dense enough on expansion.
2303   static const int kMaxUncheckedFastElementsLength = 5000;
2304
2305   // Same as above but for old arrays. This limit is more strict. We
2306   // don't want to be wasteful with long lived objects.
2307   static const int kMaxUncheckedOldFastElementsLength = 500;
2308
2309   // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2310   // permissible values (see the DCHECK in heap.cc).
2311   static const int kInitialMaxFastElementArray = 100000;
2312
2313   // This constant applies only to the initial map of "global.Object" and
2314   // not to arbitrary other JSObject maps.
2315   static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2316
2317   static const int kMaxInstanceSize = 255 * kPointerSize;
2318   // When extending the backing storage for property values, we increase
2319   // its size by more than the 1 entry necessary, so sequentially adding fields
2320   // to the same object requires fewer allocations and copies.
2321   static const int kFieldsAdded = 3;
2322
2323   // Layout description.
2324   static const int kPropertiesOffset = HeapObject::kHeaderSize;
2325   static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2326   static const int kHeaderSize = kElementsOffset + kPointerSize;
2327
2328   STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2329
2330   class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2331    public:
2332     static inline int SizeOf(Map* map, HeapObject* object);
2333   };
2334
2335   Context* GetCreationContext();
2336
2337   // Enqueue change record for Object.observe. May cause GC.
2338   MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2339       Handle<JSObject> object, const char* type, Handle<Name> name,
2340       Handle<Object> old_value);
2341
2342   // Gets the number of currently used elements.
2343   int GetFastElementsUsage();
2344
2345   // Deletes an existing named property in a normalized object.
2346   static void DeleteNormalizedProperty(Handle<JSObject> object,
2347                                        Handle<Name> name, int entry);
2348
2349   static bool AllCanRead(LookupIterator* it);
2350   static bool AllCanWrite(LookupIterator* it);
2351
2352  private:
2353   friend class JSReceiver;
2354   friend class Object;
2355
2356   static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2357   static void MigrateFastToSlow(Handle<JSObject> object,
2358                                 Handle<Map> new_map,
2359                                 int expected_additional_properties);
2360
2361   // Used from Object::GetProperty().
2362   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2363       LookupIterator* it);
2364
2365   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2366       LookupIterator* it, Handle<Object> value);
2367
2368   // Add a property to a slow-case object.
2369   static void AddSlowProperty(Handle<JSObject> object,
2370                               Handle<Name> name,
2371                               Handle<Object> value,
2372                               PropertyAttributes attributes);
2373
2374   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2375       LookupIterator* it);
2376
2377   bool ReferencesObjectFromElements(FixedArray* elements,
2378                                     ElementsKind kind,
2379                                     Object* object);
2380
2381   // Return the hash table backing store or the inline stored identity hash,
2382   // whatever is found.
2383   MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2384
2385   // Return the hash table backing store for hidden properties.  If there is no
2386   // backing store, allocate one.
2387   static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2388       Handle<JSObject> object);
2389
2390   // Set the hidden property backing store to either a hash table or
2391   // the inline-stored identity hash.
2392   static Handle<Object> SetHiddenPropertiesHashTable(
2393       Handle<JSObject> object,
2394       Handle<Object> value);
2395
2396   MUST_USE_RESULT Object* GetIdentityHash();
2397
2398   static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2399
2400   static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2401       Handle<JSObject> object, Handle<FixedArrayBase> elements);
2402
2403   // Helper for fast versions of preventExtensions, seal, and freeze.
2404   // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2405   template <PropertyAttributes attrs>
2406   MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2407       Handle<JSObject> object);
2408
2409   DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2410 };
2411
2412
2413 // Common superclass for FixedArrays that allow implementations to share
2414 // common accessors and some code paths.
2415 class FixedArrayBase: public HeapObject {
2416  public:
2417   // [length]: length of the array.
2418   inline int length() const;
2419   inline void set_length(int value);
2420
2421   // Get and set the length using acquire loads and release stores.
2422   inline int synchronized_length() const;
2423   inline void synchronized_set_length(int value);
2424
2425   DECLARE_CAST(FixedArrayBase)
2426
2427   // Layout description.
2428   // Length is smi tagged when it is stored.
2429   static const int kLengthOffset = HeapObject::kHeaderSize;
2430   static const int kHeaderSize = kLengthOffset + kPointerSize;
2431 };
2432
2433
2434 class FixedDoubleArray;
2435 class IncrementalMarking;
2436
2437
2438 // FixedArray describes fixed-sized arrays with element type Object*.
2439 class FixedArray: public FixedArrayBase {
2440  public:
2441   // Setter and getter for elements.
2442   inline Object* get(int index) const;
2443   static inline Handle<Object> get(Handle<FixedArray> array, int index);
2444   // Setter that uses write barrier.
2445   inline void set(int index, Object* value);
2446   inline bool is_the_hole(int index);
2447
2448   // Setter that doesn't need write barrier.
2449   inline void set(int index, Smi* value);
2450   // Setter with explicit barrier mode.
2451   inline void set(int index, Object* value, WriteBarrierMode mode);
2452
2453   // Setters for frequently used oddballs located in old space.
2454   inline void set_undefined(int index);
2455   inline void set_null(int index);
2456   inline void set_the_hole(int index);
2457
2458   inline Object** GetFirstElementAddress();
2459   inline bool ContainsOnlySmisOrHoles();
2460
2461   // Gives access to raw memory which stores the array's data.
2462   inline Object** data_start();
2463
2464   inline void FillWithHoles(int from, int to);
2465
2466   // Shrink length and insert filler objects.
2467   void Shrink(int length);
2468
2469   enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2470
2471   // Add the elements of a JSArray to this FixedArray.
2472   MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2473       Handle<FixedArray> content, Handle<JSObject> array,
2474       KeyFilter filter = ALL_KEYS);
2475
2476   // Computes the union of keys and return the result.
2477   // Used for implementing "for (n in object) { }"
2478   MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2479       Handle<FixedArray> first,
2480       Handle<FixedArray> second);
2481
2482   // Copy a sub array from the receiver to dest.
2483   void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2484
2485   // Garbage collection support.
2486   static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2487
2488   // Code Generation support.
2489   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2490
2491   // Garbage collection support.
2492   inline Object** RawFieldOfElementAt(int index);
2493
2494   DECLARE_CAST(FixedArray)
2495
2496   // Maximal allowed size, in bytes, of a single FixedArray.
2497   // Prevents overflowing size computations, as well as extreme memory
2498   // consumption.
2499   static const int kMaxSize = 128 * MB * kPointerSize;
2500   // Maximally allowed length of a FixedArray.
2501   static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2502
2503   // Dispatched behavior.
2504   DECLARE_PRINTER(FixedArray)
2505   DECLARE_VERIFIER(FixedArray)
2506 #ifdef DEBUG
2507   // Checks if two FixedArrays have identical contents.
2508   bool IsEqualTo(FixedArray* other);
2509 #endif
2510
2511   // Swap two elements in a pair of arrays.  If this array and the
2512   // numbers array are the same object, the elements are only swapped
2513   // once.
2514   void SwapPairs(FixedArray* numbers, int i, int j);
2515
2516   // Sort prefix of this array and the numbers array as pairs wrt. the
2517   // numbers.  If the numbers array and the this array are the same
2518   // object, the prefix of this array is sorted.
2519   void SortPairs(FixedArray* numbers, uint32_t len);
2520
2521   class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2522    public:
2523     static inline int SizeOf(Map* map, HeapObject* object);
2524   };
2525
2526  protected:
2527   // Set operation on FixedArray without using write barriers. Can
2528   // only be used for storing old space objects or smis.
2529   static inline void NoWriteBarrierSet(FixedArray* array,
2530                                        int index,
2531                                        Object* value);
2532
2533   // Set operation on FixedArray without incremental write barrier. Can
2534   // only be used if the object is guaranteed to be white (whiteness witness
2535   // is present).
2536   static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2537                                                   int index,
2538                                                   Object* value);
2539
2540  private:
2541   STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2542
2543   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2544 };
2545
2546
2547 // FixedDoubleArray describes fixed-sized arrays with element type double.
2548 class FixedDoubleArray: public FixedArrayBase {
2549  public:
2550   // Setter and getter for elements.
2551   inline double get_scalar(int index);
2552   inline uint64_t get_representation(int index);
2553   static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2554   inline void set(int index, double value);
2555   inline void set_the_hole(int index);
2556
2557   // Checking for the hole.
2558   inline bool is_the_hole(int index);
2559
2560   // Garbage collection support.
2561   inline static int SizeFor(int length) {
2562     return kHeaderSize + length * kDoubleSize;
2563   }
2564
2565   // Gives access to raw memory which stores the array's data.
2566   inline double* data_start();
2567
2568   inline void FillWithHoles(int from, int to);
2569
2570   // Code Generation support.
2571   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2572
2573   DECLARE_CAST(FixedDoubleArray)
2574
2575   // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2576   // Prevents overflowing size computations, as well as extreme memory
2577   // consumption.
2578   static const int kMaxSize = 512 * MB;
2579   // Maximally allowed length of a FixedArray.
2580   static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2581
2582   // Dispatched behavior.
2583   DECLARE_PRINTER(FixedDoubleArray)
2584   DECLARE_VERIFIER(FixedDoubleArray)
2585
2586  private:
2587   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2588 };
2589
2590
2591 class WeakFixedArray : public FixedArray {
2592  public:
2593   // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2594   // This function does not check if the value exists already, callers must
2595   // ensure this themselves if necessary.
2596   static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2597                                     Handle<HeapObject> value,
2598                                     int* assigned_index = NULL);
2599
2600   // Returns true if an entry was found and removed.
2601   bool Remove(Handle<HeapObject> value);
2602
2603   class NullCallback {
2604    public:
2605     static void Callback(Object* value, int old_index, int new_index) {}
2606   };
2607
2608   template <class CompactionCallback>
2609   void Compact();
2610
2611   inline Object* Get(int index) const;
2612   inline void Clear(int index);
2613   inline int Length() const;
2614
2615   inline bool IsEmptySlot(int index) const;
2616   static Object* Empty() { return Smi::FromInt(0); }
2617
2618   class Iterator {
2619    public:
2620     explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2621     void Reset(Object* maybe_array);
2622
2623     template <class T>
2624     inline T* Next();
2625
2626    private:
2627     int index_;
2628     WeakFixedArray* list_;
2629 #ifdef DEBUG
2630     int last_used_index_;
2631     DisallowHeapAllocation no_gc_;
2632 #endif  // DEBUG
2633     DISALLOW_COPY_AND_ASSIGN(Iterator);
2634   };
2635
2636   DECLARE_CAST(WeakFixedArray)
2637
2638  private:
2639   static const int kLastUsedIndexIndex = 0;
2640   static const int kFirstIndex = 1;
2641
2642   static Handle<WeakFixedArray> Allocate(
2643       Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2644
2645   static void Set(Handle<WeakFixedArray> array, int index,
2646                   Handle<HeapObject> value);
2647   inline void clear(int index);
2648
2649   inline int last_used_index() const;
2650   inline void set_last_used_index(int index);
2651
2652   // Disallow inherited setters.
2653   void set(int index, Smi* value);
2654   void set(int index, Object* value);
2655   void set(int index, Object* value, WriteBarrierMode mode);
2656   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2657 };
2658
2659
2660 // Generic array grows dynamically with O(1) amortized insertion.
2661 class ArrayList : public FixedArray {
2662  public:
2663   enum AddMode {
2664     kNone,
2665     // Use this if GC can delete elements from the array.
2666     kReloadLengthAfterAllocation,
2667   };
2668   static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2669                                AddMode mode = kNone);
2670   static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2671                                Handle<Object> obj2, AddMode = kNone);
2672   inline int Length();
2673   inline void SetLength(int length);
2674   inline Object* Get(int index);
2675   inline Object** Slot(int index);
2676   inline void Set(int index, Object* obj);
2677   inline void Clear(int index, Object* undefined);
2678   DECLARE_CAST(ArrayList)
2679
2680  private:
2681   static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2682   static const int kLengthIndex = 0;
2683   static const int kFirstIndex = 1;
2684   DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2685 };
2686
2687
2688 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2689 // The format of the these objects is:
2690 //   [0]: Number of descriptors
2691 //   [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2692 //          [0]: pointer to fixed array with enum cache
2693 //          [1]: either Smi(0) or pointer to fixed array with indices
2694 //   [2]: first key
2695 //   [2 + number of descriptors * kDescriptorSize]: start of slack
2696 class DescriptorArray: public FixedArray {
2697  public:
2698   // Returns true for both shared empty_descriptor_array and for smis, which the
2699   // map uses to encode additional bit fields when the descriptor array is not
2700   // yet used.
2701   inline bool IsEmpty();
2702
2703   // Returns the number of descriptors in the array.
2704   inline int number_of_descriptors();
2705
2706   inline int number_of_descriptors_storage();
2707
2708   inline int NumberOfSlackDescriptors();
2709
2710   inline void SetNumberOfDescriptors(int number_of_descriptors);
2711   inline int number_of_entries();
2712
2713   inline bool HasEnumCache();
2714
2715   inline void CopyEnumCacheFrom(DescriptorArray* array);
2716
2717   inline FixedArray* GetEnumCache();
2718
2719   inline bool HasEnumIndicesCache();
2720
2721   inline FixedArray* GetEnumIndicesCache();
2722
2723   inline Object** GetEnumCacheSlot();
2724
2725   void ClearEnumCache();
2726
2727   // Initialize or change the enum cache,
2728   // using the supplied storage for the small "bridge".
2729   void SetEnumCache(FixedArray* bridge_storage,
2730                     FixedArray* new_cache,
2731                     Object* new_index_cache);
2732
2733   bool CanHoldValue(int descriptor, Object* value);
2734
2735   // Accessors for fetching instance descriptor at descriptor number.
2736   inline Name* GetKey(int descriptor_number);
2737   inline Object** GetKeySlot(int descriptor_number);
2738   inline Object* GetValue(int descriptor_number);
2739   inline void SetValue(int descriptor_number, Object* value);
2740   inline Object** GetValueSlot(int descriptor_number);
2741   static inline int GetValueOffset(int descriptor_number);
2742   inline Object** GetDescriptorStartSlot(int descriptor_number);
2743   inline Object** GetDescriptorEndSlot(int descriptor_number);
2744   inline PropertyDetails GetDetails(int descriptor_number);
2745   inline PropertyType GetType(int descriptor_number);
2746   inline int GetFieldIndex(int descriptor_number);
2747   inline HeapType* GetFieldType(int descriptor_number);
2748   inline Object* GetConstant(int descriptor_number);
2749   inline Object* GetCallbacksObject(int descriptor_number);
2750   inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2751
2752   inline Name* GetSortedKey(int descriptor_number);
2753   inline int GetSortedKeyIndex(int descriptor_number);
2754   inline void SetSortedKey(int pointer, int descriptor_number);
2755   inline void SetRepresentation(int descriptor_number,
2756                                 Representation representation);
2757
2758   // Accessor for complete descriptor.
2759   inline void Get(int descriptor_number, Descriptor* desc);
2760   inline void Set(int descriptor_number, Descriptor* desc);
2761   void Replace(int descriptor_number, Descriptor* descriptor);
2762
2763   // Append automatically sets the enumeration index. This should only be used
2764   // to add descriptors in bulk at the end, followed by sorting the descriptor
2765   // array.
2766   inline void Append(Descriptor* desc);
2767
2768   static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2769                                           int enumeration_index,
2770                                           int slack = 0);
2771
2772   static Handle<DescriptorArray> CopyUpToAddAttributes(
2773       Handle<DescriptorArray> desc,
2774       int enumeration_index,
2775       PropertyAttributes attributes,
2776       int slack = 0);
2777
2778   // Sort the instance descriptors by the hash codes of their keys.
2779   void Sort();
2780
2781   // Search the instance descriptors for given name.
2782   INLINE(int Search(Name* name, int number_of_own_descriptors));
2783
2784   // As the above, but uses DescriptorLookupCache and updates it when
2785   // necessary.
2786   INLINE(int SearchWithCache(Name* name, Map* map));
2787
2788   // Allocates a DescriptorArray, but returns the singleton
2789   // empty descriptor array object if number_of_descriptors is 0.
2790   static Handle<DescriptorArray> Allocate(Isolate* isolate,
2791                                           int number_of_descriptors,
2792                                           int slack = 0);
2793
2794   DECLARE_CAST(DescriptorArray)
2795
2796   // Constant for denoting key was not found.
2797   static const int kNotFound = -1;
2798
2799   static const int kDescriptorLengthIndex = 0;
2800   static const int kEnumCacheIndex = 1;
2801   static const int kFirstIndex = 2;
2802
2803   // The length of the "bridge" to the enum cache.
2804   static const int kEnumCacheBridgeLength = 2;
2805   static const int kEnumCacheBridgeCacheIndex = 0;
2806   static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2807
2808   // Layout description.
2809   static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2810   static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2811   static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2812
2813   // Layout description for the bridge array.
2814   static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2815
2816   // Layout of descriptor.
2817   static const int kDescriptorKey = 0;
2818   static const int kDescriptorDetails = 1;
2819   static const int kDescriptorValue = 2;
2820   static const int kDescriptorSize = 3;
2821
2822 #if defined(DEBUG) || defined(OBJECT_PRINT)
2823   // For our gdb macros, we should perhaps change these in the future.
2824   void Print();
2825
2826   // Print all the descriptors.
2827   void PrintDescriptors(std::ostream& os);  // NOLINT
2828 #endif
2829
2830 #ifdef DEBUG
2831   // Is the descriptor array sorted and without duplicates?
2832   bool IsSortedNoDuplicates(int valid_descriptors = -1);
2833
2834   // Is the descriptor array consistent with the back pointers in targets?
2835   bool IsConsistentWithBackPointers(Map* current_map);
2836
2837   // Are two DescriptorArrays equal?
2838   bool IsEqualTo(DescriptorArray* other);
2839 #endif
2840
2841   // Returns the fixed array length required to hold number_of_descriptors
2842   // descriptors.
2843   static int LengthFor(int number_of_descriptors) {
2844     return ToKeyIndex(number_of_descriptors);
2845   }
2846
2847  private:
2848   // WhitenessWitness is used to prove that a descriptor array is white
2849   // (unmarked), so incremental write barriers can be skipped because the
2850   // marking invariant cannot be broken and slots pointing into evacuation
2851   // candidates will be discovered when the object is scanned. A witness is
2852   // always stack-allocated right after creating an array. By allocating a
2853   // witness, incremental marking is globally disabled. The witness is then
2854   // passed along wherever needed to statically prove that the array is known to
2855   // be white.
2856   class WhitenessWitness {
2857    public:
2858     inline explicit WhitenessWitness(DescriptorArray* array);
2859     inline ~WhitenessWitness();
2860
2861    private:
2862     IncrementalMarking* marking_;
2863   };
2864
2865   // An entry in a DescriptorArray, represented as an (array, index) pair.
2866   class Entry {
2867    public:
2868     inline explicit Entry(DescriptorArray* descs, int index) :
2869         descs_(descs), index_(index) { }
2870
2871     inline PropertyType type();
2872     inline Object* GetCallbackObject();
2873
2874    private:
2875     DescriptorArray* descs_;
2876     int index_;
2877   };
2878
2879   // Conversion from descriptor number to array indices.
2880   static int ToKeyIndex(int descriptor_number) {
2881     return kFirstIndex +
2882            (descriptor_number * kDescriptorSize) +
2883            kDescriptorKey;
2884   }
2885
2886   static int ToDetailsIndex(int descriptor_number) {
2887     return kFirstIndex +
2888            (descriptor_number * kDescriptorSize) +
2889            kDescriptorDetails;
2890   }
2891
2892   static int ToValueIndex(int descriptor_number) {
2893     return kFirstIndex +
2894            (descriptor_number * kDescriptorSize) +
2895            kDescriptorValue;
2896   }
2897
2898   // Transfer a complete descriptor from the src descriptor array to this
2899   // descriptor array.
2900   void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2901
2902   inline void Set(int descriptor_number,
2903                   Descriptor* desc,
2904                   const WhitenessWitness&);
2905
2906   // Swap first and second descriptor.
2907   inline void SwapSortedKeys(int first, int second);
2908
2909   DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2910 };
2911
2912
2913 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2914
2915 template <SearchMode search_mode, typename T>
2916 inline int Search(T* array, Name* name, int valid_entries = 0,
2917                   int* out_insertion_index = NULL);
2918
2919
2920 // HashTable is a subclass of FixedArray that implements a hash table
2921 // that uses open addressing and quadratic probing.
2922 //
2923 // In order for the quadratic probing to work, elements that have not
2924 // yet been used and elements that have been deleted are
2925 // distinguished.  Probing continues when deleted elements are
2926 // encountered and stops when unused elements are encountered.
2927 //
2928 // - Elements with key == undefined have not been used yet.
2929 // - Elements with key == the_hole have been deleted.
2930 //
2931 // The hash table class is parameterized with a Shape and a Key.
2932 // Shape must be a class with the following interface:
2933 //   class ExampleShape {
2934 //    public:
2935 //      // Tells whether key matches other.
2936 //     static bool IsMatch(Key key, Object* other);
2937 //     // Returns the hash value for key.
2938 //     static uint32_t Hash(Key key);
2939 //     // Returns the hash value for object.
2940 //     static uint32_t HashForObject(Key key, Object* object);
2941 //     // Convert key to an object.
2942 //     static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2943 //     // The prefix size indicates number of elements in the beginning
2944 //     // of the backing storage.
2945 //     static const int kPrefixSize = ..;
2946 //     // The Element size indicates number of elements per entry.
2947 //     static const int kEntrySize = ..;
2948 //   };
2949 // The prefix size indicates an amount of memory in the
2950 // beginning of the backing storage that can be used for non-element
2951 // information by subclasses.
2952
2953 template<typename Key>
2954 class BaseShape {
2955  public:
2956   static const bool UsesSeed = false;
2957   static uint32_t Hash(Key key) { return 0; }
2958   static uint32_t SeededHash(Key key, uint32_t seed) {
2959     DCHECK(UsesSeed);
2960     return Hash(key);
2961   }
2962   static uint32_t HashForObject(Key key, Object* object) { return 0; }
2963   static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2964     DCHECK(UsesSeed);
2965     return HashForObject(key, object);
2966   }
2967 };
2968
2969
2970 class HashTableBase : public FixedArray {
2971  public:
2972   // Returns the number of elements in the hash table.
2973   inline int NumberOfElements();
2974
2975   // Returns the number of deleted elements in the hash table.
2976   inline int NumberOfDeletedElements();
2977
2978   // Returns the capacity of the hash table.
2979   inline int Capacity();
2980
2981   // ElementAdded should be called whenever an element is added to a
2982   // hash table.
2983   inline void ElementAdded();
2984
2985   // ElementRemoved should be called whenever an element is removed from
2986   // a hash table.
2987   inline void ElementRemoved();
2988   inline void ElementsRemoved(int n);
2989
2990   // Computes the required capacity for a table holding the given
2991   // number of elements. May be more than HashTable::kMaxCapacity.
2992   static inline int ComputeCapacity(int at_least_space_for);
2993
2994   // Tells whether k is a real key.  The hole and undefined are not allowed
2995   // as keys and can be used to indicate missing or deleted elements.
2996   inline bool IsKey(Object* k);
2997
2998   // Compute the probe offset (quadratic probing).
2999   INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3000     return (n + n * n) >> 1;
3001   }
3002
3003   static const int kNumberOfElementsIndex = 0;
3004   static const int kNumberOfDeletedElementsIndex = 1;
3005   static const int kCapacityIndex = 2;
3006   static const int kPrefixStartIndex = 3;
3007
3008   // Constant used for denoting a absent entry.
3009   static const int kNotFound = -1;
3010
3011  protected:
3012   // Update the number of elements in the hash table.
3013   inline void SetNumberOfElements(int nof);
3014
3015   // Update the number of deleted elements in the hash table.
3016   inline void SetNumberOfDeletedElements(int nod);
3017
3018   // Returns probe entry.
3019   static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3020     DCHECK(base::bits::IsPowerOfTwo32(size));
3021     return (hash + GetProbeOffset(number)) & (size - 1);
3022   }
3023
3024   inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3025     return hash & (size - 1);
3026   }
3027
3028   inline static uint32_t NextProbe(
3029       uint32_t last, uint32_t number, uint32_t size) {
3030     return (last + number) & (size - 1);
3031   }
3032 };
3033
3034
3035 template <typename Derived, typename Shape, typename Key>
3036 class HashTable : public HashTableBase {
3037  public:
3038   // Wrapper methods
3039   inline uint32_t Hash(Key key) {
3040     if (Shape::UsesSeed) {
3041       return Shape::SeededHash(key, GetHeap()->HashSeed());
3042     } else {
3043       return Shape::Hash(key);
3044     }
3045   }
3046
3047   inline uint32_t HashForObject(Key key, Object* object) {
3048     if (Shape::UsesSeed) {
3049       return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3050     } else {
3051       return Shape::HashForObject(key, object);
3052     }
3053   }
3054
3055   // Returns a new HashTable object.
3056   MUST_USE_RESULT static Handle<Derived> New(
3057       Isolate* isolate, int at_least_space_for,
3058       MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3059       PretenureFlag pretenure = NOT_TENURED);
3060
3061   DECLARE_CAST(HashTable)
3062
3063   // Garbage collection support.
3064   void IteratePrefix(ObjectVisitor* visitor);
3065   void IterateElements(ObjectVisitor* visitor);
3066
3067   // Find entry for key otherwise return kNotFound.
3068   inline int FindEntry(Key key);
3069   inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3070   int FindEntry(Isolate* isolate, Key key);
3071
3072   // Rehashes the table in-place.
3073   void Rehash(Key key);
3074
3075   // Returns the key at entry.
3076   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3077
3078   static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3079   static const int kEntrySize = Shape::kEntrySize;
3080   static const int kElementsStartOffset =
3081       kHeaderSize + kElementsStartIndex * kPointerSize;
3082   static const int kCapacityOffset =
3083       kHeaderSize + kCapacityIndex * kPointerSize;
3084
3085   // Returns the index for an entry (of the key)
3086   static inline int EntryToIndex(int entry) {
3087     return (entry * kEntrySize) + kElementsStartIndex;
3088   }
3089
3090  protected:
3091   friend class ObjectHashTable;
3092
3093   // Find the entry at which to insert element with the given key that
3094   // has the given hash value.
3095   uint32_t FindInsertionEntry(uint32_t hash);
3096
3097   // Attempt to shrink hash table after removal of key.
3098   MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3099
3100   // Ensure enough space for n additional elements.
3101   MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3102       Handle<Derived> table,
3103       int n,
3104       Key key,
3105       PretenureFlag pretenure = NOT_TENURED);
3106
3107   // Sets the capacity of the hash table.
3108   void SetCapacity(int capacity) {
3109     // To scale a computed hash code to fit within the hash table, we
3110     // use bit-wise AND with a mask, so the capacity must be positive
3111     // and non-zero.
3112     DCHECK(capacity > 0);
3113     DCHECK(capacity <= kMaxCapacity);
3114     set(kCapacityIndex, Smi::FromInt(capacity));
3115   }
3116
3117   // Maximal capacity of HashTable. Based on maximal length of underlying
3118   // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3119   // cannot overflow.
3120   static const int kMaxCapacity =
3121       (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3122
3123  private:
3124   // Returns _expected_ if one of entries given by the first _probe_ probes is
3125   // equal to  _expected_. Otherwise, returns the entry given by the probe
3126   // number _probe_.
3127   uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3128
3129   void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3130
3131   // Rehashes this hash-table into the new table.
3132   void Rehash(Handle<Derived> new_table, Key key);
3133 };
3134
3135
3136 // HashTableKey is an abstract superclass for virtual key behavior.
3137 class HashTableKey {
3138  public:
3139   // Returns whether the other object matches this key.
3140   virtual bool IsMatch(Object* other) = 0;
3141   // Returns the hash value for this key.
3142   virtual uint32_t Hash() = 0;
3143   // Returns the hash value for object.
3144   virtual uint32_t HashForObject(Object* key) = 0;
3145   // Returns the key object for storing into the hash table.
3146   MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3147   // Required.
3148   virtual ~HashTableKey() {}
3149 };
3150
3151
3152 class StringTableShape : public BaseShape<HashTableKey*> {
3153  public:
3154   static inline bool IsMatch(HashTableKey* key, Object* value) {
3155     return key->IsMatch(value);
3156   }
3157
3158   static inline uint32_t Hash(HashTableKey* key) {
3159     return key->Hash();
3160   }
3161
3162   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3163     return key->HashForObject(object);
3164   }
3165
3166   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3167
3168   static const int kPrefixSize = 0;
3169   static const int kEntrySize = 1;
3170 };
3171
3172 class SeqOneByteString;
3173
3174 // StringTable.
3175 //
3176 // No special elements in the prefix and the element size is 1
3177 // because only the string itself (the key) needs to be stored.
3178 class StringTable: public HashTable<StringTable,
3179                                     StringTableShape,
3180                                     HashTableKey*> {
3181  public:
3182   // Find string in the string table. If it is not there yet, it is
3183   // added. The return value is the string found.
3184   static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3185   static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3186   static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3187
3188   // Tries to internalize given string and returns string handle on success
3189   // or an empty handle otherwise.
3190   MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3191       Isolate* isolate,
3192       Handle<String> string);
3193
3194   // Looks up a string that is equal to the given string and returns
3195   // string handle if it is found, or an empty handle otherwise.
3196   MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3197       Isolate* isolate,
3198       Handle<String> str);
3199   MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3200       Isolate* isolate,
3201       uint16_t c1,
3202       uint16_t c2);
3203
3204   static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3205
3206   DECLARE_CAST(StringTable)
3207
3208  private:
3209   template <bool seq_one_byte>
3210   friend class JsonParser;
3211
3212   DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3213 };
3214
3215
3216 template <typename Derived, typename Shape, typename Key>
3217 class Dictionary: public HashTable<Derived, Shape, Key> {
3218   typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3219
3220  public:
3221   // Returns the value at entry.
3222   Object* ValueAt(int entry) {
3223     return this->get(Derived::EntryToIndex(entry) + 1);
3224   }
3225
3226   // Set the value for entry.
3227   void ValueAtPut(int entry, Object* value) {
3228     this->set(Derived::EntryToIndex(entry) + 1, value);
3229   }
3230
3231   // Returns the property details for the property at entry.
3232   PropertyDetails DetailsAt(int entry) {
3233     return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3234   }
3235
3236   // Set the details for entry.
3237   void DetailsAtPut(int entry, PropertyDetails value) {
3238     Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3239   }
3240
3241   // Returns true if property at given entry is deleted.
3242   bool IsDeleted(int entry) {
3243     return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3244   }
3245
3246   // Delete a property from the dictionary.
3247   static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3248
3249   // Attempt to shrink the dictionary after deletion of key.
3250   MUST_USE_RESULT static inline Handle<Derived> Shrink(
3251       Handle<Derived> dictionary,
3252       Key key) {
3253     return DerivedHashTable::Shrink(dictionary, key);
3254   }
3255
3256   // Sorting support
3257   // TODO(dcarney): templatize or move to SeededNumberDictionary
3258   void CopyValuesTo(FixedArray* elements);
3259
3260   // Returns the number of elements in the dictionary filtering out properties
3261   // with the specified attributes.
3262   int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3263
3264   // Returns the number of enumerable elements in the dictionary.
3265   int NumberOfEnumElements() {
3266     return NumberOfElementsFilterAttributes(
3267         static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3268   }
3269
3270   // Returns true if the dictionary contains any elements that are non-writable,
3271   // non-configurable, non-enumerable, or have getters/setters.
3272   bool HasComplexElements();
3273
3274   enum SortMode { UNSORTED, SORTED };
3275
3276   // Fill in details for properties into storage.
3277   // Returns the number of properties added.
3278   int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3279                  SortMode sort_mode);
3280
3281   // Copies enumerable keys to preallocated fixed array.
3282   void CopyEnumKeysTo(FixedArray* storage);
3283
3284   // Accessors for next enumeration index.
3285   void SetNextEnumerationIndex(int index) {
3286     DCHECK(index != 0);
3287     this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3288   }
3289
3290   int NextEnumerationIndex() {
3291     return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3292   }
3293
3294   // Creates a new dictionary.
3295   MUST_USE_RESULT static Handle<Derived> New(
3296       Isolate* isolate,
3297       int at_least_space_for,
3298       PretenureFlag pretenure = NOT_TENURED);
3299
3300   // Ensure enough space for n additional elements.
3301   static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3302
3303 #ifdef OBJECT_PRINT
3304   void Print(std::ostream& os);  // NOLINT
3305 #endif
3306   // Returns the key (slow).
3307   Object* SlowReverseLookup(Object* value);
3308
3309   // Sets the entry to (key, value) pair.
3310   inline void SetEntry(int entry,
3311                        Handle<Object> key,
3312                        Handle<Object> value);
3313   inline void SetEntry(int entry,
3314                        Handle<Object> key,
3315                        Handle<Object> value,
3316                        PropertyDetails details);
3317
3318   MUST_USE_RESULT static Handle<Derived> Add(
3319       Handle<Derived> dictionary,
3320       Key key,
3321       Handle<Object> value,
3322       PropertyDetails details);
3323
3324   // Returns iteration indices array for the |dictionary|.
3325   // Values are direct indices in the |HashTable| array.
3326   static Handle<FixedArray> BuildIterationIndicesArray(
3327       Handle<Derived> dictionary);
3328
3329  protected:
3330   // Generic at put operation.
3331   MUST_USE_RESULT static Handle<Derived> AtPut(
3332       Handle<Derived> dictionary,
3333       Key key,
3334       Handle<Object> value);
3335
3336   // Add entry to dictionary.
3337   static void AddEntry(
3338       Handle<Derived> dictionary,
3339       Key key,
3340       Handle<Object> value,
3341       PropertyDetails details,
3342       uint32_t hash);
3343
3344   // Generate new enumeration indices to avoid enumeration index overflow.
3345   // Returns iteration indices array for the |dictionary|.
3346   static Handle<FixedArray> GenerateNewEnumerationIndices(
3347       Handle<Derived> dictionary);
3348   static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3349   static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3350 };
3351
3352
3353 template <typename Derived, typename Shape>
3354 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3355   typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3356
3357  public:
3358   // Find entry for key, otherwise return kNotFound. Optimized version of
3359   // HashTable::FindEntry.
3360   int FindEntry(Handle<Name> key);
3361 };
3362
3363
3364 template <typename Key>
3365 class BaseDictionaryShape : public BaseShape<Key> {
3366  public:
3367   template <typename Dictionary>
3368   static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3369     STATIC_ASSERT(Dictionary::kEntrySize == 3);
3370     DCHECK(entry >= 0);  // Not found is -1, which is not caught by get().
3371     return PropertyDetails(
3372         Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3373   }
3374
3375   template <typename Dictionary>
3376   static inline void DetailsAtPut(Dictionary* dict, int entry,
3377                                   PropertyDetails value) {
3378     STATIC_ASSERT(Dictionary::kEntrySize == 3);
3379     dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3380   }
3381
3382   template <typename Dictionary>
3383   static bool IsDeleted(Dictionary* dict, int entry) {
3384     return false;
3385   }
3386
3387   template <typename Dictionary>
3388   static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3389                               Handle<Object> value, PropertyDetails details);
3390 };
3391
3392
3393 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3394  public:
3395   static inline bool IsMatch(Handle<Name> key, Object* other);
3396   static inline uint32_t Hash(Handle<Name> key);
3397   static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3398   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3399   static const int kPrefixSize = 2;
3400   static const int kEntrySize = 3;
3401   static const bool kIsEnumerable = true;
3402 };
3403
3404
3405 class NameDictionary
3406     : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3407   typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3408       DerivedDictionary;
3409
3410  public:
3411   DECLARE_CAST(NameDictionary)
3412
3413   inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3414       Handle<NameDictionary> dictionary);
3415 };
3416
3417
3418 class GlobalDictionaryShape : public NameDictionaryShape {
3419  public:
3420   static const int kEntrySize = 2;  // Overrides NameDictionaryShape::kEntrySize
3421
3422   template <typename Dictionary>
3423   static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3424
3425   template <typename Dictionary>
3426   static inline void DetailsAtPut(Dictionary* dict, int entry,
3427                                   PropertyDetails value);
3428
3429   template <typename Dictionary>
3430   static bool IsDeleted(Dictionary* dict, int entry);
3431
3432   template <typename Dictionary>
3433   static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3434                               Handle<Object> value, PropertyDetails details);
3435 };
3436
3437
3438 class GlobalDictionary
3439     : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3440  public:
3441   DECLARE_CAST(GlobalDictionary)
3442 };
3443
3444
3445 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3446  public:
3447   static inline bool IsMatch(uint32_t key, Object* other);
3448   static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3449   static const int kEntrySize = 3;
3450   static const bool kIsEnumerable = false;
3451 };
3452
3453
3454 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3455  public:
3456   static const bool UsesSeed = true;
3457   static const int kPrefixSize = 2;
3458
3459   static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3460   static inline uint32_t SeededHashForObject(uint32_t key,
3461                                              uint32_t seed,
3462                                              Object* object);
3463 };
3464
3465
3466 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3467  public:
3468   static const int kPrefixSize = 0;
3469
3470   static inline uint32_t Hash(uint32_t key);
3471   static inline uint32_t HashForObject(uint32_t key, Object* object);
3472 };
3473
3474
3475 class SeededNumberDictionary
3476     : public Dictionary<SeededNumberDictionary,
3477                         SeededNumberDictionaryShape,
3478                         uint32_t> {
3479  public:
3480   DECLARE_CAST(SeededNumberDictionary)
3481
3482   // Type specific at put (default NONE attributes is used when adding).
3483   MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3484       Handle<SeededNumberDictionary> dictionary, uint32_t key,
3485       Handle<Object> value, bool used_as_prototype);
3486   MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3487       Handle<SeededNumberDictionary> dictionary, uint32_t key,
3488       Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3489
3490   // Set an existing entry or add a new one if needed.
3491   // Return the updated dictionary.
3492   MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3493       Handle<SeededNumberDictionary> dictionary, uint32_t key,
3494       Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3495
3496   void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3497
3498   // If slow elements are required we will never go back to fast-case
3499   // for the elements kept in this dictionary.  We require slow
3500   // elements if an element has been added at an index larger than
3501   // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3502   // when defining a getter or setter with a number key.
3503   inline bool requires_slow_elements();
3504   inline void set_requires_slow_elements();
3505
3506   // Get the value of the max number key that has been added to this
3507   // dictionary.  max_number_key can only be called if
3508   // requires_slow_elements returns false.
3509   inline uint32_t max_number_key();
3510
3511   // Bit masks.
3512   static const int kRequiresSlowElementsMask = 1;
3513   static const int kRequiresSlowElementsTagSize = 1;
3514   static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3515 };
3516
3517
3518 class UnseededNumberDictionary
3519     : public Dictionary<UnseededNumberDictionary,
3520                         UnseededNumberDictionaryShape,
3521                         uint32_t> {
3522  public:
3523   DECLARE_CAST(UnseededNumberDictionary)
3524
3525   // Type specific at put (default NONE attributes is used when adding).
3526   MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3527       Handle<UnseededNumberDictionary> dictionary,
3528       uint32_t key,
3529       Handle<Object> value);
3530   MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3531       Handle<UnseededNumberDictionary> dictionary,
3532       uint32_t key,
3533       Handle<Object> value);
3534
3535   // Set an existing entry or add a new one if needed.
3536   // Return the updated dictionary.
3537   MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3538       Handle<UnseededNumberDictionary> dictionary,
3539       uint32_t key,
3540       Handle<Object> value);
3541 };
3542
3543
3544 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3545  public:
3546   static inline bool IsMatch(Handle<Object> key, Object* other);
3547   static inline uint32_t Hash(Handle<Object> key);
3548   static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3549   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3550   static const int kPrefixSize = 0;
3551   static const int kEntrySize = 2;
3552 };
3553
3554
3555 // ObjectHashTable maps keys that are arbitrary objects to object values by
3556 // using the identity hash of the key for hashing purposes.
3557 class ObjectHashTable: public HashTable<ObjectHashTable,
3558                                         ObjectHashTableShape,
3559                                         Handle<Object> > {
3560   typedef HashTable<
3561       ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3562  public:
3563   DECLARE_CAST(ObjectHashTable)
3564
3565   // Attempt to shrink hash table after removal of key.
3566   MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3567       Handle<ObjectHashTable> table,
3568       Handle<Object> key);
3569
3570   // Looks up the value associated with the given key. The hole value is
3571   // returned in case the key is not present.
3572   Object* Lookup(Handle<Object> key);
3573   Object* Lookup(Handle<Object> key, int32_t hash);
3574   Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3575
3576   // Adds (or overwrites) the value associated with the given key.
3577   static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3578                                      Handle<Object> key,
3579                                      Handle<Object> value);
3580   static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3581                                      Handle<Object> key, Handle<Object> value,
3582                                      int32_t hash);
3583
3584   // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3585   static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3586                                         Handle<Object> key,
3587                                         bool* was_present);
3588   static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3589                                         Handle<Object> key, bool* was_present,
3590                                         int32_t hash);
3591
3592  protected:
3593   friend class MarkCompactCollector;
3594
3595   void AddEntry(int entry, Object* key, Object* value);
3596   void RemoveEntry(int entry);
3597
3598   // Returns the index to the value of an entry.
3599   static inline int EntryToValueIndex(int entry) {
3600     return EntryToIndex(entry) + 1;
3601   }
3602 };
3603
3604
3605 // OrderedHashTable is a HashTable with Object keys that preserves
3606 // insertion order. There are Map and Set interfaces (OrderedHashMap
3607 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3608 //
3609 // Only Object* keys are supported, with Object::SameValueZero() used as the
3610 // equality operator and Object::GetHash() for the hash function.
3611 //
3612 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3613 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3614 // Originally attributed to Tyler Close.
3615 //
3616 // Memory layout:
3617 //   [0]: bucket count
3618 //   [1]: element count
3619 //   [2]: deleted element count
3620 //   [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3621 //                            offset into the data table (see below) where the
3622 //                            first item in this bucket is stored.
3623 //   [3 + NumberOfBuckets()..length]: "data table", an array of length
3624 //                            Capacity() * kEntrySize, where the first entrysize
3625 //                            items are handled by the derived class and the
3626 //                            item at kChainOffset is another entry into the
3627 //                            data table indicating the next entry in this hash
3628 //                            bucket.
3629 //
3630 // When we transition the table to a new version we obsolete it and reuse parts
3631 // of the memory to store information how to transition an iterator to the new
3632 // table:
3633 //
3634 // Memory layout for obsolete table:
3635 //   [0]: bucket count
3636 //   [1]: Next newer table
3637 //   [2]: Number of removed holes or -1 when the table was cleared.
3638 //   [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3639 //   [3 + NumberOfRemovedHoles()..length]: Not used
3640 //
3641 template<class Derived, class Iterator, int entrysize>
3642 class OrderedHashTable: public FixedArray {
3643  public:
3644   // Returns an OrderedHashTable with a capacity of at least |capacity|.
3645   static Handle<Derived> Allocate(
3646       Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3647
3648   // Returns an OrderedHashTable (possibly |table|) with enough space
3649   // to add at least one new element.
3650   static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3651
3652   // Returns an OrderedHashTable (possibly |table|) that's shrunken
3653   // if possible.
3654   static Handle<Derived> Shrink(Handle<Derived> table);
3655
3656   // Returns a new empty OrderedHashTable and records the clearing so that
3657   // exisiting iterators can be updated.
3658   static Handle<Derived> Clear(Handle<Derived> table);
3659
3660   int NumberOfElements() {
3661     return Smi::cast(get(kNumberOfElementsIndex))->value();
3662   }
3663
3664   int NumberOfDeletedElements() {
3665     return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3666   }
3667
3668   int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3669
3670   int NumberOfBuckets() {
3671     return Smi::cast(get(kNumberOfBucketsIndex))->value();
3672   }
3673
3674   // Returns an index into |this| for the given entry.
3675   int EntryToIndex(int entry) {
3676     return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3677   }
3678
3679   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3680
3681   bool IsObsolete() {
3682     return !get(kNextTableIndex)->IsSmi();
3683   }
3684
3685   // The next newer table. This is only valid if the table is obsolete.
3686   Derived* NextTable() {
3687     return Derived::cast(get(kNextTableIndex));
3688   }
3689
3690   // When the table is obsolete we store the indexes of the removed holes.
3691   int RemovedIndexAt(int index) {
3692     return Smi::cast(get(kRemovedHolesIndex + index))->value();
3693   }
3694
3695   static const int kNotFound = -1;
3696   static const int kMinCapacity = 4;
3697
3698   static const int kNumberOfBucketsIndex = 0;
3699   static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3700   static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3701   static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3702   static const int kNextTableIndex = kNumberOfElementsIndex;
3703
3704   static const int kNumberOfBucketsOffset =
3705       kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3706   static const int kNumberOfElementsOffset =
3707       kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3708   static const int kNumberOfDeletedElementsOffset =
3709       kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3710   static const int kHashTableStartOffset =
3711       kHeaderSize + kHashTableStartIndex * kPointerSize;
3712   static const int kNextTableOffset =
3713       kHeaderSize + kNextTableIndex * kPointerSize;
3714
3715   static const int kEntrySize = entrysize + 1;
3716   static const int kChainOffset = entrysize;
3717
3718   static const int kLoadFactor = 2;
3719
3720   // NumberOfDeletedElements is set to kClearedTableSentinel when
3721   // the table is cleared, which allows iterator transitions to
3722   // optimize that case.
3723   static const int kClearedTableSentinel = -1;
3724
3725  private:
3726   static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3727
3728   void SetNumberOfBuckets(int num) {
3729     set(kNumberOfBucketsIndex, Smi::FromInt(num));
3730   }
3731
3732   void SetNumberOfElements(int num) {
3733     set(kNumberOfElementsIndex, Smi::FromInt(num));
3734   }
3735
3736   void SetNumberOfDeletedElements(int num) {
3737     set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3738   }
3739
3740   int Capacity() {
3741     return NumberOfBuckets() * kLoadFactor;
3742   }
3743
3744   void SetNextTable(Derived* next_table) {
3745     set(kNextTableIndex, next_table);
3746   }
3747
3748   void SetRemovedIndexAt(int index, int removed_index) {
3749     return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3750   }
3751
3752   static const int kRemovedHolesIndex = kHashTableStartIndex;
3753
3754   static const int kMaxCapacity =
3755       (FixedArray::kMaxLength - kHashTableStartIndex)
3756       / (1 + (kEntrySize * kLoadFactor));
3757 };
3758
3759
3760 class JSSetIterator;
3761
3762
3763 class OrderedHashSet: public OrderedHashTable<
3764     OrderedHashSet, JSSetIterator, 1> {
3765  public:
3766   DECLARE_CAST(OrderedHashSet)
3767 };
3768
3769
3770 class JSMapIterator;
3771
3772
3773 class OrderedHashMap
3774     : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3775  public:
3776   DECLARE_CAST(OrderedHashMap)
3777
3778   inline Object* ValueAt(int entry);
3779
3780   static const int kValueOffset = 1;
3781 };
3782
3783
3784 template <int entrysize>
3785 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3786  public:
3787   static inline bool IsMatch(Handle<Object> key, Object* other);
3788   static inline uint32_t Hash(Handle<Object> key);
3789   static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3790   static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3791   static const int kPrefixSize = 0;
3792   static const int kEntrySize = entrysize;
3793 };
3794
3795
3796 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3797 // values. The table wraps the keys in weak cells and store values directly.
3798 // Thus it references keys weakly and values strongly.
3799 class WeakHashTable: public HashTable<WeakHashTable,
3800                                       WeakHashTableShape<2>,
3801                                       Handle<Object> > {
3802   typedef HashTable<
3803       WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3804  public:
3805   DECLARE_CAST(WeakHashTable)
3806
3807   // Looks up the value associated with the given key. The hole value is
3808   // returned in case the key is not present.
3809   Object* Lookup(Handle<HeapObject> key);
3810
3811   // Adds (or overwrites) the value associated with the given key. Mapping a
3812   // key to the hole value causes removal of the whole entry.
3813   MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3814                                                    Handle<HeapObject> key,
3815                                                    Handle<HeapObject> value);
3816
3817   static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3818
3819  private:
3820   friend class MarkCompactCollector;
3821
3822   void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3823
3824   // Returns the index to the value of an entry.
3825   static inline int EntryToValueIndex(int entry) {
3826     return EntryToIndex(entry) + 1;
3827   }
3828 };
3829
3830
3831 // ScopeInfo represents information about different scopes of a source
3832 // program  and the allocation of the scope's variables. Scope information
3833 // is stored in a compressed form in ScopeInfo objects and is used
3834 // at runtime (stack dumps, deoptimization, etc.).
3835
3836 // This object provides quick access to scope info details for runtime
3837 // routines.
3838 class ScopeInfo : public FixedArray {
3839  public:
3840   DECLARE_CAST(ScopeInfo)
3841
3842   // Return the type of this scope.
3843   ScopeType scope_type();
3844
3845   // Does this scope call eval?
3846   bool CallsEval();
3847
3848   // Return the language mode of this scope.
3849   LanguageMode language_mode();
3850
3851   // True if this scope is a (var) declaration scope.
3852   bool is_declaration_scope();
3853
3854   // Does this scope make a sloppy eval call?
3855   bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3856
3857   // Return the total number of locals allocated on the stack and in the
3858   // context. This includes the parameters that are allocated in the context.
3859   int LocalCount();
3860
3861   // Return the number of stack slots for code. This number consists of two
3862   // parts:
3863   //  1. One stack slot per stack allocated local.
3864   //  2. One stack slot for the function name if it is stack allocated.
3865   int StackSlotCount();
3866
3867   // Return the number of context slots for code if a context is allocated. This
3868   // number consists of three parts:
3869   //  1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3870   //  2. One context slot per context allocated local.
3871   //  3. One context slot for the function name if it is context allocated.
3872   // Parameters allocated in the context count as context allocated locals. If
3873   // no contexts are allocated for this scope ContextLength returns 0.
3874   int ContextLength();
3875
3876   // Does this scope declare a "this" binding?
3877   bool HasReceiver();
3878
3879   // Does this scope declare a "this" binding, and the "this" binding is stack-
3880   // or context-allocated?
3881   bool HasAllocatedReceiver();
3882
3883   // Is this scope the scope of a named function expression?
3884   bool HasFunctionName();
3885
3886   // Return if this has context allocated locals.
3887   bool HasHeapAllocatedLocals();
3888
3889   // Return if contexts are allocated for this scope.
3890   bool HasContext();
3891
3892   // Return if this is a function scope with "use asm".
3893   inline bool IsAsmModule();
3894
3895   // Return if this is a nested function within an asm module scope.
3896   inline bool IsAsmFunction();
3897
3898   inline bool HasSimpleParameters();
3899
3900   // Return the function_name if present.
3901   String* FunctionName();
3902
3903   // Return the name of the given parameter.
3904   String* ParameterName(int var);
3905
3906   // Return the name of the given local.
3907   String* LocalName(int var);
3908
3909   // Return the name of the given stack local.
3910   String* StackLocalName(int var);
3911
3912   // Return the name of the given stack local.
3913   int StackLocalIndex(int var);
3914
3915   // Return the name of the given context local.
3916   String* ContextLocalName(int var);
3917
3918   // Return the mode of the given context local.
3919   VariableMode ContextLocalMode(int var);
3920
3921   // Return the initialization flag of the given context local.
3922   InitializationFlag ContextLocalInitFlag(int var);
3923
3924   // Return the initialization flag of the given context local.
3925   MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3926
3927   // Return true if this local was introduced by the compiler, and should not be
3928   // exposed to the user in a debugger.
3929   bool LocalIsSynthetic(int var);
3930
3931   String* StrongModeFreeVariableName(int var);
3932   int StrongModeFreeVariableStartPosition(int var);
3933   int StrongModeFreeVariableEndPosition(int var);
3934
3935   // Lookup support for serialized scope info. Returns the
3936   // the stack slot index for a given slot name if the slot is
3937   // present; otherwise returns a value < 0. The name must be an internalized
3938   // string.
3939   int StackSlotIndex(String* name);
3940
3941   // Lookup support for serialized scope info. Returns the local context slot
3942   // index for a given slot name if the slot is present; otherwise
3943   // returns a value < 0. The name must be an internalized string.
3944   // If the slot is present and mode != NULL, sets *mode to the corresponding
3945   // mode for that variable.
3946   static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3947                               VariableMode* mode, InitializationFlag* init_flag,
3948                               MaybeAssignedFlag* maybe_assigned_flag);
3949
3950   // Similar to ContextSlotIndex() but this method searches only among
3951   // global slots of the serialized scope info. Returns the context slot index
3952   // for a given slot name if the slot is present; otherwise returns a
3953   // value < 0. The name must be an internalized string. If the slot is present
3954   // and mode != NULL, sets *mode to the corresponding mode for that variable.
3955   static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
3956                                     Handle<String> name, VariableMode* mode,
3957                                     InitializationFlag* init_flag,
3958                                     MaybeAssignedFlag* maybe_assigned_flag);
3959
3960   // Lookup the name of a certain context slot by its index.
3961   String* ContextSlotName(int slot_index);
3962
3963   // Lookup support for serialized scope info. Returns the
3964   // parameter index for a given parameter name if the parameter is present;
3965   // otherwise returns a value < 0. The name must be an internalized string.
3966   int ParameterIndex(String* name);
3967
3968   // Lookup support for serialized scope info. Returns the function context
3969   // slot index if the function name is present and context-allocated (named
3970   // function expressions, only), otherwise returns a value < 0. The name
3971   // must be an internalized string.
3972   int FunctionContextSlotIndex(String* name, VariableMode* mode);
3973
3974   // Lookup support for serialized scope info.  Returns the receiver context
3975   // slot index if scope has a "this" binding, and the binding is
3976   // context-allocated.  Otherwise returns a value < 0.
3977   int ReceiverContextSlotIndex();
3978
3979   FunctionKind function_kind();
3980
3981   static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3982   static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3983
3984   // Serializes empty scope info.
3985   static ScopeInfo* Empty(Isolate* isolate);
3986
3987 #ifdef DEBUG
3988   void Print();
3989 #endif
3990
3991   // The layout of the static part of a ScopeInfo is as follows. Each entry is
3992   // numeric and occupies one array slot.
3993   // 1. A set of properties of the scope
3994   // 2. The number of parameters. This only applies to function scopes. For
3995   //    non-function scopes this is 0.
3996   // 3. The number of non-parameter variables allocated on the stack.
3997   // 4. The number of non-parameter and parameter variables allocated in the
3998   //    context.
3999 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4000   V(Flags)                                   \
4001   V(ParameterCount)                          \
4002   V(StackLocalCount)                         \
4003   V(ContextLocalCount)                       \
4004   V(ContextGlobalCount)                      \
4005   V(StrongModeFreeVariableCount)
4006
4007 #define FIELD_ACCESSORS(name)       \
4008   inline void Set##name(int value); \
4009   inline int name();
4010   FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4011 #undef FIELD_ACCESSORS
4012
4013  private:
4014   enum {
4015 #define DECL_INDEX(name) k##name,
4016     FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4017 #undef DECL_INDEX
4018     kVariablePartIndex
4019   };
4020
4021   // The layout of the variable part of a ScopeInfo is as follows:
4022   // 1. ParameterEntries:
4023   //    This part stores the names of the parameters for function scopes. One
4024   //    slot is used per parameter, so in total this part occupies
4025   //    ParameterCount() slots in the array. For other scopes than function
4026   //    scopes ParameterCount() is 0.
4027   // 2. StackLocalFirstSlot:
4028   //    Index of a first stack slot for stack local. Stack locals belonging to
4029   //    this scope are located on a stack at slots starting from this index.
4030   // 3. StackLocalEntries:
4031   //    Contains the names of local variables that are allocated on the stack,
4032   //    in increasing order of the stack slot index. First local variable has
4033   //    a stack slot index defined in StackLocalFirstSlot (point 2 above).
4034   //    One slot is used per stack local, so in total this part occupies
4035   //    StackLocalCount() slots in the array.
4036   // 4. ContextLocalNameEntries:
4037   //    Contains the names of local variables and parameters that are allocated
4038   //    in the context. They are stored in increasing order of the context slot
4039   //    index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4040   //    context local, so in total this part occupies ContextLocalCount() slots
4041   //    in the array.
4042   // 5. ContextLocalInfoEntries:
4043   //    Contains the variable modes and initialization flags corresponding to
4044   //    the context locals in ContextLocalNameEntries. One slot is used per
4045   //    context local, so in total this part occupies ContextLocalCount()
4046   //    slots in the array.
4047   // 6. StrongModeFreeVariableNameEntries:
4048   //    Stores the names of strong mode free variables.
4049   // 7. StrongModeFreeVariablePositionEntries:
4050   //    Stores the locations (start and end position) of strong mode free
4051   //    variables.
4052   // 8. RecieverEntryIndex:
4053   //    If the scope binds a "this" value, one slot is reserved to hold the
4054   //    context or stack slot index for the variable.
4055   // 9. FunctionNameEntryIndex:
4056   //    If the scope belongs to a named function expression this part contains
4057   //    information about the function variable. It always occupies two array
4058   //    slots:  a. The name of the function variable.
4059   //            b. The context or stack slot index for the variable.
4060   int ParameterEntriesIndex();
4061   int StackLocalFirstSlotIndex();
4062   int StackLocalEntriesIndex();
4063   int ContextLocalNameEntriesIndex();
4064   int ContextGlobalNameEntriesIndex();
4065   int ContextLocalInfoEntriesIndex();
4066   int ContextGlobalInfoEntriesIndex();
4067   int StrongModeFreeVariableNameEntriesIndex();
4068   int StrongModeFreeVariablePositionEntriesIndex();
4069   int ReceiverEntryIndex();
4070   int FunctionNameEntryIndex();
4071
4072   int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4073              VariableLocation* location, InitializationFlag* init_flag,
4074              MaybeAssignedFlag* maybe_assigned_flag);
4075
4076   // Used for the function name variable for named function expressions, and for
4077   // the receiver.
4078   enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4079
4080   // Properties of scopes.
4081   class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4082   class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4083   STATIC_ASSERT(LANGUAGE_END == 3);
4084   class LanguageModeField
4085       : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4086   class DeclarationScopeField
4087       : public BitField<bool, LanguageModeField::kNext, 1> {};
4088   class ReceiverVariableField
4089       : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4090                         2> {};
4091   class FunctionVariableField
4092       : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4093                         2> {};
4094   class FunctionVariableMode
4095       : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4096   class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4097   };
4098   class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4099   class HasSimpleParametersField
4100       : public BitField<bool, AsmFunctionField::kNext, 1> {};
4101   class FunctionKindField
4102       : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4103
4104   // BitFields representing the encoded information for context locals in the
4105   // ContextLocalInfoEntries part.
4106   class ContextLocalMode:      public BitField<VariableMode,         0, 3> {};
4107   class ContextLocalInitFlag:  public BitField<InitializationFlag,   3, 1> {};
4108   class ContextLocalMaybeAssignedFlag
4109       : public BitField<MaybeAssignedFlag, 4, 1> {};
4110
4111   friend class ScopeIterator;
4112 };
4113
4114
4115 // The cache for maps used by normalized (dictionary mode) objects.
4116 // Such maps do not have property descriptors, so a typical program
4117 // needs very limited number of distinct normalized maps.
4118 class NormalizedMapCache: public FixedArray {
4119  public:
4120   static Handle<NormalizedMapCache> New(Isolate* isolate);
4121
4122   MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4123                                        PropertyNormalizationMode mode);
4124   void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4125
4126   void Clear();
4127
4128   DECLARE_CAST(NormalizedMapCache)
4129
4130   static inline bool IsNormalizedMapCache(const Object* obj);
4131
4132   DECLARE_VERIFIER(NormalizedMapCache)
4133  private:
4134   static const int kEntries = 64;
4135
4136   static inline int GetIndex(Handle<Map> map);
4137
4138   // The following declarations hide base class methods.
4139   Object* get(int index);
4140   void set(int index, Object* value);
4141 };
4142
4143
4144 // ByteArray represents fixed sized byte arrays.  Used for the relocation info
4145 // that is attached to code objects.
4146 class ByteArray: public FixedArrayBase {
4147  public:
4148   inline int Size();
4149
4150   // Setter and getter.
4151   inline byte get(int index);
4152   inline void set(int index, byte value);
4153
4154   // Treat contents as an int array.
4155   inline int get_int(int index);
4156
4157   static int SizeFor(int length) {
4158     return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4159   }
4160   // We use byte arrays for free blocks in the heap.  Given a desired size in
4161   // bytes that is a multiple of the word size and big enough to hold a byte
4162   // array, this function returns the number of elements a byte array should
4163   // have.
4164   static int LengthFor(int size_in_bytes) {
4165     DCHECK(IsAligned(size_in_bytes, kPointerSize));
4166     DCHECK(size_in_bytes >= kHeaderSize);
4167     return size_in_bytes - kHeaderSize;
4168   }
4169
4170   // Returns data start address.
4171   inline Address GetDataStartAddress();
4172
4173   // Returns a pointer to the ByteArray object for a given data start address.
4174   static inline ByteArray* FromDataStartAddress(Address address);
4175
4176   DECLARE_CAST(ByteArray)
4177
4178   // Dispatched behavior.
4179   inline int ByteArraySize();
4180   DECLARE_PRINTER(ByteArray)
4181   DECLARE_VERIFIER(ByteArray)
4182
4183   // Layout description.
4184   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4185
4186   // Maximal memory consumption for a single ByteArray.
4187   static const int kMaxSize = 512 * MB;
4188   // Maximal length of a single ByteArray.
4189   static const int kMaxLength = kMaxSize - kHeaderSize;
4190
4191  private:
4192   DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4193 };
4194
4195
4196 // BytecodeArray represents a sequence of interpreter bytecodes.
4197 class BytecodeArray : public FixedArrayBase {
4198  public:
4199   static int SizeFor(int length) {
4200     return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4201   }
4202
4203   // Setter and getter
4204   inline byte get(int index);
4205   inline void set(int index, byte value);
4206
4207   // Returns data start address.
4208   inline Address GetFirstBytecodeAddress();
4209
4210   // Accessors for frame size.
4211   inline int frame_size() const;
4212   inline void set_frame_size(int frame_size);
4213
4214   // Accessors for parameter count (including implicit 'this' receiver).
4215   inline int parameter_count() const;
4216   inline void set_parameter_count(int number_of_parameters);
4217
4218   // Accessors for the constant pool.
4219   DECL_ACCESSORS(constant_pool, FixedArray)
4220
4221   DECLARE_CAST(BytecodeArray)
4222
4223   // Dispatched behavior.
4224   inline int BytecodeArraySize();
4225   inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4226
4227   DECLARE_PRINTER(BytecodeArray)
4228   DECLARE_VERIFIER(BytecodeArray)
4229
4230   void Disassemble(std::ostream& os);
4231
4232   // Layout description.
4233   static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4234   static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4235   static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4236   static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4237
4238   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4239
4240   // Maximal memory consumption for a single BytecodeArray.
4241   static const int kMaxSize = 512 * MB;
4242   // Maximal length of a single BytecodeArray.
4243   static const int kMaxLength = kMaxSize - kHeaderSize;
4244
4245  private:
4246   DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4247 };
4248
4249
4250 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4251 // They look like heap objects (are heap object tagged and have a map) so that
4252 // the heap remains iterable.  They have a size and a next pointer.
4253 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4254 // in the free list.
4255 class FreeSpace: public HeapObject {
4256  public:
4257   // [size]: size of the free space including the header.
4258   inline int size() const;
4259   inline void set_size(int value);
4260
4261   inline int nobarrier_size() const;
4262   inline void nobarrier_set_size(int value);
4263
4264   inline int Size();
4265
4266   // Accessors for the next field.
4267   inline FreeSpace* next();
4268   inline FreeSpace** next_address();
4269   inline void set_next(FreeSpace* next);
4270
4271   inline static FreeSpace* cast(HeapObject* obj);
4272
4273   // Dispatched behavior.
4274   DECLARE_PRINTER(FreeSpace)
4275   DECLARE_VERIFIER(FreeSpace)
4276
4277   // Layout description.
4278   // Size is smi tagged when it is stored.
4279   static const int kSizeOffset = HeapObject::kHeaderSize;
4280   static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4281
4282  private:
4283   DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4284 };
4285
4286
4287 // V has parameters (Type, type, TYPE, C type, element_size)
4288 #define TYPED_ARRAYS(V) \
4289   V(Uint8, uint8, UINT8, uint8_t, 1)                                           \
4290   V(Int8, int8, INT8, int8_t, 1)                                               \
4291   V(Uint16, uint16, UINT16, uint16_t, 2)                                       \
4292   V(Int16, int16, INT16, int16_t, 2)                                           \
4293   V(Uint32, uint32, UINT32, uint32_t, 4)                                       \
4294   V(Int32, int32, INT32, int32_t, 4)                                           \
4295   V(Float32, float32, FLOAT32, float, 4)                                       \
4296   V(Float64, float64, FLOAT64, double, 8)                                      \
4297   V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4298
4299
4300 class FixedTypedArrayBase: public FixedArrayBase {
4301  public:
4302   // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4303   DECL_ACCESSORS(base_pointer, Object)
4304
4305   // [external_pointer]: Contains the offset between base_pointer and the start
4306   // of the data. If the base_pointer is a nullptr, the external_pointer
4307   // therefore points to the actual backing store.
4308   DECL_ACCESSORS(external_pointer, void)
4309
4310   // Dispatched behavior.
4311   inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4312
4313   template <typename StaticVisitor>
4314   inline void FixedTypedArrayBaseIterateBody();
4315
4316   DECLARE_CAST(FixedTypedArrayBase)
4317
4318   static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4319   static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4320   static const int kHeaderSize =
4321       DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4322
4323   static const int kDataOffset = kHeaderSize;
4324
4325   inline int size();
4326
4327   static inline int TypedArraySize(InstanceType type, int length);
4328   inline int TypedArraySize(InstanceType type);
4329
4330   // Use with care: returns raw pointer into heap.
4331   inline void* DataPtr();
4332
4333   inline int DataSize();
4334
4335  private:
4336   static inline int ElementSize(InstanceType type);
4337
4338   inline int DataSize(InstanceType type);
4339
4340   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4341 };
4342
4343
4344 template <class Traits>
4345 class FixedTypedArray: public FixedTypedArrayBase {
4346  public:
4347   typedef typename Traits::ElementType ElementType;
4348   static const InstanceType kInstanceType = Traits::kInstanceType;
4349
4350   DECLARE_CAST(FixedTypedArray<Traits>)
4351
4352   inline ElementType get_scalar(int index);
4353   static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4354   inline void set(int index, ElementType value);
4355
4356   static inline ElementType from_int(int value);
4357   static inline ElementType from_double(double value);
4358
4359   // This accessor applies the correct conversion from Smi, HeapNumber
4360   // and undefined.
4361   inline void SetValue(uint32_t index, Object* value);
4362
4363   DECLARE_PRINTER(FixedTypedArray)
4364   DECLARE_VERIFIER(FixedTypedArray)
4365
4366  private:
4367   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4368 };
4369
4370 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size)         \
4371   class Type##ArrayTraits {                                                   \
4372    public:   /* NOLINT */                                                     \
4373     typedef elementType ElementType;                                          \
4374     static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE;      \
4375     static const char* Designator() { return #type " array"; }                \
4376     static inline Handle<Object> ToHandle(Isolate* isolate,                   \
4377                                           elementType scalar);                \
4378     static inline elementType defaultValue();                                 \
4379   };                                                                          \
4380                                                                               \
4381   typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4382
4383 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4384
4385 #undef FIXED_TYPED_ARRAY_TRAITS
4386
4387
4388 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4389 // data for code generated by the Hydrogen/Lithium compiler.  It also
4390 // contains information about functions that were inlined.  If N different
4391 // functions were inlined then first N elements of the literal array will
4392 // contain these functions.
4393 //
4394 // It can be empty.
4395 class DeoptimizationInputData: public FixedArray {
4396  public:
4397   // Layout description.  Indices in the array.
4398   static const int kTranslationByteArrayIndex = 0;
4399   static const int kInlinedFunctionCountIndex = 1;
4400   static const int kLiteralArrayIndex = 2;
4401   static const int kOsrAstIdIndex = 3;
4402   static const int kOsrPcOffsetIndex = 4;
4403   static const int kOptimizationIdIndex = 5;
4404   static const int kSharedFunctionInfoIndex = 6;
4405   static const int kWeakCellCacheIndex = 7;
4406   static const int kFirstDeoptEntryIndex = 8;
4407
4408   // Offsets of deopt entry elements relative to the start of the entry.
4409   static const int kAstIdRawOffset = 0;
4410   static const int kTranslationIndexOffset = 1;
4411   static const int kArgumentsStackHeightOffset = 2;
4412   static const int kPcOffset = 3;
4413   static const int kDeoptEntrySize = 4;
4414
4415   // Simple element accessors.
4416 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4417   inline type* name();                        \
4418   inline void Set##name(type* value);
4419
4420   DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4421   DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4422   DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4423   DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4424   DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4425   DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4426   DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4427   DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4428
4429 #undef DECLARE_ELEMENT_ACCESSORS
4430
4431   // Accessors for elements of the ith deoptimization entry.
4432 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4433   inline type* name(int i);                 \
4434   inline void Set##name(int i, type* value);
4435
4436   DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4437   DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4438   DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4439   DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4440
4441 #undef DECLARE_ENTRY_ACCESSORS
4442
4443   inline BailoutId AstId(int i);
4444
4445   inline void SetAstId(int i, BailoutId value);
4446
4447   inline int DeoptCount();
4448
4449   // Allocates a DeoptimizationInputData.
4450   static Handle<DeoptimizationInputData> New(Isolate* isolate,
4451                                              int deopt_entry_count,
4452                                              PretenureFlag pretenure);
4453
4454   DECLARE_CAST(DeoptimizationInputData)
4455
4456 #ifdef ENABLE_DISASSEMBLER
4457   void DeoptimizationInputDataPrint(std::ostream& os);  // NOLINT
4458 #endif
4459
4460  private:
4461   static int IndexForEntry(int i) {
4462     return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4463   }
4464
4465
4466   static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4467 };
4468
4469
4470 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4471 // data for code generated by the full compiler.
4472 // The format of the these objects is
4473 //   [i * 2]: Ast ID for ith deoptimization.
4474 //   [i * 2 + 1]: PC and state of ith deoptimization
4475 class DeoptimizationOutputData: public FixedArray {
4476  public:
4477   inline int DeoptPoints();
4478
4479   inline BailoutId AstId(int index);
4480
4481   inline void SetAstId(int index, BailoutId id);
4482
4483   inline Smi* PcAndState(int index);
4484   inline void SetPcAndState(int index, Smi* offset);
4485
4486   static int LengthOfFixedArray(int deopt_points) {
4487     return deopt_points * 2;
4488   }
4489
4490   // Allocates a DeoptimizationOutputData.
4491   static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4492                                               int number_of_deopt_points,
4493                                               PretenureFlag pretenure);
4494
4495   DECLARE_CAST(DeoptimizationOutputData)
4496
4497 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4498   void DeoptimizationOutputDataPrint(std::ostream& os);  // NOLINT
4499 #endif
4500 };
4501
4502
4503 // HandlerTable is a fixed array containing entries for exception handlers in
4504 // the code object it is associated with. The tables comes in two flavors:
4505 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4506 //    exception handler and a range representing the try-block covered by that
4507 //    handler. Layout looks as follows:
4508 //      [ range-start , range-end , handler-offset , stack-depth ]
4509 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4510 //    per call-site that could throw an exception. Layout looks as follows:
4511 //      [ return-address-offset , handler-offset ]
4512 class HandlerTable : public FixedArray {
4513  public:
4514   // Conservative prediction whether a given handler will locally catch an
4515   // exception or cause a re-throw to outside the code boundary. Since this is
4516   // undecidable it is merely an approximation (e.g. useful for debugger).
4517   enum CatchPrediction { UNCAUGHT, CAUGHT };
4518
4519   // Accessors for handler table based on ranges.
4520   inline void SetRangeStart(int index, int value);
4521   inline void SetRangeEnd(int index, int value);
4522   inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4523   inline void SetRangeDepth(int index, int value);
4524
4525   // Accessors for handler table based on return addresses.
4526   inline void SetReturnOffset(int index, int value);
4527   inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4528
4529   // Lookup handler in a table based on ranges.
4530   int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4531
4532   // Lookup handler in a table based on return addresses.
4533   int LookupReturn(int pc_offset, CatchPrediction* prediction);
4534
4535   // Returns the required length of the underlying fixed array.
4536   static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4537   static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4538
4539   DECLARE_CAST(HandlerTable)
4540
4541 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4542   void HandlerTableRangePrint(std::ostream& os);   // NOLINT
4543   void HandlerTableReturnPrint(std::ostream& os);  // NOLINT
4544 #endif
4545
4546  private:
4547   // Layout description for handler table based on ranges.
4548   static const int kRangeStartIndex = 0;
4549   static const int kRangeEndIndex = 1;
4550   static const int kRangeHandlerIndex = 2;
4551   static const int kRangeDepthIndex = 3;
4552   static const int kRangeEntrySize = 4;
4553
4554   // Layout description for handler table based on return addresses.
4555   static const int kReturnOffsetIndex = 0;
4556   static const int kReturnHandlerIndex = 1;
4557   static const int kReturnEntrySize = 2;
4558
4559   // Encoding of the {handler} field.
4560   class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4561   class HandlerOffsetField : public BitField<int, 1, 30> {};
4562 };
4563
4564
4565 // Code describes objects with on-the-fly generated machine code.
4566 class Code: public HeapObject {
4567  public:
4568   // Opaque data type for encapsulating code flags like kind, inline
4569   // cache state, and arguments count.
4570   typedef uint32_t Flags;
4571
4572 #define NON_IC_KIND_LIST(V) \
4573   V(FUNCTION)               \
4574   V(OPTIMIZED_FUNCTION)     \
4575   V(STUB)                   \
4576   V(HANDLER)                \
4577   V(BUILTIN)                \
4578   V(REGEXP)                 \
4579   V(PLACEHOLDER)
4580
4581 #define IC_KIND_LIST(V) \
4582   V(LOAD_IC)            \
4583   V(KEYED_LOAD_IC)      \
4584   V(CALL_IC)            \
4585   V(STORE_IC)           \
4586   V(KEYED_STORE_IC)     \
4587   V(BINARY_OP_IC)       \
4588   V(COMPARE_IC)         \
4589   V(COMPARE_NIL_IC)     \
4590   V(TO_BOOLEAN_IC)
4591
4592 #define CODE_KIND_LIST(V) \
4593   NON_IC_KIND_LIST(V)     \
4594   IC_KIND_LIST(V)
4595
4596   enum Kind {
4597 #define DEFINE_CODE_KIND_ENUM(name) name,
4598     CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4599 #undef DEFINE_CODE_KIND_ENUM
4600     NUMBER_OF_KINDS
4601   };
4602
4603   // No more than 16 kinds. The value is currently encoded in four bits in
4604   // Flags.
4605   STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4606
4607   static const char* Kind2String(Kind kind);
4608
4609   // Types of stubs.
4610   enum StubType {
4611     NORMAL,
4612     FAST
4613   };
4614
4615   static const int kPrologueOffsetNotSet = -1;
4616
4617 #ifdef ENABLE_DISASSEMBLER
4618   // Printing
4619   static const char* ICState2String(InlineCacheState state);
4620   static const char* StubType2String(StubType type);
4621   static void PrintExtraICState(std::ostream& os,  // NOLINT
4622                                 Kind kind, ExtraICState extra);
4623   void Disassemble(const char* name, std::ostream& os);  // NOLINT
4624 #endif  // ENABLE_DISASSEMBLER
4625
4626   // [instruction_size]: Size of the native instructions
4627   inline int instruction_size() const;
4628   inline void set_instruction_size(int value);
4629
4630   // [relocation_info]: Code relocation information
4631   DECL_ACCESSORS(relocation_info, ByteArray)
4632   void InvalidateRelocation();
4633   void InvalidateEmbeddedObjects();
4634
4635   // [handler_table]: Fixed array containing offsets of exception handlers.
4636   DECL_ACCESSORS(handler_table, FixedArray)
4637
4638   // [deoptimization_data]: Array containing data for deopt.
4639   DECL_ACCESSORS(deoptimization_data, FixedArray)
4640
4641   // [raw_type_feedback_info]: This field stores various things, depending on
4642   // the kind of the code object.
4643   //   FUNCTION           => type feedback information.
4644   //   STUB and ICs       => major/minor key as Smi.
4645   DECL_ACCESSORS(raw_type_feedback_info, Object)
4646   inline Object* type_feedback_info();
4647   inline void set_type_feedback_info(
4648       Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4649   inline uint32_t stub_key();
4650   inline void set_stub_key(uint32_t key);
4651
4652   // [next_code_link]: Link for lists of optimized or deoptimized code.
4653   // Note that storage for this field is overlapped with typefeedback_info.
4654   DECL_ACCESSORS(next_code_link, Object)
4655
4656   // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4657   // field does not have to be traced during garbage collection since
4658   // it is only used by the garbage collector itself.
4659   DECL_ACCESSORS(gc_metadata, Object)
4660
4661   // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4662   // at the moment when this object was created.
4663   inline void set_ic_age(int count);
4664   inline int ic_age() const;
4665
4666   // [prologue_offset]: Offset of the function prologue, used for aging
4667   // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4668   inline int prologue_offset() const;
4669   inline void set_prologue_offset(int offset);
4670
4671   // [constant_pool offset]: Offset of the constant pool.
4672   // Valid for FLAG_enable_embedded_constant_pool only
4673   inline int constant_pool_offset() const;
4674   inline void set_constant_pool_offset(int offset);
4675
4676   // Unchecked accessors to be used during GC.
4677   inline ByteArray* unchecked_relocation_info();
4678
4679   inline int relocation_size();
4680
4681   // [flags]: Various code flags.
4682   inline Flags flags();
4683   inline void set_flags(Flags flags);
4684
4685   // [flags]: Access to specific code flags.
4686   inline Kind kind();
4687   inline InlineCacheState ic_state();  // Only valid for IC stubs.
4688   inline ExtraICState extra_ic_state();  // Only valid for IC stubs.
4689
4690   inline StubType type();  // Only valid for monomorphic IC stubs.
4691
4692   // Testers for IC stub kinds.
4693   inline bool is_inline_cache_stub();
4694   inline bool is_debug_stub();
4695   inline bool is_handler();
4696   inline bool is_load_stub();
4697   inline bool is_keyed_load_stub();
4698   inline bool is_store_stub();
4699   inline bool is_keyed_store_stub();
4700   inline bool is_call_stub();
4701   inline bool is_binary_op_stub();
4702   inline bool is_compare_ic_stub();
4703   inline bool is_compare_nil_ic_stub();
4704   inline bool is_to_boolean_ic_stub();
4705   inline bool is_keyed_stub();
4706   inline bool is_optimized_code();
4707   inline bool embeds_maps_weakly();
4708
4709   inline bool IsCodeStubOrIC();
4710   inline bool IsJavaScriptCode();
4711
4712   inline void set_raw_kind_specific_flags1(int value);
4713   inline void set_raw_kind_specific_flags2(int value);
4714
4715   // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4716   // object was generated by either the hydrogen or the TurboFan optimizing
4717   // compiler (but it may not be an optimized function).
4718   inline bool is_crankshafted();
4719   inline bool is_hydrogen_stub();  // Crankshafted, but not a function.
4720   inline void set_is_crankshafted(bool value);
4721
4722   // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4723   // code object was generated by the TurboFan optimizing compiler.
4724   inline bool is_turbofanned();
4725   inline void set_is_turbofanned(bool value);
4726
4727   // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4728   // embedded objects in code should be treated weakly.
4729   inline bool can_have_weak_objects();
4730   inline void set_can_have_weak_objects(bool value);
4731
4732   // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4733   // deoptimization support.
4734   inline bool has_deoptimization_support();
4735   inline void set_has_deoptimization_support(bool value);
4736
4737   // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4738   // been compiled with debug break slots.
4739   inline bool has_debug_break_slots();
4740   inline void set_has_debug_break_slots(bool value);
4741
4742   // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4743   // reloc info includes runtime and external references to support
4744   // serialization/deserialization.
4745   inline bool has_reloc_info_for_serialization();
4746   inline void set_has_reloc_info_for_serialization(bool value);
4747
4748   // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4749   // how long the function has been marked for OSR and therefore which
4750   // level of loop nesting we are willing to do on-stack replacement
4751   // for.
4752   inline void set_allow_osr_at_loop_nesting_level(int level);
4753   inline int allow_osr_at_loop_nesting_level();
4754
4755   // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4756   // the code object was seen on the stack with no IC patching going on.
4757   inline int profiler_ticks();
4758   inline void set_profiler_ticks(int ticks);
4759
4760   // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4761   // For builtins, tells which builtin index it has.
4762   // Note that builtins can have a code kind other than BUILTIN, which means
4763   // that for arbitrary code objects, this index value may be random garbage.
4764   // To verify in that case, compare the code object to the indexed builtin.
4765   inline int builtin_index();
4766   inline void set_builtin_index(int id);
4767
4768   // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4769   // reserved in the code prologue.
4770   inline unsigned stack_slots();
4771   inline void set_stack_slots(unsigned slots);
4772
4773   // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4774   // the instruction stream where the safepoint table starts.
4775   inline unsigned safepoint_table_offset();
4776   inline void set_safepoint_table_offset(unsigned offset);
4777
4778   // [back_edge_table_start]: For kind FUNCTION, the offset in the
4779   // instruction stream where the back edge table starts.
4780   inline unsigned back_edge_table_offset();
4781   inline void set_back_edge_table_offset(unsigned offset);
4782
4783   inline bool back_edges_patched_for_osr();
4784
4785   // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4786   inline uint16_t to_boolean_state();
4787
4788   // [has_function_cache]: For kind STUB tells whether there is a function
4789   // cache is passed to the stub.
4790   inline bool has_function_cache();
4791   inline void set_has_function_cache(bool flag);
4792
4793
4794   // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4795   // the code is going to be deoptimized because of dead embedded maps.
4796   inline bool marked_for_deoptimization();
4797   inline void set_marked_for_deoptimization(bool flag);
4798
4799   // [constant_pool]: The constant pool for this function.
4800   inline Address constant_pool();
4801
4802   // Get the safepoint entry for the given pc.
4803   SafepointEntry GetSafepointEntry(Address pc);
4804
4805   // Find an object in a stub with a specified map
4806   Object* FindNthObject(int n, Map* match_map);
4807
4808   // Find the first allocation site in an IC stub.
4809   AllocationSite* FindFirstAllocationSite();
4810
4811   // Find the first map in an IC stub.
4812   Map* FindFirstMap();
4813   void FindAllMaps(MapHandleList* maps);
4814
4815   // Find the first handler in an IC stub.
4816   Code* FindFirstHandler();
4817
4818   // Find |length| handlers and put them into |code_list|. Returns false if not
4819   // enough handlers can be found.
4820   bool FindHandlers(CodeHandleList* code_list, int length = -1);
4821
4822   // Find the handler for |map|.
4823   MaybeHandle<Code> FindHandlerForMap(Map* map);
4824
4825   // Find the first name in an IC stub.
4826   Name* FindFirstName();
4827
4828   class FindAndReplacePattern;
4829   // For each (map-to-find, object-to-replace) pair in the pattern, this
4830   // function replaces the corresponding placeholder in the code with the
4831   // object-to-replace. The function assumes that pairs in the pattern come in
4832   // the same order as the placeholders in the code.
4833   // If the placeholder is a weak cell, then the value of weak cell is matched
4834   // against the map-to-find.
4835   void FindAndReplace(const FindAndReplacePattern& pattern);
4836
4837   // The entire code object including its header is copied verbatim to the
4838   // snapshot so that it can be written in one, fast, memcpy during
4839   // deserialization. The deserializer will overwrite some pointers, rather
4840   // like a runtime linker, but the random allocation addresses used in the
4841   // mksnapshot process would still be present in the unlinked snapshot data,
4842   // which would make snapshot production non-reproducible. This method wipes
4843   // out the to-be-overwritten header data for reproducible snapshots.
4844   inline void WipeOutHeader();
4845
4846   // Flags operations.
4847   static inline Flags ComputeFlags(
4848       Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4849       ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4850       CacheHolderFlag holder = kCacheOnReceiver);
4851
4852   static inline Flags ComputeMonomorphicFlags(
4853       Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4854       CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4855
4856   static inline Flags ComputeHandlerFlags(
4857       Kind handler_kind, StubType type = NORMAL,
4858       CacheHolderFlag holder = kCacheOnReceiver);
4859
4860   static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4861   static inline StubType ExtractTypeFromFlags(Flags flags);
4862   static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4863   static inline Kind ExtractKindFromFlags(Flags flags);
4864   static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4865
4866   static inline Flags RemoveTypeFromFlags(Flags flags);
4867   static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4868
4869   // Convert a target address into a code object.
4870   static inline Code* GetCodeFromTargetAddress(Address address);
4871
4872   // Convert an entry address into an object.
4873   static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4874
4875   // Returns the address of the first instruction.
4876   inline byte* instruction_start();
4877
4878   // Returns the address right after the last instruction.
4879   inline byte* instruction_end();
4880
4881   // Returns the size of the instructions, padding, and relocation information.
4882   inline int body_size();
4883
4884   // Returns the address of the first relocation info (read backwards!).
4885   inline byte* relocation_start();
4886
4887   // Code entry point.
4888   inline byte* entry();
4889
4890   // Returns true if pc is inside this object's instructions.
4891   inline bool contains(byte* pc);
4892
4893   // Relocate the code by delta bytes. Called to signal that this code
4894   // object has been moved by delta bytes.
4895   void Relocate(intptr_t delta);
4896
4897   // Migrate code described by desc.
4898   void CopyFrom(const CodeDesc& desc);
4899
4900   // Returns the object size for a given body (used for allocation).
4901   static int SizeFor(int body_size) {
4902     DCHECK_SIZE_TAG_ALIGNED(body_size);
4903     return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4904   }
4905
4906   // Calculate the size of the code object to report for log events. This takes
4907   // the layout of the code object into account.
4908   inline int ExecutableSize();
4909
4910   // Locating source position.
4911   int SourcePosition(Address pc);
4912   int SourceStatementPosition(Address pc);
4913
4914   DECLARE_CAST(Code)
4915
4916   // Dispatched behavior.
4917   inline int CodeSize();
4918   inline void CodeIterateBody(ObjectVisitor* v);
4919
4920   template<typename StaticVisitor>
4921   inline void CodeIterateBody(Heap* heap);
4922
4923   DECLARE_PRINTER(Code)
4924   DECLARE_VERIFIER(Code)
4925
4926   void ClearInlineCaches();
4927   void ClearInlineCaches(Kind kind);
4928
4929   BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4930   uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4931
4932 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4933   enum Age {
4934     kToBeExecutedOnceCodeAge = -3,
4935     kNotExecutedCodeAge = -2,
4936     kExecutedOnceCodeAge = -1,
4937     kNoAgeCodeAge = 0,
4938     CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4939     kAfterLastCodeAge,
4940     kFirstCodeAge = kToBeExecutedOnceCodeAge,
4941     kLastCodeAge = kAfterLastCodeAge - 1,
4942     kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4943     kIsOldCodeAge = kSexagenarianCodeAge,
4944     kPreAgedCodeAge = kIsOldCodeAge - 1
4945   };
4946 #undef DECLARE_CODE_AGE_ENUM
4947
4948   // Code aging.  Indicates how many full GCs this code has survived without
4949   // being entered through the prologue.  Used to determine when it is
4950   // relatively safe to flush this code object and replace it with the lazy
4951   // compilation stub.
4952   static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4953   static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4954   void MakeYoung(Isolate* isolate);
4955   void MarkToBeExecutedOnce(Isolate* isolate);
4956   void MakeOlder(MarkingParity);
4957   static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4958   bool IsOld();
4959   Age GetAge();
4960   static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4961     return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4962   }
4963
4964   void PrintDeoptLocation(FILE* out, Address pc);
4965   bool CanDeoptAt(Address pc);
4966
4967 #ifdef VERIFY_HEAP
4968   void VerifyEmbeddedObjectsDependency();
4969 #endif
4970
4971 #ifdef DEBUG
4972   enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4973   void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4974   static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4975 #endif  // DEBUG
4976
4977   inline bool CanContainWeakObjects();
4978
4979   inline bool IsWeakObject(Object* object);
4980
4981   static inline bool IsWeakObjectInOptimizedCode(Object* object);
4982
4983   static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4984   WeakCell* CachedWeakCell();
4985
4986   // Max loop nesting marker used to postpose OSR. We don't take loop
4987   // nesting that is deeper than 5 levels into account.
4988   static const int kMaxLoopNestingMarker = 6;
4989
4990   static const int kConstantPoolSize =
4991       FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4992
4993   // Layout description.
4994   static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4995   static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4996   static const int kDeoptimizationDataOffset =
4997       kHandlerTableOffset + kPointerSize;
4998   // For FUNCTION kind, we store the type feedback info here.
4999   static const int kTypeFeedbackInfoOffset =
5000       kDeoptimizationDataOffset + kPointerSize;
5001   static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5002   static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5003   static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5004   static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5005   static const int kFlagsOffset = kICAgeOffset + kIntSize;
5006   static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5007   static const int kKindSpecificFlags2Offset =
5008       kKindSpecificFlags1Offset + kIntSize;
5009   // Note: We might be able to squeeze this into the flags above.
5010   static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5011   static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5012   static const int kHeaderPaddingStart =
5013       kConstantPoolOffset + kConstantPoolSize;
5014
5015   // Add padding to align the instruction start following right after
5016   // the Code object header.
5017   static const int kHeaderSize =
5018       (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5019
5020   // Byte offsets within kKindSpecificFlags1Offset.
5021   static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5022   class FullCodeFlagsHasDeoptimizationSupportField:
5023       public BitField<bool, 0, 1> {};  // NOLINT
5024   class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5025   class FullCodeFlagsHasRelocInfoForSerialization
5026       : public BitField<bool, 2, 1> {};
5027   // Bit 3 in this bitfield is unused.
5028   class ProfilerTicksField : public BitField<int, 4, 28> {};
5029
5030   // Flags layout.  BitField<type, shift, size>.
5031   class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5032   class TypeField : public BitField<StubType, 4, 1> {};
5033   class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5034   class KindField : public BitField<Kind, 7, 4> {};
5035   class ExtraICStateField: public BitField<ExtraICState, 11,
5036       PlatformSmiTagging::kSmiValueSize - 11 + 1> {};  // NOLINT
5037
5038   // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5039   static const int kStackSlotsFirstBit = 0;
5040   static const int kStackSlotsBitCount = 24;
5041   static const int kHasFunctionCacheBit =
5042       kStackSlotsFirstBit + kStackSlotsBitCount;
5043   static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5044   static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5045   static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5046
5047   STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5048   STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5049
5050   class StackSlotsField: public BitField<int,
5051       kStackSlotsFirstBit, kStackSlotsBitCount> {};  // NOLINT
5052   class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5053   };  // NOLINT
5054   class MarkedForDeoptimizationField
5055       : public BitField<bool, kMarkedForDeoptimizationBit, 1> {};   // NOLINT
5056   class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5057   };  // NOLINT
5058   class CanHaveWeakObjectsField
5059       : public BitField<bool, kCanHaveWeakObjects, 1> {};  // NOLINT
5060
5061   // KindSpecificFlags2 layout (ALL)
5062   static const int kIsCrankshaftedBit = 0;
5063   class IsCrankshaftedField: public BitField<bool,
5064       kIsCrankshaftedBit, 1> {};  // NOLINT
5065
5066   // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5067   static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5068   static const int kSafepointTableOffsetBitCount = 30;
5069
5070   STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5071                 kSafepointTableOffsetBitCount <= 32);
5072   STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5073
5074   class SafepointTableOffsetField: public BitField<int,
5075       kSafepointTableOffsetFirstBit,
5076       kSafepointTableOffsetBitCount> {};  // NOLINT
5077
5078   // KindSpecificFlags2 layout (FUNCTION)
5079   class BackEdgeTableOffsetField: public BitField<int,
5080       kIsCrankshaftedBit + 1, 27> {};  // NOLINT
5081   class AllowOSRAtLoopNestingLevelField: public BitField<int,
5082       kIsCrankshaftedBit + 1 + 27, 4> {};  // NOLINT
5083   STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5084
5085   static const int kArgumentsBits = 16;
5086   static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5087
5088   // This constant should be encodable in an ARM instruction.
5089   static const int kFlagsNotUsedInLookup =
5090       TypeField::kMask | CacheHolderField::kMask;
5091
5092  private:
5093   friend class RelocIterator;
5094   friend class Deoptimizer;  // For FindCodeAgeSequence.
5095
5096   void ClearInlineCaches(Kind* kind);
5097
5098   // Code aging
5099   byte* FindCodeAgeSequence();
5100   static void GetCodeAgeAndParity(Code* code, Age* age,
5101                                   MarkingParity* parity);
5102   static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5103                                   MarkingParity* parity);
5104   static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5105
5106   // Code aging -- platform-specific
5107   static void PatchPlatformCodeAge(Isolate* isolate,
5108                                    byte* sequence, Age age,
5109                                    MarkingParity parity);
5110
5111   DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5112 };
5113
5114
5115 // This class describes the layout of dependent codes array of a map. The
5116 // array is partitioned into several groups of dependent codes. Each group
5117 // contains codes with the same dependency on the map. The array has the
5118 // following layout for n dependency groups:
5119 //
5120 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5121 // | C1 | C2 | ... | Cn | group 1 |  group 2 | ... | group n | undefined |
5122 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5123 //
5124 // The first n elements are Smis, each of them specifies the number of codes
5125 // in the corresponding group. The subsequent elements contain grouped code
5126 // objects in weak cells. The suffix of the array can be filled with the
5127 // undefined value if the number of codes is less than the length of the
5128 // array. The order of the code objects within a group is not preserved.
5129 //
5130 // All code indexes used in the class are counted starting from the first
5131 // code object of the first group. In other words, code index 0 corresponds
5132 // to array index n = kCodesStartIndex.
5133
5134 class DependentCode: public FixedArray {
5135  public:
5136   enum DependencyGroup {
5137     // Group of code that weakly embed this map and depend on being
5138     // deoptimized when the map is garbage collected.
5139     kWeakCodeGroup,
5140     // Group of code that embed a transition to this map, and depend on being
5141     // deoptimized when the transition is replaced by a new version.
5142     kTransitionGroup,
5143     // Group of code that omit run-time prototype checks for prototypes
5144     // described by this map. The group is deoptimized whenever an object
5145     // described by this map changes shape (and transitions to a new map),
5146     // possibly invalidating the assumptions embedded in the code.
5147     kPrototypeCheckGroup,
5148     // Group of code that depends on global property values in property cells
5149     // not being changed.
5150     kPropertyCellChangedGroup,
5151     // Group of code that omit run-time type checks for the field(s) introduced
5152     // by this map.
5153     kFieldTypeGroup,
5154     // Group of code that omit run-time type checks for initial maps of
5155     // constructors.
5156     kInitialMapChangedGroup,
5157     // Group of code that depends on tenuring information in AllocationSites
5158     // not being changed.
5159     kAllocationSiteTenuringChangedGroup,
5160     // Group of code that depends on element transition information in
5161     // AllocationSites not being changed.
5162     kAllocationSiteTransitionChangedGroup
5163   };
5164
5165   static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5166
5167   // Array for holding the index of the first code object of each group.
5168   // The last element stores the total number of code objects.
5169   class GroupStartIndexes {
5170    public:
5171     explicit GroupStartIndexes(DependentCode* entries);
5172     void Recompute(DependentCode* entries);
5173     int at(int i) { return start_indexes_[i]; }
5174     int number_of_entries() { return start_indexes_[kGroupCount]; }
5175    private:
5176     int start_indexes_[kGroupCount + 1];
5177   };
5178
5179   bool Contains(DependencyGroup group, WeakCell* code_cell);
5180
5181   static Handle<DependentCode> InsertCompilationDependencies(
5182       Handle<DependentCode> entries, DependencyGroup group,
5183       Handle<Foreign> info);
5184
5185   static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5186                                               DependencyGroup group,
5187                                               Handle<WeakCell> code_cell);
5188
5189   void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5190                             WeakCell* code_cell);
5191
5192   void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5193                                      Foreign* info);
5194
5195   void DeoptimizeDependentCodeGroup(Isolate* isolate,
5196                                     DependentCode::DependencyGroup group);
5197
5198   bool MarkCodeForDeoptimization(Isolate* isolate,
5199                                  DependentCode::DependencyGroup group);
5200
5201   // The following low-level accessors should only be used by this class
5202   // and the mark compact collector.
5203   inline int number_of_entries(DependencyGroup group);
5204   inline void set_number_of_entries(DependencyGroup group, int value);
5205   inline Object* object_at(int i);
5206   inline void set_object_at(int i, Object* object);
5207   inline void clear_at(int i);
5208   inline void copy(int from, int to);
5209   DECLARE_CAST(DependentCode)
5210
5211   static const char* DependencyGroupName(DependencyGroup group);
5212   static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5213
5214  private:
5215   static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5216                                       DependencyGroup group,
5217                                       Handle<Object> object);
5218   static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5219   // Make a room at the end of the given group by moving out the first
5220   // code objects of the subsequent groups.
5221   inline void ExtendGroup(DependencyGroup group);
5222   // Compact by removing cleared weak cells and return true if there was
5223   // any cleared weak cell.
5224   bool Compact();
5225   static int Grow(int number_of_entries) {
5226     if (number_of_entries < 5) return number_of_entries + 1;
5227     return number_of_entries * 5 / 4;
5228   }
5229   static const int kCodesStartIndex = kGroupCount;
5230 };
5231
5232
5233 class PrototypeInfo;
5234
5235
5236 // All heap objects have a Map that describes their structure.
5237 //  A Map contains information about:
5238 //  - Size information about the object
5239 //  - How to iterate over an object (for garbage collection)
5240 class Map: public HeapObject {
5241  public:
5242   // Instance size.
5243   // Size in bytes or kVariableSizeSentinel if instances do not have
5244   // a fixed size.
5245   inline int instance_size();
5246   inline void set_instance_size(int value);
5247
5248   // Only to clear an unused byte, remove once byte is used.
5249   inline void clear_unused();
5250
5251   // [inobject_properties_or_constructor_function_index]: Provides access
5252   // to the inobject properties in case of JSObject maps, or the constructor
5253   // function index in case of primitive maps.
5254   inline int inobject_properties_or_constructor_function_index();
5255   inline void set_inobject_properties_or_constructor_function_index(int value);
5256   // Count of properties allocated in the object (JSObject only).
5257   inline int GetInObjectProperties();
5258   inline void SetInObjectProperties(int value);
5259   // Index of the constructor function in the native context (primitives only),
5260   // or the special sentinel value to indicate that there is no object wrapper
5261   // for the primitive (i.e. in case of null or undefined).
5262   static const int kNoConstructorFunctionIndex = 0;
5263   inline int GetConstructorFunctionIndex();
5264   inline void SetConstructorFunctionIndex(int value);
5265
5266   // Instance type.
5267   inline InstanceType instance_type();
5268   inline void set_instance_type(InstanceType value);
5269
5270   // Tells how many unused property fields are available in the
5271   // instance (only used for JSObject in fast mode).
5272   inline int unused_property_fields();
5273   inline void set_unused_property_fields(int value);
5274
5275   // Bit field.
5276   inline byte bit_field() const;
5277   inline void set_bit_field(byte value);
5278
5279   // Bit field 2.
5280   inline byte bit_field2() const;
5281   inline void set_bit_field2(byte value);
5282
5283   // Bit field 3.
5284   inline uint32_t bit_field3() const;
5285   inline void set_bit_field3(uint32_t bits);
5286
5287   class EnumLengthBits:             public BitField<int,
5288       0, kDescriptorIndexBitCount> {};  // NOLINT
5289   class NumberOfOwnDescriptorsBits: public BitField<int,
5290       kDescriptorIndexBitCount, kDescriptorIndexBitCount> {};  // NOLINT
5291   STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5292   class DictionaryMap : public BitField<bool, 20, 1> {};
5293   class OwnsDescriptors : public BitField<bool, 21, 1> {};
5294   class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5295   class Deprecated : public BitField<bool, 23, 1> {};
5296   class IsUnstable : public BitField<bool, 24, 1> {};
5297   class IsMigrationTarget : public BitField<bool, 25, 1> {};
5298   class IsStrong : public BitField<bool, 26, 1> {};
5299   // Bit 27 is free.
5300
5301   // Keep this bit field at the very end for better code in
5302   // Builtins::kJSConstructStubGeneric stub.
5303   // This counter is used for in-object slack tracking and for map aging.
5304   // The in-object slack tracking is considered enabled when the counter is
5305   // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5306   class Counter : public BitField<int, 28, 4> {};
5307   static const int kSlackTrackingCounterStart = 14;
5308   static const int kSlackTrackingCounterEnd = 8;
5309   static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5310   static const int kRetainingCounterEnd = 0;
5311
5312   // Tells whether the object in the prototype property will be used
5313   // for instances created from this function.  If the prototype
5314   // property is set to a value that is not a JSObject, the prototype
5315   // property will not be used to create instances of the function.
5316   // See ECMA-262, 13.2.2.
5317   inline void set_non_instance_prototype(bool value);
5318   inline bool has_non_instance_prototype();
5319
5320   // Tells whether function has special prototype property. If not, prototype
5321   // property will not be created when accessed (will return undefined),
5322   // and construction from this function will not be allowed.
5323   inline void set_function_with_prototype(bool value);
5324   inline bool function_with_prototype();
5325
5326   // Tells whether the instance with this map should be ignored by the
5327   // Object.getPrototypeOf() function and the __proto__ accessor.
5328   inline void set_is_hidden_prototype();
5329   inline bool is_hidden_prototype() const;
5330
5331   // Records and queries whether the instance has a named interceptor.
5332   inline void set_has_named_interceptor();
5333   inline bool has_named_interceptor();
5334
5335   // Records and queries whether the instance has an indexed interceptor.
5336   inline void set_has_indexed_interceptor();
5337   inline bool has_indexed_interceptor();
5338
5339   // Tells whether the instance is undetectable.
5340   // An undetectable object is a special class of JSObject: 'typeof' operator
5341   // returns undefined, ToBoolean returns false. Otherwise it behaves like
5342   // a normal JS object.  It is useful for implementing undetectable
5343   // document.all in Firefox & Safari.
5344   // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5345   inline void set_is_undetectable();
5346   inline bool is_undetectable();
5347
5348   // Tells whether the instance has a call-as-function handler.
5349   inline void set_is_observed();
5350   inline bool is_observed();
5351
5352   // Tells whether the instance has a [[Call]] internal field.
5353   // This property is implemented according to ES6, section 7.2.3.
5354   inline void set_is_callable();
5355   inline bool is_callable() const;
5356
5357   inline void set_is_strong();
5358   inline bool is_strong();
5359   inline void set_is_extensible(bool value);
5360   inline bool is_extensible();
5361   inline void set_is_prototype_map(bool value);
5362   inline bool is_prototype_map() const;
5363
5364   inline void set_elements_kind(ElementsKind elements_kind);
5365   inline ElementsKind elements_kind();
5366
5367   // Tells whether the instance has fast elements that are only Smis.
5368   inline bool has_fast_smi_elements();
5369
5370   // Tells whether the instance has fast elements.
5371   inline bool has_fast_object_elements();
5372   inline bool has_fast_smi_or_object_elements();
5373   inline bool has_fast_double_elements();
5374   inline bool has_fast_elements();
5375   inline bool has_sloppy_arguments_elements();
5376   inline bool has_fixed_typed_array_elements();
5377   inline bool has_dictionary_elements();
5378
5379   static bool IsValidElementsTransition(ElementsKind from_kind,
5380                                         ElementsKind to_kind);
5381
5382   // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5383   // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5384   bool DictionaryElementsInPrototypeChainOnly();
5385
5386   inline Map* ElementsTransitionMap();
5387
5388   inline FixedArrayBase* GetInitialElements();
5389
5390   // [raw_transitions]: Provides access to the transitions storage field.
5391   // Don't call set_raw_transitions() directly to overwrite transitions, use
5392   // the TransitionArray::ReplaceTransitions() wrapper instead!
5393   DECL_ACCESSORS(raw_transitions, Object)
5394   // [prototype_info]: Per-prototype metadata. Aliased with transitions
5395   // (which prototype maps don't have).
5396   DECL_ACCESSORS(prototype_info, Object)
5397   // PrototypeInfo is created lazily using this helper (which installs it on
5398   // the given prototype's map).
5399   static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5400       Handle<JSObject> prototype, Isolate* isolate);
5401   static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5402       Handle<Map> prototype_map, Isolate* isolate);
5403
5404   // [prototype chain validity cell]: Associated with a prototype object,
5405   // stored in that object's map's PrototypeInfo, indicates that prototype
5406   // chains through this object are currently valid. The cell will be
5407   // invalidated and replaced when the prototype chain changes.
5408   static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5409                                                             Isolate* isolate);
5410   static const int kPrototypeChainValid = 0;
5411   static const int kPrototypeChainInvalid = 1;
5412
5413   Map* FindRootMap();
5414   Map* FindFieldOwner(int descriptor);
5415
5416   inline int GetInObjectPropertyOffset(int index);
5417
5418   int NumberOfFields();
5419
5420   // TODO(ishell): candidate with JSObject::MigrateToMap().
5421   bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5422                               int target_inobject, int target_unused,
5423                               int* old_number_of_fields);
5424   // TODO(ishell): moveit!
5425   static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5426   MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5427       Handle<HeapType> type1,
5428       Handle<HeapType> type2,
5429       Isolate* isolate);
5430   static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5431                                   Representation new_representation,
5432                                   Handle<HeapType> new_field_type);
5433   static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5434                                          PropertyKind new_kind,
5435                                          PropertyAttributes new_attributes,
5436                                          Representation new_representation,
5437                                          Handle<HeapType> new_field_type,
5438                                          StoreMode store_mode);
5439   static Handle<Map> CopyGeneralizeAllRepresentations(
5440       Handle<Map> map, int modify_index, StoreMode store_mode,
5441       PropertyKind kind, PropertyAttributes attributes, const char* reason);
5442
5443   static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5444                                             int descriptor_number,
5445                                             Handle<Object> value);
5446
5447   static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5448                                const char* reason);
5449
5450   // Returns the constructor name (the name (possibly, inferred name) of the
5451   // function that was used to instantiate the object).
5452   String* constructor_name();
5453
5454   // Tells whether the map is used for JSObjects in dictionary mode (ie
5455   // normalized objects, ie objects for which HasFastProperties returns false).
5456   // A map can never be used for both dictionary mode and fast mode JSObjects.
5457   // False by default and for HeapObjects that are not JSObjects.
5458   inline void set_dictionary_map(bool value);
5459   inline bool is_dictionary_map();
5460
5461   // Tells whether the instance needs security checks when accessing its
5462   // properties.
5463   inline void set_is_access_check_needed(bool access_check_needed);
5464   inline bool is_access_check_needed();
5465
5466   // Returns true if map has a non-empty stub code cache.
5467   inline bool has_code_cache();
5468
5469   // [prototype]: implicit prototype object.
5470   DECL_ACCESSORS(prototype, Object)
5471   // TODO(jkummerow): make set_prototype private.
5472   static void SetPrototype(
5473       Handle<Map> map, Handle<Object> prototype,
5474       PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5475
5476   // [constructor]: points back to the function responsible for this map.
5477   // The field overlaps with the back pointer. All maps in a transition tree
5478   // have the same constructor, so maps with back pointers can walk the
5479   // back pointer chain until they find the map holding their constructor.
5480   DECL_ACCESSORS(constructor_or_backpointer, Object)
5481   inline Object* GetConstructor() const;
5482   inline void SetConstructor(Object* constructor,
5483                              WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5484   // [back pointer]: points back to the parent map from which a transition
5485   // leads to this map. The field overlaps with the constructor (see above).
5486   inline Object* GetBackPointer();
5487   inline void SetBackPointer(Object* value,
5488                              WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5489
5490   // [instance descriptors]: describes the object.
5491   DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5492
5493   // [layout descriptor]: describes the object layout.
5494   DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5495   // |layout descriptor| accessor which can be used from GC.
5496   inline LayoutDescriptor* layout_descriptor_gc_safe();
5497   inline bool HasFastPointerLayout() const;
5498
5499   // |layout descriptor| accessor that is safe to call even when
5500   // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5501   // |layout_descriptor| field at all).
5502   inline LayoutDescriptor* GetLayoutDescriptor();
5503
5504   inline void UpdateDescriptors(DescriptorArray* descriptors,
5505                                 LayoutDescriptor* layout_descriptor);
5506   inline void InitializeDescriptors(DescriptorArray* descriptors,
5507                                     LayoutDescriptor* layout_descriptor);
5508
5509   // [stub cache]: contains stubs compiled for this map.
5510   DECL_ACCESSORS(code_cache, Object)
5511
5512   // [dependent code]: list of optimized codes that weakly embed this map.
5513   DECL_ACCESSORS(dependent_code, DependentCode)
5514
5515   // [weak cell cache]: cache that stores a weak cell pointing to this map.
5516   DECL_ACCESSORS(weak_cell_cache, Object)
5517
5518   inline PropertyDetails GetLastDescriptorDetails();
5519
5520   inline int LastAdded();
5521
5522   inline int NumberOfOwnDescriptors();
5523   inline void SetNumberOfOwnDescriptors(int number);
5524
5525   inline Cell* RetrieveDescriptorsPointer();
5526
5527   inline int EnumLength();
5528   inline void SetEnumLength(int length);
5529
5530   inline bool owns_descriptors();
5531   inline void set_owns_descriptors(bool owns_descriptors);
5532   inline void mark_unstable();
5533   inline bool is_stable();
5534   inline void set_migration_target(bool value);
5535   inline bool is_migration_target();
5536   inline void set_counter(int value);
5537   inline int counter();
5538   inline void deprecate();
5539   inline bool is_deprecated();
5540   inline bool CanBeDeprecated();
5541   // Returns a non-deprecated version of the input. If the input was not
5542   // deprecated, it is directly returned. Otherwise, the non-deprecated version
5543   // is found by re-transitioning from the root of the transition tree using the
5544   // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5545   // is found.
5546   static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5547
5548   // Returns a non-deprecated version of the input. This method may deprecate
5549   // existing maps along the way if encodings conflict. Not for use while
5550   // gathering type feedback. Use TryUpdate in those cases instead.
5551   static Handle<Map> Update(Handle<Map> map);
5552
5553   static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5554   static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5555                                           Descriptor* descriptor,
5556                                           TransitionFlag flag);
5557
5558   MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5559       Handle<Map> map,
5560       Handle<Name> name,
5561       Handle<HeapType> type,
5562       PropertyAttributes attributes,
5563       Representation representation,
5564       TransitionFlag flag);
5565
5566   MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5567       Handle<Map> map,
5568       Handle<Name> name,
5569       Handle<Object> constant,
5570       PropertyAttributes attributes,
5571       TransitionFlag flag);
5572
5573   // Returns a new map with all transitions dropped from the given map and
5574   // the ElementsKind set.
5575   static Handle<Map> TransitionElementsTo(Handle<Map> map,
5576                                           ElementsKind to_kind);
5577
5578   static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5579
5580   static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5581                                         ElementsKind kind,
5582                                         TransitionFlag flag);
5583
5584   static Handle<Map> CopyForObserved(Handle<Map> map);
5585
5586   static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5587                                               PropertyAttributes attrs_to_add,
5588                                               Handle<Symbol> transition_marker,
5589                                               const char* reason);
5590
5591   static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5592
5593
5594   // Maximal number of fast properties. Used to restrict the number of map
5595   // transitions to avoid an explosion in the number of maps for objects used as
5596   // dictionaries.
5597   inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5598   static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5599                                               Handle<Name> name,
5600                                               Handle<Object> value,
5601                                               PropertyAttributes attributes,
5602                                               StoreFromKeyed store_mode);
5603   static Handle<Map> TransitionToAccessorProperty(
5604       Handle<Map> map, Handle<Name> name, AccessorComponent component,
5605       Handle<Object> accessor, PropertyAttributes attributes);
5606   static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5607                                                  int descriptor,
5608                                                  PropertyKind kind,
5609                                                  PropertyAttributes attributes);
5610
5611   inline void AppendDescriptor(Descriptor* desc);
5612
5613   // Returns a copy of the map, prepared for inserting into the transition
5614   // tree (if the |map| owns descriptors then the new one will share
5615   // descriptors with |map|).
5616   static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5617
5618   // Returns a copy of the map, with all transitions dropped from the
5619   // instance descriptors.
5620   static Handle<Map> Copy(Handle<Map> map, const char* reason);
5621   static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5622
5623   // Returns the next free property index (only valid for FAST MODE).
5624   int NextFreePropertyIndex();
5625
5626   // Returns the number of properties described in instance_descriptors
5627   // filtering out properties with the specified attributes.
5628   int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5629                                   PropertyAttributes filter = NONE);
5630
5631   DECLARE_CAST(Map)
5632
5633   // Code cache operations.
5634
5635   // Clears the code cache.
5636   inline void ClearCodeCache(Heap* heap);
5637
5638   // Update code cache.
5639   static void UpdateCodeCache(Handle<Map> map,
5640                               Handle<Name> name,
5641                               Handle<Code> code);
5642
5643   // Extend the descriptor array of the map with the list of descriptors.
5644   // In case of duplicates, the latest descriptor is used.
5645   static void AppendCallbackDescriptors(Handle<Map> map,
5646                                         Handle<Object> descriptors);
5647
5648   static inline int SlackForArraySize(int old_size, int size_limit);
5649
5650   static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5651
5652   // Returns the found code or undefined if absent.
5653   Object* FindInCodeCache(Name* name, Code::Flags flags);
5654
5655   // Returns the non-negative index of the code object if it is in the
5656   // cache and -1 otherwise.
5657   int IndexInCodeCache(Object* name, Code* code);
5658
5659   // Removes a code object from the code cache at the given index.
5660   void RemoveFromCodeCache(Name* name, Code* code, int index);
5661
5662   // Computes a hash value for this map, to be used in HashTables and such.
5663   int Hash();
5664
5665   // Returns the map that this map transitions to if its elements_kind
5666   // is changed to |elements_kind|, or NULL if no such map is cached yet.
5667   // |safe_to_add_transitions| is set to false if adding transitions is not
5668   // allowed.
5669   Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5670
5671   // Returns the transitioned map for this map with the most generic
5672   // elements_kind that's found in |candidates|, or null handle if no match is
5673   // found at all.
5674   static Handle<Map> FindTransitionedMap(Handle<Map> map,
5675                                          MapHandleList* candidates);
5676
5677   inline bool CanTransition();
5678
5679   inline bool IsPrimitiveMap();
5680   inline bool IsJSObjectMap();
5681   inline bool IsJSArrayMap();
5682   inline bool IsStringMap();
5683   inline bool IsJSProxyMap();
5684   inline bool IsJSGlobalProxyMap();
5685   inline bool IsJSGlobalObjectMap();
5686   inline bool IsGlobalObjectMap();
5687
5688   inline bool CanOmitMapChecks();
5689
5690   static void AddDependentCode(Handle<Map> map,
5691                                DependentCode::DependencyGroup group,
5692                                Handle<Code> code);
5693
5694   bool IsMapInArrayPrototypeChain();
5695
5696   static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5697
5698   // Dispatched behavior.
5699   DECLARE_PRINTER(Map)
5700   DECLARE_VERIFIER(Map)
5701
5702 #ifdef VERIFY_HEAP
5703   void DictionaryMapVerify();
5704   void VerifyOmittedMapChecks();
5705 #endif
5706
5707   inline int visitor_id();
5708   inline void set_visitor_id(int visitor_id);
5709
5710   static Handle<Map> TransitionToPrototype(Handle<Map> map,
5711                                            Handle<Object> prototype,
5712                                            PrototypeOptimizationMode mode);
5713
5714   static const int kMaxPreAllocatedPropertyFields = 255;
5715
5716   // Layout description.
5717   static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5718   static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5719   static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5720   static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5721   static const int kConstructorOrBackPointerOffset =
5722       kPrototypeOffset + kPointerSize;
5723   // When there is only one transition, it is stored directly in this field;
5724   // otherwise a transition array is used.
5725   // For prototype maps, this slot is used to store this map's PrototypeInfo
5726   // struct.
5727   static const int kTransitionsOrPrototypeInfoOffset =
5728       kConstructorOrBackPointerOffset + kPointerSize;
5729   static const int kDescriptorsOffset =
5730       kTransitionsOrPrototypeInfoOffset + kPointerSize;
5731 #if V8_DOUBLE_FIELDS_UNBOXING
5732   static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5733   static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5734 #else
5735   static const int kLayoutDecriptorOffset = 1;  // Must not be ever accessed.
5736   static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5737 #endif
5738   static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5739   static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5740   static const int kSize = kWeakCellCacheOffset + kPointerSize;
5741
5742   // Layout of pointer fields. Heap iteration code relies on them
5743   // being continuously allocated.
5744   static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5745   static const int kPointerFieldsEndOffset = kSize;
5746
5747   // Byte offsets within kInstanceSizesOffset.
5748   static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5749   static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5750   static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5751       kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5752   // Note there is one byte available for use here.
5753   static const int kUnusedByte = 2;
5754   static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5755   static const int kVisitorIdByte = 3;
5756   static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5757
5758   // Byte offsets within kInstanceAttributesOffset attributes.
5759 #if V8_TARGET_LITTLE_ENDIAN
5760   // Order instance type and bit field together such that they can be loaded
5761   // together as a 16-bit word with instance type in the lower 8 bits regardless
5762   // of endianess. Also provide endian-independent offset to that 16-bit word.
5763   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5764   static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5765 #else
5766   static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5767   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5768 #endif
5769   static const int kInstanceTypeAndBitFieldOffset =
5770       kInstanceAttributesOffset + 0;
5771   static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5772   static const int kUnusedPropertyFieldsByte = 3;
5773   static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5774
5775   STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5776                 Internals::kMapInstanceTypeAndBitFieldOffset);
5777
5778   // Bit positions for bit field.
5779   static const int kHasNonInstancePrototype = 0;
5780   static const int kIsCallable = 1;
5781   static const int kHasNamedInterceptor = 2;
5782   static const int kHasIndexedInterceptor = 3;
5783   static const int kIsUndetectable = 4;
5784   static const int kIsObserved = 5;
5785   static const int kIsAccessCheckNeeded = 6;
5786   class FunctionWithPrototype: public BitField<bool, 7,  1> {};
5787
5788   // Bit positions for bit field 2
5789   static const int kIsExtensible = 0;
5790   static const int kStringWrapperSafeForDefaultValueOf = 1;
5791   class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5792   class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5793
5794   // Derived values from bit field 2
5795   static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5796       (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5797   static const int8_t kMaximumBitField2FastSmiElementValue =
5798       static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5799                           Map::ElementsKindBits::kShift) - 1;
5800   static const int8_t kMaximumBitField2FastHoleyElementValue =
5801       static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5802                           Map::ElementsKindBits::kShift) - 1;
5803   static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5804       static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5805                           Map::ElementsKindBits::kShift) - 1;
5806
5807   typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5808                               kPointerFieldsEndOffset,
5809                               kSize> BodyDescriptor;
5810
5811   // Compares this map to another to see if they describe equivalent objects.
5812   // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5813   // it had exactly zero inobject properties.
5814   // The "shared" flags of both this map and |other| are ignored.
5815   bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5816
5817   // Returns true if given field is unboxed double.
5818   inline bool IsUnboxedDoubleField(FieldIndex index);
5819
5820 #if TRACE_MAPS
5821   static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5822   static void TraceAllTransitions(Map* map);
5823 #endif
5824
5825   static inline Handle<Map> CopyInstallDescriptorsForTesting(
5826       Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5827       Handle<LayoutDescriptor> layout_descriptor);
5828
5829  private:
5830   static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5831                                 Handle<Name> name, SimpleTransitionFlag flag);
5832
5833   bool EquivalentToForTransition(Map* other);
5834   static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5835   static Handle<Map> ShareDescriptor(Handle<Map> map,
5836                                      Handle<DescriptorArray> descriptors,
5837                                      Descriptor* descriptor);
5838   static Handle<Map> CopyInstallDescriptors(
5839       Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5840       Handle<LayoutDescriptor> layout_descriptor);
5841   static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5842                                        Descriptor* descriptor,
5843                                        TransitionFlag flag);
5844   static Handle<Map> CopyReplaceDescriptors(
5845       Handle<Map> map, Handle<DescriptorArray> descriptors,
5846       Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5847       MaybeHandle<Name> maybe_name, const char* reason,
5848       SimpleTransitionFlag simple_flag);
5849
5850   static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5851                                            Handle<DescriptorArray> descriptors,
5852                                            Descriptor* descriptor,
5853                                            int index,
5854                                            TransitionFlag flag);
5855   static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5856       Handle<Map> map, int descriptor, PropertyKind kind,
5857       PropertyAttributes attributes, const char** reason);
5858
5859   static Handle<Map> CopyNormalized(Handle<Map> map,
5860                                     PropertyNormalizationMode mode);
5861
5862   // Fires when the layout of an object with a leaf map changes.
5863   // This includes adding transitions to the leaf map or changing
5864   // the descriptor array.
5865   inline void NotifyLeafMapLayoutChange();
5866
5867   void DeprecateTransitionTree();
5868   bool DeprecateTarget(PropertyKind kind, Name* key,
5869                        PropertyAttributes attributes,
5870                        DescriptorArray* new_descriptors,
5871                        LayoutDescriptor* new_layout_descriptor);
5872
5873   Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5874
5875   // Update field type of the given descriptor to new representation and new
5876   // type. The type must be prepared for storing in descriptor array:
5877   // it must be either a simple type or a map wrapped in a weak cell.
5878   void UpdateFieldType(int descriptor_number, Handle<Name> name,
5879                        Representation new_representation,
5880                        Handle<Object> new_wrapped_type);
5881
5882   void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5883                             PropertyAttributes attributes);
5884   void PrintGeneralization(FILE* file,
5885                            const char* reason,
5886                            int modify_index,
5887                            int split,
5888                            int descriptors,
5889                            bool constant_to_field,
5890                            Representation old_representation,
5891                            Representation new_representation,
5892                            HeapType* old_field_type,
5893                            HeapType* new_field_type);
5894
5895   static const int kFastPropertiesSoftLimit = 12;
5896   static const int kMaxFastProperties = 128;
5897
5898   DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5899 };
5900
5901
5902 // An abstract superclass, a marker class really, for simple structure classes.
5903 // It doesn't carry much functionality but allows struct classes to be
5904 // identified in the type system.
5905 class Struct: public HeapObject {
5906  public:
5907   inline void InitializeBody(int object_size);
5908   DECLARE_CAST(Struct)
5909 };
5910
5911
5912 // A simple one-element struct, useful where smis need to be boxed.
5913 class Box : public Struct {
5914  public:
5915   // [value]: the boxed contents.
5916   DECL_ACCESSORS(value, Object)
5917
5918   DECLARE_CAST(Box)
5919
5920   // Dispatched behavior.
5921   DECLARE_PRINTER(Box)
5922   DECLARE_VERIFIER(Box)
5923
5924   static const int kValueOffset = HeapObject::kHeaderSize;
5925   static const int kSize = kValueOffset + kPointerSize;
5926
5927  private:
5928   DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5929 };
5930
5931
5932 // Container for metadata stored on each prototype map.
5933 class PrototypeInfo : public Struct {
5934  public:
5935   static const int UNREGISTERED = -1;
5936
5937   // [prototype_users]: WeakFixedArray containing maps using this prototype,
5938   // or Smi(0) if uninitialized.
5939   DECL_ACCESSORS(prototype_users, Object)
5940   // [registry_slot]: Slot in prototype's user registry where this user
5941   // is stored. Returns UNREGISTERED if this prototype has not been registered.
5942   inline int registry_slot() const;
5943   inline void set_registry_slot(int slot);
5944   // [validity_cell]: Cell containing the validity bit for prototype chains
5945   // going through this object, or Smi(0) if uninitialized.
5946   DECL_ACCESSORS(validity_cell, Object)
5947   // [constructor_name]: User-friendly name of the original constructor.
5948   DECL_ACCESSORS(constructor_name, Object)
5949
5950   DECLARE_CAST(PrototypeInfo)
5951
5952   // Dispatched behavior.
5953   DECLARE_PRINTER(PrototypeInfo)
5954   DECLARE_VERIFIER(PrototypeInfo)
5955
5956   static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5957   static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5958   static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5959   static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5960   static const int kSize = kConstructorNameOffset + kPointerSize;
5961
5962  private:
5963   DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5964 };
5965
5966
5967 // Pair used to store both a ScopeInfo and an extension object in the extension
5968 // slot of a block context. Needed in the rare case where a declaration block
5969 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5970 // a sloppy direct eval. (In no other case both are needed at the same time.)
5971 class SloppyBlockWithEvalContextExtension : public Struct {
5972  public:
5973   // [scope_info]: Scope info.
5974   DECL_ACCESSORS(scope_info, ScopeInfo)
5975   // [extension]: Extension object.
5976   DECL_ACCESSORS(extension, JSObject)
5977
5978   DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5979
5980   // Dispatched behavior.
5981   DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5982   DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5983
5984   static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5985   static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5986   static const int kSize = kExtensionOffset + kPointerSize;
5987
5988  private:
5989   DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5990 };
5991
5992
5993 // Script describes a script which has been added to the VM.
5994 class Script: public Struct {
5995  public:
5996   // Script types.
5997   enum Type {
5998     TYPE_NATIVE = 0,
5999     TYPE_EXTENSION = 1,
6000     TYPE_NORMAL = 2
6001   };
6002
6003   // Script compilation types.
6004   enum CompilationType {
6005     COMPILATION_TYPE_HOST = 0,
6006     COMPILATION_TYPE_EVAL = 1
6007   };
6008
6009   // Script compilation state.
6010   enum CompilationState {
6011     COMPILATION_STATE_INITIAL = 0,
6012     COMPILATION_STATE_COMPILED = 1
6013   };
6014
6015   // [source]: the script source.
6016   DECL_ACCESSORS(source, Object)
6017
6018   // [name]: the script name.
6019   DECL_ACCESSORS(name, Object)
6020
6021   // [id]: the script id.
6022   DECL_ACCESSORS(id, Smi)
6023
6024   // [line_offset]: script line offset in resource from where it was extracted.
6025   DECL_ACCESSORS(line_offset, Smi)
6026
6027   // [column_offset]: script column offset in resource from where it was
6028   // extracted.
6029   DECL_ACCESSORS(column_offset, Smi)
6030
6031   // [context_data]: context data for the context this script was compiled in.
6032   DECL_ACCESSORS(context_data, Object)
6033
6034   // [wrapper]: the wrapper cache.  This is either undefined or a WeakCell.
6035   DECL_ACCESSORS(wrapper, HeapObject)
6036
6037   // [type]: the script type.
6038   DECL_ACCESSORS(type, Smi)
6039
6040   // [line_ends]: FixedArray of line ends positions.
6041   DECL_ACCESSORS(line_ends, Object)
6042
6043   // [eval_from_shared]: for eval scripts the shared funcion info for the
6044   // function from which eval was called.
6045   DECL_ACCESSORS(eval_from_shared, Object)
6046
6047   // [eval_from_instructions_offset]: the instruction offset in the code for the
6048   // function from which eval was called where eval was called.
6049   DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6050
6051   // [shared_function_infos]: weak fixed array containing all shared
6052   // function infos created from this script.
6053   DECL_ACCESSORS(shared_function_infos, Object)
6054
6055   // [flags]: Holds an exciting bitfield.
6056   DECL_ACCESSORS(flags, Smi)
6057
6058   // [source_url]: sourceURL from magic comment
6059   DECL_ACCESSORS(source_url, Object)
6060
6061   // [source_url]: sourceMappingURL magic comment
6062   DECL_ACCESSORS(source_mapping_url, Object)
6063
6064   // [compilation_type]: how the the script was compiled. Encoded in the
6065   // 'flags' field.
6066   inline CompilationType compilation_type();
6067   inline void set_compilation_type(CompilationType type);
6068
6069   // [compilation_state]: determines whether the script has already been
6070   // compiled. Encoded in the 'flags' field.
6071   inline CompilationState compilation_state();
6072   inline void set_compilation_state(CompilationState state);
6073
6074   // [hide_source]: determines whether the script source can be exposed as
6075   // function source. Encoded in the 'flags' field.
6076   inline bool hide_source();
6077   inline void set_hide_source(bool value);
6078
6079   // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6080   // and used by the embedder to make decisions about the script. V8 just passes
6081   // this through. Encoded in the 'flags' field.
6082   inline v8::ScriptOriginOptions origin_options();
6083   inline void set_origin_options(ScriptOriginOptions origin_options);
6084
6085   DECLARE_CAST(Script)
6086
6087   // If script source is an external string, check that the underlying
6088   // resource is accessible. Otherwise, always return true.
6089   inline bool HasValidSource();
6090
6091   // Convert code position into column number.
6092   static int GetColumnNumber(Handle<Script> script, int code_pos);
6093
6094   // Convert code position into (zero-based) line number.
6095   // The non-handlified version does not allocate, but may be much slower.
6096   static int GetLineNumber(Handle<Script> script, int code_pos);
6097   int GetLineNumber(int code_pos);
6098
6099   static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6100
6101   // Init line_ends array with code positions of line ends inside script source.
6102   static void InitLineEnds(Handle<Script> script);
6103
6104   // Get the JS object wrapping the given script; create it if none exists.
6105   static Handle<JSObject> GetWrapper(Handle<Script> script);
6106
6107   // Look through the list of existing shared function infos to find one
6108   // that matches the function literal.  Return empty handle if not found.
6109   MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6110
6111   // Iterate over all script objects on the heap.
6112   class Iterator {
6113    public:
6114     explicit Iterator(Isolate* isolate);
6115     Script* Next();
6116
6117    private:
6118     WeakFixedArray::Iterator iterator_;
6119     DISALLOW_COPY_AND_ASSIGN(Iterator);
6120   };
6121
6122   // Dispatched behavior.
6123   DECLARE_PRINTER(Script)
6124   DECLARE_VERIFIER(Script)
6125
6126   static const int kSourceOffset = HeapObject::kHeaderSize;
6127   static const int kNameOffset = kSourceOffset + kPointerSize;
6128   static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6129   static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6130   static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6131   static const int kWrapperOffset = kContextOffset + kPointerSize;
6132   static const int kTypeOffset = kWrapperOffset + kPointerSize;
6133   static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6134   static const int kIdOffset = kLineEndsOffset + kPointerSize;
6135   static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6136   static const int kEvalFrominstructionsOffsetOffset =
6137       kEvalFromSharedOffset + kPointerSize;
6138   static const int kSharedFunctionInfosOffset =
6139       kEvalFrominstructionsOffsetOffset + kPointerSize;
6140   static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6141   static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6142   static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6143   static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6144
6145  private:
6146   int GetLineNumberWithArray(int code_pos);
6147
6148   // Bit positions in the flags field.
6149   static const int kCompilationTypeBit = 0;
6150   static const int kCompilationStateBit = 1;
6151   static const int kHideSourceBit = 2;
6152   static const int kOriginOptionsShift = 3;
6153   static const int kOriginOptionsSize = 3;
6154   static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6155                                         << kOriginOptionsShift;
6156
6157   DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6158 };
6159
6160
6161 // List of builtin functions we want to identify to improve code
6162 // generation.
6163 //
6164 // Each entry has a name of a global object property holding an object
6165 // optionally followed by ".prototype", a name of a builtin function
6166 // on the object (the one the id is set for), and a label.
6167 //
6168 // Installation of ids for the selected builtin functions is handled
6169 // by the bootstrapper.
6170 #define FUNCTIONS_WITH_ID_LIST(V)                   \
6171   V(Array.prototype, indexOf, ArrayIndexOf)         \
6172   V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6173   V(Array.prototype, push, ArrayPush)               \
6174   V(Array.prototype, pop, ArrayPop)                 \
6175   V(Array.prototype, shift, ArrayShift)             \
6176   V(Function.prototype, apply, FunctionApply)       \
6177   V(Function.prototype, call, FunctionCall)         \
6178   V(String.prototype, charCodeAt, StringCharCodeAt) \
6179   V(String.prototype, charAt, StringCharAt)         \
6180   V(String, fromCharCode, StringFromCharCode)       \
6181   V(Math, random, MathRandom)                       \
6182   V(Math, floor, MathFloor)                         \
6183   V(Math, round, MathRound)                         \
6184   V(Math, ceil, MathCeil)                           \
6185   V(Math, abs, MathAbs)                             \
6186   V(Math, log, MathLog)                             \
6187   V(Math, exp, MathExp)                             \
6188   V(Math, sqrt, MathSqrt)                           \
6189   V(Math, pow, MathPow)                             \
6190   V(Math, max, MathMax)                             \
6191   V(Math, min, MathMin)                             \
6192   V(Math, cos, MathCos)                             \
6193   V(Math, sin, MathSin)                             \
6194   V(Math, tan, MathTan)                             \
6195   V(Math, acos, MathAcos)                           \
6196   V(Math, asin, MathAsin)                           \
6197   V(Math, atan, MathAtan)                           \
6198   V(Math, atan2, MathAtan2)                         \
6199   V(Math, imul, MathImul)                           \
6200   V(Math, clz32, MathClz32)                         \
6201   V(Math, fround, MathFround)
6202
6203 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6204   V(Atomics, load, AtomicsLoad)          \
6205   V(Atomics, store, AtomicsStore)
6206
6207 enum BuiltinFunctionId {
6208   kArrayCode,
6209 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name)    \
6210   k##name,
6211   FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6212       ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6213 #undef DECLARE_FUNCTION_ID
6214   // Fake id for a special case of Math.pow. Note, it continues the
6215   // list of math functions.
6216   kMathPowHalf
6217 };
6218
6219
6220 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6221 // that both {code} and {literals} can be NULL to pass search result status.
6222 struct CodeAndLiterals {
6223   Code* code;            // Cached optimized code.
6224   FixedArray* literals;  // Cached literals array.
6225 };
6226
6227
6228 // SharedFunctionInfo describes the JSFunction information that can be
6229 // shared by multiple instances of the function.
6230 class SharedFunctionInfo: public HeapObject {
6231  public:
6232   // [name]: Function name.
6233   DECL_ACCESSORS(name, Object)
6234
6235   // [code]: Function code.
6236   DECL_ACCESSORS(code, Code)
6237   inline void ReplaceCode(Code* code);
6238
6239   // [optimized_code_map]: Map from native context to optimized code
6240   // and a shared literals array or Smi(0) if none.
6241   DECL_ACCESSORS(optimized_code_map, Object)
6242
6243   // Returns entry from optimized code map for specified context and OSR entry.
6244   // Note that {code == nullptr} indicates no matching entry has been found,
6245   // whereas {literals == nullptr} indicates the code is context-independent.
6246   CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6247                                          BailoutId osr_ast_id);
6248
6249   // Clear optimized code map.
6250   void ClearOptimizedCodeMap();
6251
6252   // Removed a specific optimized code object from the optimized code map.
6253   void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6254
6255   // Trims the optimized code map after entries have been removed.
6256   void TrimOptimizedCodeMap(int shrink_by);
6257
6258   // Add a new entry to the optimized code map for context-independent code.
6259   static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6260                                               Handle<Code> code);
6261
6262   // Add a new entry to the optimized code map for context-dependent code.
6263   static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6264                                     Handle<Context> native_context,
6265                                     Handle<Code> code,
6266                                     Handle<FixedArray> literals,
6267                                     BailoutId osr_ast_id);
6268
6269   // Set up the link between shared function info and the script. The shared
6270   // function info is added to the list on the script.
6271   static void SetScript(Handle<SharedFunctionInfo> shared,
6272                         Handle<Object> script_object);
6273
6274   // Layout description of the optimized code map.
6275   static const int kNextMapIndex = 0;
6276   static const int kSharedCodeIndex = 1;
6277   static const int kEntriesStart = 2;
6278   static const int kContextOffset = 0;
6279   static const int kCachedCodeOffset = 1;
6280   static const int kLiteralsOffset = 2;
6281   static const int kOsrAstIdOffset = 3;
6282   static const int kEntryLength = 4;
6283   static const int kInitialLength = kEntriesStart + kEntryLength;
6284
6285   // [scope_info]: Scope info.
6286   DECL_ACCESSORS(scope_info, ScopeInfo)
6287
6288   // [construct stub]: Code stub for constructing instances of this function.
6289   DECL_ACCESSORS(construct_stub, Code)
6290
6291   // Returns if this function has been compiled to native code yet.
6292   inline bool is_compiled();
6293
6294   // [length]: The function length - usually the number of declared parameters.
6295   // Use up to 2^30 parameters.
6296   inline int length() const;
6297   inline void set_length(int value);
6298
6299   // [internal formal parameter count]: The declared number of parameters.
6300   // For subclass constructors, also includes new.target.
6301   // The size of function's frame is internal_formal_parameter_count + 1.
6302   inline int internal_formal_parameter_count() const;
6303   inline void set_internal_formal_parameter_count(int value);
6304
6305   // Set the formal parameter count so the function code will be
6306   // called without using argument adaptor frames.
6307   inline void DontAdaptArguments();
6308
6309   // [expected_nof_properties]: Expected number of properties for the function.
6310   inline int expected_nof_properties() const;
6311   inline void set_expected_nof_properties(int value);
6312
6313   // [feedback_vector] - accumulates ast node feedback from full-codegen and
6314   // (increasingly) from crankshafted code where sufficient feedback isn't
6315   // available.
6316   DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6317
6318   // Unconditionally clear the type feedback vector (including vector ICs).
6319   void ClearTypeFeedbackInfo();
6320
6321   // Clear the type feedback vector with a more subtle policy at GC time.
6322   void ClearTypeFeedbackInfoAtGCTime();
6323
6324 #if TRACE_MAPS
6325   // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6326   // even if the GC moves this SharedFunctionInfo.
6327   inline int unique_id() const;
6328   inline void set_unique_id(int value);
6329 #endif
6330
6331   // [instance class name]: class name for instances.
6332   DECL_ACCESSORS(instance_class_name, Object)
6333
6334   // [function data]: This field holds some additional data for function.
6335   // Currently it has one of:
6336   //  - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6337   //  - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6338   //  - a BytecodeArray for the interpreter [HasBytecodeArray()].
6339   // In the long run we don't want all functions to have this field but
6340   // we can fix that when we have a better model for storing hidden data
6341   // on objects.
6342   DECL_ACCESSORS(function_data, Object)
6343
6344   inline bool IsApiFunction();
6345   inline FunctionTemplateInfo* get_api_func_data();
6346   inline bool HasBuiltinFunctionId();
6347   inline BuiltinFunctionId builtin_function_id();
6348   inline bool HasBytecodeArray();
6349   inline BytecodeArray* bytecode_array();
6350
6351   // [script info]: Script from which the function originates.
6352   DECL_ACCESSORS(script, Object)
6353
6354   // [num_literals]: Number of literals used by this function.
6355   inline int num_literals() const;
6356   inline void set_num_literals(int value);
6357
6358   // [start_position_and_type]: Field used to store both the source code
6359   // position, whether or not the function is a function expression,
6360   // and whether or not the function is a toplevel function. The two
6361   // least significants bit indicates whether the function is an
6362   // expression and the rest contains the source code position.
6363   inline int start_position_and_type() const;
6364   inline void set_start_position_and_type(int value);
6365
6366   // The function is subject to debugging if a debug info is attached.
6367   inline bool HasDebugInfo();
6368   inline DebugInfo* GetDebugInfo();
6369
6370   // A function has debug code if the compiled code has debug break slots.
6371   inline bool HasDebugCode();
6372
6373   // [debug info]: Debug information.
6374   DECL_ACCESSORS(debug_info, Object)
6375
6376   // [inferred name]: Name inferred from variable or property
6377   // assignment of this function. Used to facilitate debugging and
6378   // profiling of JavaScript code written in OO style, where almost
6379   // all functions are anonymous but are assigned to object
6380   // properties.
6381   DECL_ACCESSORS(inferred_name, String)
6382
6383   // The function's name if it is non-empty, otherwise the inferred name.
6384   String* DebugName();
6385
6386   // Position of the 'function' token in the script source.
6387   inline int function_token_position() const;
6388   inline void set_function_token_position(int function_token_position);
6389
6390   // Position of this function in the script source.
6391   inline int start_position() const;
6392   inline void set_start_position(int start_position);
6393
6394   // End position of this function in the script source.
6395   inline int end_position() const;
6396   inline void set_end_position(int end_position);
6397
6398   // Is this function a function expression in the source code.
6399   DECL_BOOLEAN_ACCESSORS(is_expression)
6400
6401   // Is this function a top-level function (scripts, evals).
6402   DECL_BOOLEAN_ACCESSORS(is_toplevel)
6403
6404   // Bit field containing various information collected by the compiler to
6405   // drive optimization.
6406   inline int compiler_hints() const;
6407   inline void set_compiler_hints(int value);
6408
6409   inline int ast_node_count() const;
6410   inline void set_ast_node_count(int count);
6411
6412   inline int profiler_ticks() const;
6413   inline void set_profiler_ticks(int ticks);
6414
6415   // Inline cache age is used to infer whether the function survived a context
6416   // disposal or not. In the former case we reset the opt_count.
6417   inline int ic_age();
6418   inline void set_ic_age(int age);
6419
6420   // Indicates if this function can be lazy compiled.
6421   // This is used to determine if we can safely flush code from a function
6422   // when doing GC if we expect that the function will no longer be used.
6423   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6424
6425   // Indicates if this function can be lazy compiled without a context.
6426   // This is used to determine if we can force compilation without reaching
6427   // the function through program execution but through other means (e.g. heap
6428   // iteration by the debugger).
6429   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6430
6431   // Indicates whether optimizations have been disabled for this
6432   // shared function info. If a function is repeatedly optimized or if
6433   // we cannot optimize the function we disable optimization to avoid
6434   // spending time attempting to optimize it again.
6435   DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6436
6437   // Indicates the language mode.
6438   inline LanguageMode language_mode();
6439   inline void set_language_mode(LanguageMode language_mode);
6440
6441   // False if the function definitely does not allocate an arguments object.
6442   DECL_BOOLEAN_ACCESSORS(uses_arguments)
6443
6444   // Indicates that this function uses a super property (or an eval that may
6445   // use a super property).
6446   // This is needed to set up the [[HomeObject]] on the function instance.
6447   DECL_BOOLEAN_ACCESSORS(needs_home_object)
6448
6449   // True if the function has any duplicated parameter names.
6450   DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6451
6452   // Indicates whether the function is a native function.
6453   // These needs special treatment in .call and .apply since
6454   // null passed as the receiver should not be translated to the
6455   // global object.
6456   DECL_BOOLEAN_ACCESSORS(native)
6457
6458   // Indicate that this function should always be inlined in optimized code.
6459   DECL_BOOLEAN_ACCESSORS(force_inline)
6460
6461   // Indicates that the function was created by the Function function.
6462   // Though it's anonymous, toString should treat it as if it had the name
6463   // "anonymous".  We don't set the name itself so that the system does not
6464   // see a binding for it.
6465   DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6466
6467   // Indicates whether the function is a bound function created using
6468   // the bind function.
6469   DECL_BOOLEAN_ACCESSORS(bound)
6470
6471   // Indicates that the function is anonymous (the name field can be set
6472   // through the API, which does not change this flag).
6473   DECL_BOOLEAN_ACCESSORS(is_anonymous)
6474
6475   // Is this a function or top-level/eval code.
6476   DECL_BOOLEAN_ACCESSORS(is_function)
6477
6478   // Indicates that code for this function cannot be compiled with Crankshaft.
6479   DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6480
6481   // Indicates that code for this function cannot be flushed.
6482   DECL_BOOLEAN_ACCESSORS(dont_flush)
6483
6484   // Indicates that this function is a generator.
6485   DECL_BOOLEAN_ACCESSORS(is_generator)
6486
6487   // Indicates that this function is an arrow function.
6488   DECL_BOOLEAN_ACCESSORS(is_arrow)
6489
6490   // Indicates that this function is a concise method.
6491   DECL_BOOLEAN_ACCESSORS(is_concise_method)
6492
6493   // Indicates that this function is an accessor (getter or setter).
6494   DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6495
6496   // Indicates that this function is a default constructor.
6497   DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6498
6499   // Indicates that this function is an asm function.
6500   DECL_BOOLEAN_ACCESSORS(asm_function)
6501
6502   // Indicates that the the shared function info is deserialized from cache.
6503   DECL_BOOLEAN_ACCESSORS(deserialized)
6504
6505   // Indicates that the the shared function info has never been compiled before.
6506   DECL_BOOLEAN_ACCESSORS(never_compiled)
6507
6508   inline FunctionKind kind();
6509   inline void set_kind(FunctionKind kind);
6510
6511   // Indicates whether or not the code in the shared function support
6512   // deoptimization.
6513   inline bool has_deoptimization_support();
6514
6515   // Enable deoptimization support through recompiled code.
6516   void EnableDeoptimizationSupport(Code* recompiled);
6517
6518   // Disable (further) attempted optimization of all functions sharing this
6519   // shared function info.
6520   void DisableOptimization(BailoutReason reason);
6521
6522   inline BailoutReason disable_optimization_reason();
6523
6524   // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6525   // code, returns whether it asserted (i.e., always true if assertions are
6526   // disabled).
6527   bool VerifyBailoutId(BailoutId id);
6528
6529   // [source code]: Source code for the function.
6530   bool HasSourceCode() const;
6531   Handle<Object> GetSourceCode();
6532
6533   // Number of times the function was optimized.
6534   inline int opt_count();
6535   inline void set_opt_count(int opt_count);
6536
6537   // Number of times the function was deoptimized.
6538   inline void set_deopt_count(int value);
6539   inline int deopt_count();
6540   inline void increment_deopt_count();
6541
6542   // Number of time we tried to re-enable optimization after it
6543   // was disabled due to high number of deoptimizations.
6544   inline void set_opt_reenable_tries(int value);
6545   inline int opt_reenable_tries();
6546
6547   inline void TryReenableOptimization();
6548
6549   // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6550   inline void set_counters(int value);
6551   inline int counters() const;
6552
6553   // Stores opt_count and bailout_reason as bit-fields.
6554   inline void set_opt_count_and_bailout_reason(int value);
6555   inline int opt_count_and_bailout_reason() const;
6556
6557   inline void set_disable_optimization_reason(BailoutReason reason);
6558
6559   // Tells whether this function should be subject to debugging.
6560   inline bool IsSubjectToDebugging();
6561
6562   // Whether this function is defined in native code or extensions.
6563   inline bool IsBuiltin();
6564
6565   // Check whether or not this function is inlineable.
6566   bool IsInlineable();
6567
6568   // Source size of this function.
6569   int SourceSize();
6570
6571   // Calculate the instance size.
6572   int CalculateInstanceSize();
6573
6574   // Calculate the number of in-object properties.
6575   int CalculateInObjectProperties();
6576
6577   inline bool has_simple_parameters();
6578
6579   // Initialize a SharedFunctionInfo from a parsed function literal.
6580   static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6581                                       FunctionLiteral* lit);
6582
6583   // Dispatched behavior.
6584   DECLARE_PRINTER(SharedFunctionInfo)
6585   DECLARE_VERIFIER(SharedFunctionInfo)
6586
6587   void ResetForNewContext(int new_ic_age);
6588
6589   // Iterate over all shared function infos that are created from a script.
6590   // That excludes shared function infos created for API functions and C++
6591   // builtins.
6592   class Iterator {
6593    public:
6594     explicit Iterator(Isolate* isolate);
6595     SharedFunctionInfo* Next();
6596
6597    private:
6598     bool NextScript();
6599
6600     Script::Iterator script_iterator_;
6601     WeakFixedArray::Iterator sfi_iterator_;
6602     DisallowHeapAllocation no_gc_;
6603     DISALLOW_COPY_AND_ASSIGN(Iterator);
6604   };
6605
6606   DECLARE_CAST(SharedFunctionInfo)
6607
6608   // Constants.
6609   static const int kDontAdaptArgumentsSentinel = -1;
6610
6611   // Layout description.
6612   // Pointer fields.
6613   static const int kNameOffset = HeapObject::kHeaderSize;
6614   static const int kCodeOffset = kNameOffset + kPointerSize;
6615   static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6616   static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6617   static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6618   static const int kInstanceClassNameOffset =
6619       kConstructStubOffset + kPointerSize;
6620   static const int kFunctionDataOffset =
6621       kInstanceClassNameOffset + kPointerSize;
6622   static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6623   static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6624   static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6625   static const int kFeedbackVectorOffset =
6626       kInferredNameOffset + kPointerSize;
6627 #if TRACE_MAPS
6628   static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6629   static const int kLastPointerFieldOffset = kUniqueIdOffset;
6630 #else
6631   // Just to not break the postmortrem support with conditional offsets
6632   static const int kUniqueIdOffset = kFeedbackVectorOffset;
6633   static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6634 #endif
6635
6636 #if V8_HOST_ARCH_32_BIT
6637   // Smi fields.
6638   static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6639   static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6640   static const int kExpectedNofPropertiesOffset =
6641       kFormalParameterCountOffset + kPointerSize;
6642   static const int kNumLiteralsOffset =
6643       kExpectedNofPropertiesOffset + kPointerSize;
6644   static const int kStartPositionAndTypeOffset =
6645       kNumLiteralsOffset + kPointerSize;
6646   static const int kEndPositionOffset =
6647       kStartPositionAndTypeOffset + kPointerSize;
6648   static const int kFunctionTokenPositionOffset =
6649       kEndPositionOffset + kPointerSize;
6650   static const int kCompilerHintsOffset =
6651       kFunctionTokenPositionOffset + kPointerSize;
6652   static const int kOptCountAndBailoutReasonOffset =
6653       kCompilerHintsOffset + kPointerSize;
6654   static const int kCountersOffset =
6655       kOptCountAndBailoutReasonOffset + kPointerSize;
6656   static const int kAstNodeCountOffset =
6657       kCountersOffset + kPointerSize;
6658   static const int kProfilerTicksOffset =
6659       kAstNodeCountOffset + kPointerSize;
6660
6661   // Total size.
6662   static const int kSize = kProfilerTicksOffset + kPointerSize;
6663 #else
6664   // The only reason to use smi fields instead of int fields
6665   // is to allow iteration without maps decoding during
6666   // garbage collections.
6667   // To avoid wasting space on 64-bit architectures we use
6668   // the following trick: we group integer fields into pairs
6669 // The least significant integer in each pair is shifted left by 1.
6670 // By doing this we guarantee that LSB of each kPointerSize aligned
6671 // word is not set and thus this word cannot be treated as pointer
6672 // to HeapObject during old space traversal.
6673 #if V8_TARGET_LITTLE_ENDIAN
6674   static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6675   static const int kFormalParameterCountOffset =
6676       kLengthOffset + kIntSize;
6677
6678   static const int kExpectedNofPropertiesOffset =
6679       kFormalParameterCountOffset + kIntSize;
6680   static const int kNumLiteralsOffset =
6681       kExpectedNofPropertiesOffset + kIntSize;
6682
6683   static const int kEndPositionOffset =
6684       kNumLiteralsOffset + kIntSize;
6685   static const int kStartPositionAndTypeOffset =
6686       kEndPositionOffset + kIntSize;
6687
6688   static const int kFunctionTokenPositionOffset =
6689       kStartPositionAndTypeOffset + kIntSize;
6690   static const int kCompilerHintsOffset =
6691       kFunctionTokenPositionOffset + kIntSize;
6692
6693   static const int kOptCountAndBailoutReasonOffset =
6694       kCompilerHintsOffset + kIntSize;
6695   static const int kCountersOffset =
6696       kOptCountAndBailoutReasonOffset + kIntSize;
6697
6698   static const int kAstNodeCountOffset =
6699       kCountersOffset + kIntSize;
6700   static const int kProfilerTicksOffset =
6701       kAstNodeCountOffset + kIntSize;
6702
6703   // Total size.
6704   static const int kSize = kProfilerTicksOffset + kIntSize;
6705
6706 #elif V8_TARGET_BIG_ENDIAN
6707   static const int kFormalParameterCountOffset =
6708       kLastPointerFieldOffset + kPointerSize;
6709   static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6710
6711   static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6712   static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6713
6714   static const int kStartPositionAndTypeOffset =
6715       kExpectedNofPropertiesOffset + kIntSize;
6716   static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6717
6718   static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6719   static const int kFunctionTokenPositionOffset =
6720       kCompilerHintsOffset + kIntSize;
6721
6722   static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6723   static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6724
6725   static const int kProfilerTicksOffset =
6726       kOptCountAndBailoutReasonOffset + kIntSize;
6727   static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6728
6729   // Total size.
6730   static const int kSize = kAstNodeCountOffset + kIntSize;
6731
6732 #else
6733 #error Unknown byte ordering
6734 #endif  // Big endian
6735 #endif  // 64-bit
6736
6737
6738   static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6739
6740   typedef FixedBodyDescriptor<kNameOffset,
6741                               kLastPointerFieldOffset + kPointerSize,
6742                               kSize> BodyDescriptor;
6743
6744   // Bit positions in start_position_and_type.
6745   // The source code start position is in the 30 most significant bits of
6746   // the start_position_and_type field.
6747   static const int kIsExpressionBit    = 0;
6748   static const int kIsTopLevelBit      = 1;
6749   static const int kStartPositionShift = 2;
6750   static const int kStartPositionMask  = ~((1 << kStartPositionShift) - 1);
6751
6752   // Bit positions in compiler_hints.
6753   enum CompilerHints {
6754     kAllowLazyCompilation,
6755     kAllowLazyCompilationWithoutContext,
6756     kOptimizationDisabled,
6757     kNative,
6758     kStrictModeFunction,
6759     kStrongModeFunction,
6760     kUsesArguments,
6761     kNeedsHomeObject,
6762     kHasDuplicateParameters,
6763     kForceInline,
6764     kBoundFunction,
6765     kIsAnonymous,
6766     kNameShouldPrintAsAnonymous,
6767     kIsFunction,
6768     kDontCrankshaft,
6769     kDontFlush,
6770     kIsArrow,
6771     kIsGenerator,
6772     kIsConciseMethod,
6773     kIsAccessorFunction,
6774     kIsDefaultConstructor,
6775     kIsSubclassConstructor,
6776     kIsBaseConstructor,
6777     kInClassLiteral,
6778     kIsAsmFunction,
6779     kDeserialized,
6780     kNeverCompiled,
6781     kCompilerHintsCount  // Pseudo entry
6782   };
6783   // Add hints for other modes when they're added.
6784   STATIC_ASSERT(LANGUAGE_END == 3);
6785
6786   class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6787
6788   class DeoptCountBits : public BitField<int, 0, 4> {};
6789   class OptReenableTriesBits : public BitField<int, 4, 18> {};
6790   class ICAgeBits : public BitField<int, 22, 8> {};
6791
6792   class OptCountBits : public BitField<int, 0, 22> {};
6793   class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6794
6795  private:
6796 #if V8_HOST_ARCH_32_BIT
6797   // On 32 bit platforms, compiler hints is a smi.
6798   static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6799   static const int kCompilerHintsSize = kPointerSize;
6800 #else
6801   // On 64 bit platforms, compiler hints is not a smi, see comment above.
6802   static const int kCompilerHintsSmiTagSize = 0;
6803   static const int kCompilerHintsSize = kIntSize;
6804 #endif
6805
6806   STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6807                 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6808
6809  public:
6810   // Constants for optimizing codegen for strict mode function and
6811   // native tests.
6812   // Allows to use byte-width instructions.
6813   static const int kStrictModeBitWithinByte =
6814       (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6815   static const int kStrongModeBitWithinByte =
6816       (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6817
6818   static const int kNativeBitWithinByte =
6819       (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6820
6821   static const int kBoundBitWithinByte =
6822       (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6823
6824 #if defined(V8_TARGET_LITTLE_ENDIAN)
6825   static const int kStrictModeByteOffset = kCompilerHintsOffset +
6826       (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6827   static const int kStrongModeByteOffset =
6828       kCompilerHintsOffset +
6829       (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6830   static const int kNativeByteOffset = kCompilerHintsOffset +
6831       (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6832   static const int kBoundByteOffset =
6833       kCompilerHintsOffset +
6834       (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6835 #elif defined(V8_TARGET_BIG_ENDIAN)
6836   static const int kStrictModeByteOffset = kCompilerHintsOffset +
6837       (kCompilerHintsSize - 1) -
6838       ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6839   static const int kStrongModeByteOffset =
6840       kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6841       ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6842   static const int kNativeByteOffset = kCompilerHintsOffset +
6843       (kCompilerHintsSize - 1) -
6844       ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6845   static const int kBoundByteOffset =
6846       kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6847       ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6848 #else
6849 #error Unknown byte ordering
6850 #endif
6851
6852  private:
6853   DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6854 };
6855
6856
6857 // Printing support.
6858 struct SourceCodeOf {
6859   explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6860       : value(v), max_length(max) {}
6861   const SharedFunctionInfo* value;
6862   int max_length;
6863 };
6864
6865
6866 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6867
6868
6869 class JSGeneratorObject: public JSObject {
6870  public:
6871   // [function]: The function corresponding to this generator object.
6872   DECL_ACCESSORS(function, JSFunction)
6873
6874   // [context]: The context of the suspended computation.
6875   DECL_ACCESSORS(context, Context)
6876
6877   // [receiver]: The receiver of the suspended computation.
6878   DECL_ACCESSORS(receiver, Object)
6879
6880   // [continuation]: Offset into code of continuation.
6881   //
6882   // A positive offset indicates a suspended generator.  The special
6883   // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6884   // cannot be resumed.
6885   inline int continuation() const;
6886   inline void set_continuation(int continuation);
6887   inline bool is_closed();
6888   inline bool is_executing();
6889   inline bool is_suspended();
6890
6891   // [operand_stack]: Saved operand stack.
6892   DECL_ACCESSORS(operand_stack, FixedArray)
6893
6894   DECLARE_CAST(JSGeneratorObject)
6895
6896   // Dispatched behavior.
6897   DECLARE_PRINTER(JSGeneratorObject)
6898   DECLARE_VERIFIER(JSGeneratorObject)
6899
6900   // Magic sentinel values for the continuation.
6901   static const int kGeneratorExecuting = -1;
6902   static const int kGeneratorClosed = 0;
6903
6904   // Layout description.
6905   static const int kFunctionOffset = JSObject::kHeaderSize;
6906   static const int kContextOffset = kFunctionOffset + kPointerSize;
6907   static const int kReceiverOffset = kContextOffset + kPointerSize;
6908   static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6909   static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6910   static const int kSize = kOperandStackOffset + kPointerSize;
6911
6912   // Resume mode, for use by runtime functions.
6913   enum ResumeMode { NEXT, THROW };
6914
6915  private:
6916   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6917 };
6918
6919
6920 // Representation for module instance objects.
6921 class JSModule: public JSObject {
6922  public:
6923   // [context]: the context holding the module's locals, or undefined if none.
6924   DECL_ACCESSORS(context, Object)
6925
6926   // [scope_info]: Scope info.
6927   DECL_ACCESSORS(scope_info, ScopeInfo)
6928
6929   DECLARE_CAST(JSModule)
6930
6931   // Dispatched behavior.
6932   DECLARE_PRINTER(JSModule)
6933   DECLARE_VERIFIER(JSModule)
6934
6935   // Layout description.
6936   static const int kContextOffset = JSObject::kHeaderSize;
6937   static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6938   static const int kSize = kScopeInfoOffset + kPointerSize;
6939
6940  private:
6941   DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6942 };
6943
6944
6945 // JSFunction describes JavaScript functions.
6946 class JSFunction: public JSObject {
6947  public:
6948   // [prototype_or_initial_map]:
6949   DECL_ACCESSORS(prototype_or_initial_map, Object)
6950
6951   // [shared]: The information about the function that
6952   // can be shared by instances.
6953   DECL_ACCESSORS(shared, SharedFunctionInfo)
6954
6955   // [context]: The context for this function.
6956   inline Context* context();
6957   inline void set_context(Object* context);
6958   inline JSObject* global_proxy();
6959
6960   // [code]: The generated code object for this function.  Executed
6961   // when the function is invoked, e.g. foo() or new foo(). See
6962   // [[Call]] and [[Construct]] description in ECMA-262, section
6963   // 8.6.2, page 27.
6964   inline Code* code();
6965   inline void set_code(Code* code);
6966   inline void set_code_no_write_barrier(Code* code);
6967   inline void ReplaceCode(Code* code);
6968
6969   // Tells whether this function is builtin.
6970   inline bool IsBuiltin();
6971
6972   // Tells whether this function inlines the given shared function info.
6973   bool Inlines(SharedFunctionInfo* candidate);
6974
6975   // Tells whether this function should be subject to debugging.
6976   inline bool IsSubjectToDebugging();
6977
6978   // Tells whether or not the function needs arguments adaption.
6979   inline bool NeedsArgumentsAdaption();
6980
6981   // Tells whether or not this function has been optimized.
6982   inline bool IsOptimized();
6983
6984   // Mark this function for lazy recompilation. The function will be
6985   // recompiled the next time it is executed.
6986   void MarkForOptimization();
6987   void AttemptConcurrentOptimization();
6988
6989   // Tells whether or not the function is already marked for lazy
6990   // recompilation.
6991   inline bool IsMarkedForOptimization();
6992   inline bool IsMarkedForConcurrentOptimization();
6993
6994   // Tells whether or not the function is on the concurrent recompilation queue.
6995   inline bool IsInOptimizationQueue();
6996
6997   // Inobject slack tracking is the way to reclaim unused inobject space.
6998   //
6999   // The instance size is initially determined by adding some slack to
7000   // expected_nof_properties (to allow for a few extra properties added
7001   // after the constructor). There is no guarantee that the extra space
7002   // will not be wasted.
7003   //
7004   // Here is the algorithm to reclaim the unused inobject space:
7005   // - Detect the first constructor call for this JSFunction.
7006   //   When it happens enter the "in progress" state: initialize construction
7007   //   counter in the initial_map.
7008   // - While the tracking is in progress create objects filled with
7009   //   one_pointer_filler_map instead of undefined_value. This way they can be
7010   //   resized quickly and safely.
7011   // - Once enough objects have been created  compute the 'slack'
7012   //   (traverse the map transition tree starting from the
7013   //   initial_map and find the lowest value of unused_property_fields).
7014   // - Traverse the transition tree again and decrease the instance size
7015   //   of every map. Existing objects will resize automatically (they are
7016   //   filled with one_pointer_filler_map). All further allocations will
7017   //   use the adjusted instance size.
7018   // - SharedFunctionInfo's expected_nof_properties left unmodified since
7019   //   allocations made using different closures could actually create different
7020   //   kind of objects (see prototype inheritance pattern).
7021   //
7022   //  Important: inobject slack tracking is not attempted during the snapshot
7023   //  creation.
7024
7025   // True if the initial_map is set and the object constructions countdown
7026   // counter is not zero.
7027   static const int kGenerousAllocationCount =
7028       Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7029   inline bool IsInobjectSlackTrackingInProgress();
7030
7031   // Starts the tracking.
7032   // Initializes object constructions countdown counter in the initial map.
7033   void StartInobjectSlackTracking();
7034
7035   // Completes the tracking.
7036   void CompleteInobjectSlackTracking();
7037
7038   // [literals_or_bindings]: Fixed array holding either
7039   // the materialized literals or the bindings of a bound function.
7040   //
7041   // If the function contains object, regexp or array literals, the
7042   // literals array prefix contains the object, regexp, and array
7043   // function to be used when creating these literals.  This is
7044   // necessary so that we do not dynamically lookup the object, regexp
7045   // or array functions.  Performing a dynamic lookup, we might end up
7046   // using the functions from a new context that we should not have
7047   // access to.
7048   //
7049   // On bound functions, the array is a (copy-on-write) fixed-array containing
7050   // the function that was bound, bound this-value and any bound
7051   // arguments. Bound functions never contain literals.
7052   DECL_ACCESSORS(literals_or_bindings, FixedArray)
7053
7054   inline FixedArray* literals();
7055   inline void set_literals(FixedArray* literals);
7056
7057   inline FixedArray* function_bindings();
7058   inline void set_function_bindings(FixedArray* bindings);
7059
7060   // The initial map for an object created by this constructor.
7061   inline Map* initial_map();
7062   static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7063                             Handle<Object> prototype);
7064   inline bool has_initial_map();
7065   static void EnsureHasInitialMap(Handle<JSFunction> function);
7066
7067   // Get and set the prototype property on a JSFunction. If the
7068   // function has an initial map the prototype is set on the initial
7069   // map. Otherwise, the prototype is put in the initial map field
7070   // until an initial map is needed.
7071   inline bool has_prototype();
7072   inline bool has_instance_prototype();
7073   inline Object* prototype();
7074   inline Object* instance_prototype();
7075   static void SetPrototype(Handle<JSFunction> function,
7076                            Handle<Object> value);
7077   static void SetInstancePrototype(Handle<JSFunction> function,
7078                                    Handle<Object> value);
7079
7080   // Creates a new closure for the fucntion with the same bindings,
7081   // bound values, and prototype. An equivalent of spec operations
7082   // ``CloneMethod`` and ``CloneBoundFunction``.
7083   static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7084
7085   // After prototype is removed, it will not be created when accessed, and
7086   // [[Construct]] from this function will not be allowed.
7087   bool RemovePrototype();
7088   inline bool should_have_prototype();
7089
7090   // Accessor for this function's initial map's [[class]]
7091   // property. This is primarily used by ECMA native functions.  This
7092   // method sets the class_name field of this function's initial map
7093   // to a given value. It creates an initial map if this function does
7094   // not have one. Note that this method does not copy the initial map
7095   // if it has one already, but simply replaces it with the new value.
7096   // Instances created afterwards will have a map whose [[class]] is
7097   // set to 'value', but there is no guarantees on instances created
7098   // before.
7099   void SetInstanceClassName(String* name);
7100
7101   // Returns if this function has been compiled to native code yet.
7102   inline bool is_compiled();
7103
7104   // Returns `false` if formal parameters include rest parameters, optional
7105   // parameters, or destructuring parameters.
7106   // TODO(caitp): make this a flag set during parsing
7107   inline bool has_simple_parameters();
7108
7109   // [next_function_link]: Links functions into various lists, e.g. the list
7110   // of optimized functions hanging off the native_context. The CodeFlusher
7111   // uses this link to chain together flushing candidates. Treated weakly
7112   // by the garbage collector.
7113   DECL_ACCESSORS(next_function_link, Object)
7114
7115   // Prints the name of the function using PrintF.
7116   void PrintName(FILE* out = stdout);
7117
7118   DECLARE_CAST(JSFunction)
7119
7120   // Iterates the objects, including code objects indirectly referenced
7121   // through pointers to the first instruction in the code object.
7122   void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7123
7124   // Dispatched behavior.
7125   DECLARE_PRINTER(JSFunction)
7126   DECLARE_VERIFIER(JSFunction)
7127
7128   // Returns the number of allocated literals.
7129   inline int NumberOfLiterals();
7130
7131   // Used for flags such as --hydrogen-filter.
7132   bool PassesFilter(const char* raw_filter);
7133
7134   // The function's name if it is configured, otherwise shared function info
7135   // debug name.
7136   static Handle<String> GetDebugName(Handle<JSFunction> function);
7137
7138   // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7139   // kSize) is weak and has special handling during garbage collection.
7140   static const int kCodeEntryOffset = JSObject::kHeaderSize;
7141   static const int kPrototypeOrInitialMapOffset =
7142       kCodeEntryOffset + kPointerSize;
7143   static const int kSharedFunctionInfoOffset =
7144       kPrototypeOrInitialMapOffset + kPointerSize;
7145   static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7146   static const int kLiteralsOffset = kContextOffset + kPointerSize;
7147   static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7148   static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7149   static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7150
7151   // Layout of the bound-function binding array.
7152   static const int kBoundFunctionIndex = 0;
7153   static const int kBoundThisIndex = 1;
7154   static const int kBoundArgumentsStartIndex = 2;
7155
7156  private:
7157   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7158 };
7159
7160
7161 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7162 // and the prototype is hidden. JSGlobalProxy always delegates
7163 // property accesses to its prototype if the prototype is not null.
7164 //
7165 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7166 //
7167 // Accessing a JSGlobalProxy requires security check.
7168
7169 class JSGlobalProxy : public JSObject {
7170  public:
7171   // [native_context]: the owner native context of this global proxy object.
7172   // It is null value if this object is not used by any context.
7173   DECL_ACCESSORS(native_context, Object)
7174
7175   // [hash]: The hash code property (undefined if not initialized yet).
7176   DECL_ACCESSORS(hash, Object)
7177
7178   DECLARE_CAST(JSGlobalProxy)
7179
7180   inline bool IsDetachedFrom(GlobalObject* global) const;
7181
7182   // Dispatched behavior.
7183   DECLARE_PRINTER(JSGlobalProxy)
7184   DECLARE_VERIFIER(JSGlobalProxy)
7185
7186   // Layout description.
7187   static const int kNativeContextOffset = JSObject::kHeaderSize;
7188   static const int kHashOffset = kNativeContextOffset + kPointerSize;
7189   static const int kSize = kHashOffset + kPointerSize;
7190
7191  private:
7192   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7193 };
7194
7195
7196 // Common super class for JavaScript global objects and the special
7197 // builtins global objects.
7198 class GlobalObject: public JSObject {
7199  public:
7200   // [builtins]: the object holding the runtime routines written in JS.
7201   DECL_ACCESSORS(builtins, JSBuiltinsObject)
7202
7203   // [native context]: the natives corresponding to this global object.
7204   DECL_ACCESSORS(native_context, Context)
7205
7206   // [global proxy]: the global proxy object of the context
7207   DECL_ACCESSORS(global_proxy, JSObject)
7208
7209   DECLARE_CAST(GlobalObject)
7210
7211   static void InvalidatePropertyCell(Handle<GlobalObject> object,
7212                                      Handle<Name> name);
7213   // Ensure that the global object has a cell for the given property name.
7214   static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7215                                                  Handle<Name> name);
7216
7217   // Layout description.
7218   static const int kBuiltinsOffset = JSObject::kHeaderSize;
7219   static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7220   static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7221   static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7222
7223  private:
7224   DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7225 };
7226
7227
7228 // JavaScript global object.
7229 class JSGlobalObject: public GlobalObject {
7230  public:
7231   DECLARE_CAST(JSGlobalObject)
7232
7233   inline bool IsDetached();
7234
7235   // Dispatched behavior.
7236   DECLARE_PRINTER(JSGlobalObject)
7237   DECLARE_VERIFIER(JSGlobalObject)
7238
7239   // Layout description.
7240   static const int kSize = GlobalObject::kHeaderSize;
7241
7242  private:
7243   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7244 };
7245
7246
7247 // Builtins global object which holds the runtime routines written in
7248 // JavaScript.
7249 class JSBuiltinsObject: public GlobalObject {
7250  public:
7251   DECLARE_CAST(JSBuiltinsObject)
7252
7253   // Dispatched behavior.
7254   DECLARE_PRINTER(JSBuiltinsObject)
7255   DECLARE_VERIFIER(JSBuiltinsObject)
7256
7257   // Layout description.
7258   static const int kSize = GlobalObject::kHeaderSize;
7259
7260  private:
7261   DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7262 };
7263
7264
7265 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7266 class JSValue: public JSObject {
7267  public:
7268   // [value]: the object being wrapped.
7269   DECL_ACCESSORS(value, Object)
7270
7271   DECLARE_CAST(JSValue)
7272
7273   // Dispatched behavior.
7274   DECLARE_PRINTER(JSValue)
7275   DECLARE_VERIFIER(JSValue)
7276
7277   // Layout description.
7278   static const int kValueOffset = JSObject::kHeaderSize;
7279   static const int kSize = kValueOffset + kPointerSize;
7280
7281  private:
7282   DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7283 };
7284
7285
7286 class DateCache;
7287
7288 // Representation for JS date objects.
7289 class JSDate: public JSObject {
7290  public:
7291   // If one component is NaN, all of them are, indicating a NaN time value.
7292   // [value]: the time value.
7293   DECL_ACCESSORS(value, Object)
7294   // [year]: caches year. Either undefined, smi, or NaN.
7295   DECL_ACCESSORS(year, Object)
7296   // [month]: caches month. Either undefined, smi, or NaN.
7297   DECL_ACCESSORS(month, Object)
7298   // [day]: caches day. Either undefined, smi, or NaN.
7299   DECL_ACCESSORS(day, Object)
7300   // [weekday]: caches day of week. Either undefined, smi, or NaN.
7301   DECL_ACCESSORS(weekday, Object)
7302   // [hour]: caches hours. Either undefined, smi, or NaN.
7303   DECL_ACCESSORS(hour, Object)
7304   // [min]: caches minutes. Either undefined, smi, or NaN.
7305   DECL_ACCESSORS(min, Object)
7306   // [sec]: caches seconds. Either undefined, smi, or NaN.
7307   DECL_ACCESSORS(sec, Object)
7308   // [cache stamp]: sample of the date cache stamp at the
7309   // moment when chached fields were cached.
7310   DECL_ACCESSORS(cache_stamp, Object)
7311
7312   DECLARE_CAST(JSDate)
7313
7314   // Returns the date field with the specified index.
7315   // See FieldIndex for the list of date fields.
7316   static Object* GetField(Object* date, Smi* index);
7317
7318   void SetValue(Object* value, bool is_value_nan);
7319
7320   // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7321   static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7322       Handle<JSReceiver> receiver, Handle<Object> hint);
7323
7324   // Dispatched behavior.
7325   DECLARE_PRINTER(JSDate)
7326   DECLARE_VERIFIER(JSDate)
7327
7328   // The order is important. It must be kept in sync with date macros
7329   // in macros.py.
7330   enum FieldIndex {
7331     kDateValue,
7332     kYear,
7333     kMonth,
7334     kDay,
7335     kWeekday,
7336     kHour,
7337     kMinute,
7338     kSecond,
7339     kFirstUncachedField,
7340     kMillisecond = kFirstUncachedField,
7341     kDays,
7342     kTimeInDay,
7343     kFirstUTCField,
7344     kYearUTC = kFirstUTCField,
7345     kMonthUTC,
7346     kDayUTC,
7347     kWeekdayUTC,
7348     kHourUTC,
7349     kMinuteUTC,
7350     kSecondUTC,
7351     kMillisecondUTC,
7352     kDaysUTC,
7353     kTimeInDayUTC,
7354     kTimezoneOffset
7355   };
7356
7357   // Layout description.
7358   static const int kValueOffset = JSObject::kHeaderSize;
7359   static const int kYearOffset = kValueOffset + kPointerSize;
7360   static const int kMonthOffset = kYearOffset + kPointerSize;
7361   static const int kDayOffset = kMonthOffset + kPointerSize;
7362   static const int kWeekdayOffset = kDayOffset + kPointerSize;
7363   static const int kHourOffset = kWeekdayOffset  + kPointerSize;
7364   static const int kMinOffset = kHourOffset + kPointerSize;
7365   static const int kSecOffset = kMinOffset + kPointerSize;
7366   static const int kCacheStampOffset = kSecOffset + kPointerSize;
7367   static const int kSize = kCacheStampOffset + kPointerSize;
7368
7369  private:
7370   inline Object* DoGetField(FieldIndex index);
7371
7372   Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7373
7374   // Computes and caches the cacheable fields of the date.
7375   inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7376
7377
7378   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7379 };
7380
7381
7382 // Representation of message objects used for error reporting through
7383 // the API. The messages are formatted in JavaScript so this object is
7384 // a real JavaScript object. The information used for formatting the
7385 // error messages are not directly accessible from JavaScript to
7386 // prevent leaking information to user code called during error
7387 // formatting.
7388 class JSMessageObject: public JSObject {
7389  public:
7390   // [type]: the type of error message.
7391   inline int type() const;
7392   inline void set_type(int value);
7393
7394   // [arguments]: the arguments for formatting the error message.
7395   DECL_ACCESSORS(argument, Object)
7396
7397   // [script]: the script from which the error message originated.
7398   DECL_ACCESSORS(script, Object)
7399
7400   // [stack_frames]: an array of stack frames for this error object.
7401   DECL_ACCESSORS(stack_frames, Object)
7402
7403   // [start_position]: the start position in the script for the error message.
7404   inline int start_position() const;
7405   inline void set_start_position(int value);
7406
7407   // [end_position]: the end position in the script for the error message.
7408   inline int end_position() const;
7409   inline void set_end_position(int value);
7410
7411   DECLARE_CAST(JSMessageObject)
7412
7413   // Dispatched behavior.
7414   DECLARE_PRINTER(JSMessageObject)
7415   DECLARE_VERIFIER(JSMessageObject)
7416
7417   // Layout description.
7418   static const int kTypeOffset = JSObject::kHeaderSize;
7419   static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7420   static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7421   static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7422   static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7423   static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7424   static const int kSize = kEndPositionOffset + kPointerSize;
7425
7426   typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7427                               kStackFramesOffset + kPointerSize,
7428                               kSize> BodyDescriptor;
7429 };
7430
7431
7432 // Regular expressions
7433 // The regular expression holds a single reference to a FixedArray in
7434 // the kDataOffset field.
7435 // The FixedArray contains the following data:
7436 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7437 // - reference to the original source string
7438 // - reference to the original flag string
7439 // If it is an atom regexp
7440 // - a reference to a literal string to search for
7441 // If it is an irregexp regexp:
7442 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7443 // used for tracking the last usage (used for code flushing).
7444 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7445 // used for tracking the last usage (used for code flushing)..
7446 // - max number of registers used by irregexp implementations.
7447 // - number of capture registers (output values) of the regexp.
7448 class JSRegExp: public JSObject {
7449  public:
7450   // Meaning of Type:
7451   // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7452   // ATOM: A simple string to match against using an indexOf operation.
7453   // IRREGEXP: Compiled with Irregexp.
7454   // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7455   enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7456   enum Flag {
7457     NONE = 0,
7458     GLOBAL = 1,
7459     IGNORE_CASE = 2,
7460     MULTILINE = 4,
7461     STICKY = 8,
7462     UNICODE_ESCAPES = 16
7463   };
7464
7465   class Flags {
7466    public:
7467     explicit Flags(uint32_t value) : value_(value) { }
7468     bool is_global() { return (value_ & GLOBAL) != 0; }
7469     bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7470     bool is_multiline() { return (value_ & MULTILINE) != 0; }
7471     bool is_sticky() { return (value_ & STICKY) != 0; }
7472     bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7473     uint32_t value() { return value_; }
7474    private:
7475     uint32_t value_;
7476   };
7477
7478   DECL_ACCESSORS(data, Object)
7479
7480   inline Type TypeTag();
7481   inline int CaptureCount();
7482   inline Flags GetFlags();
7483   inline String* Pattern();
7484   inline Object* DataAt(int index);
7485   // Set implementation data after the object has been prepared.
7486   inline void SetDataAt(int index, Object* value);
7487
7488   static int code_index(bool is_latin1) {
7489     if (is_latin1) {
7490       return kIrregexpLatin1CodeIndex;
7491     } else {
7492       return kIrregexpUC16CodeIndex;
7493     }
7494   }
7495
7496   static int saved_code_index(bool is_latin1) {
7497     if (is_latin1) {
7498       return kIrregexpLatin1CodeSavedIndex;
7499     } else {
7500       return kIrregexpUC16CodeSavedIndex;
7501     }
7502   }
7503
7504   DECLARE_CAST(JSRegExp)
7505
7506   // Dispatched behavior.
7507   DECLARE_VERIFIER(JSRegExp)
7508
7509   static const int kDataOffset = JSObject::kHeaderSize;
7510   static const int kSize = kDataOffset + kPointerSize;
7511
7512   // Indices in the data array.
7513   static const int kTagIndex = 0;
7514   static const int kSourceIndex = kTagIndex + 1;
7515   static const int kFlagsIndex = kSourceIndex + 1;
7516   static const int kDataIndex = kFlagsIndex + 1;
7517   // The data fields are used in different ways depending on the
7518   // value of the tag.
7519   // Atom regexps (literal strings).
7520   static const int kAtomPatternIndex = kDataIndex;
7521
7522   static const int kAtomDataSize = kAtomPatternIndex + 1;
7523
7524   // Irregexp compiled code or bytecode for Latin1. If compilation
7525   // fails, this fields hold an exception object that should be
7526   // thrown if the regexp is used again.
7527   static const int kIrregexpLatin1CodeIndex = kDataIndex;
7528   // Irregexp compiled code or bytecode for UC16.  If compilation
7529   // fails, this fields hold an exception object that should be
7530   // thrown if the regexp is used again.
7531   static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7532
7533   // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7534   // is a potential candidate for flushing.
7535   static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7536   // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7537   // a potential candidate for flushing.
7538   static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7539
7540   // Maximal number of registers used by either Latin1 or UC16.
7541   // Only used to check that there is enough stack space
7542   static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7543   // Number of captures in the compiled regexp.
7544   static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7545
7546   static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7547
7548   // Offsets directly into the data fixed array.
7549   static const int kDataTagOffset =
7550       FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7551   static const int kDataOneByteCodeOffset =
7552       FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7553   static const int kDataUC16CodeOffset =
7554       FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7555   static const int kIrregexpCaptureCountOffset =
7556       FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7557
7558   // In-object fields.
7559   static const int kSourceFieldIndex = 0;
7560   static const int kGlobalFieldIndex = 1;
7561   static const int kIgnoreCaseFieldIndex = 2;
7562   static const int kMultilineFieldIndex = 3;
7563   static const int kLastIndexFieldIndex = 4;
7564   static const int kInObjectFieldCount = 5;
7565
7566   // The uninitialized value for a regexp code object.
7567   static const int kUninitializedValue = -1;
7568
7569   // The compilation error value for the regexp code object. The real error
7570   // object is in the saved code field.
7571   static const int kCompilationErrorValue = -2;
7572
7573   // When we store the sweep generation at which we moved the code from the
7574   // code index to the saved code index we mask it of to be in the [0:255]
7575   // range.
7576   static const int kCodeAgeMask = 0xff;
7577 };
7578
7579
7580 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7581  public:
7582   static inline bool IsMatch(HashTableKey* key, Object* value) {
7583     return key->IsMatch(value);
7584   }
7585
7586   static inline uint32_t Hash(HashTableKey* key) {
7587     return key->Hash();
7588   }
7589
7590   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7591     return key->HashForObject(object);
7592   }
7593
7594   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7595
7596   static const int kPrefixSize = 0;
7597   static const int kEntrySize = 2;
7598 };
7599
7600
7601 // This cache is used in two different variants. For regexp caching, it simply
7602 // maps identifying info of the regexp to the cached regexp object. Scripts and
7603 // eval code only gets cached after a second probe for the code object. To do
7604 // so, on first "put" only a hash identifying the source is entered into the
7605 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7606 // such lifetimes get reduced, and removed once they reach zero. If a second put
7607 // is called while such a hash is live in the cache, the hash gets replaced by
7608 // an actual cache entry. Age also removes stale live entries from the cache.
7609 // Such entries are identified by SharedFunctionInfos pointing to either the
7610 // recompilation stub, or to "old" code. This avoids memory leaks due to
7611 // premature caching of scripts and eval strings that are never needed later.
7612 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7613                                               CompilationCacheShape,
7614                                               HashTableKey*> {
7615  public:
7616   // Find cached value for a string key, otherwise return null.
7617   Handle<Object> Lookup(
7618       Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7619   Handle<Object> LookupEval(
7620       Handle<String> src, Handle<SharedFunctionInfo> shared,
7621       LanguageMode language_mode, int scope_position);
7622   Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7623   static Handle<CompilationCacheTable> Put(
7624       Handle<CompilationCacheTable> cache, Handle<String> src,
7625       Handle<Context> context, LanguageMode language_mode,
7626       Handle<Object> value);
7627   static Handle<CompilationCacheTable> PutEval(
7628       Handle<CompilationCacheTable> cache, Handle<String> src,
7629       Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7630       int scope_position);
7631   static Handle<CompilationCacheTable> PutRegExp(
7632       Handle<CompilationCacheTable> cache, Handle<String> src,
7633       JSRegExp::Flags flags, Handle<FixedArray> value);
7634   void Remove(Object* value);
7635   void Age();
7636   static const int kHashGenerations = 10;
7637
7638   DECLARE_CAST(CompilationCacheTable)
7639
7640  private:
7641   DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7642 };
7643
7644
7645 class CodeCache: public Struct {
7646  public:
7647   DECL_ACCESSORS(default_cache, FixedArray)
7648   DECL_ACCESSORS(normal_type_cache, Object)
7649
7650   // Add the code object to the cache.
7651   static void Update(
7652       Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7653
7654   // Lookup code object in the cache. Returns code object if found and undefined
7655   // if not.
7656   Object* Lookup(Name* name, Code::Flags flags);
7657
7658   // Get the internal index of a code object in the cache. Returns -1 if the
7659   // code object is not in that cache. This index can be used to later call
7660   // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7661   // RemoveByIndex.
7662   int GetIndex(Object* name, Code* code);
7663
7664   // Remove an object from the cache with the provided internal index.
7665   void RemoveByIndex(Object* name, Code* code, int index);
7666
7667   DECLARE_CAST(CodeCache)
7668
7669   // Dispatched behavior.
7670   DECLARE_PRINTER(CodeCache)
7671   DECLARE_VERIFIER(CodeCache)
7672
7673   static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7674   static const int kNormalTypeCacheOffset =
7675       kDefaultCacheOffset + kPointerSize;
7676   static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7677
7678  private:
7679   static void UpdateDefaultCache(
7680       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7681   static void UpdateNormalTypeCache(
7682       Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7683   Object* LookupDefaultCache(Name* name, Code::Flags flags);
7684   Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7685
7686   // Code cache layout of the default cache. Elements are alternating name and
7687   // code objects for non normal load/store/call IC's.
7688   static const int kCodeCacheEntrySize = 2;
7689   static const int kCodeCacheEntryNameOffset = 0;
7690   static const int kCodeCacheEntryCodeOffset = 1;
7691
7692   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7693 };
7694
7695
7696 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7697  public:
7698   static inline bool IsMatch(HashTableKey* key, Object* value) {
7699     return key->IsMatch(value);
7700   }
7701
7702   static inline uint32_t Hash(HashTableKey* key) {
7703     return key->Hash();
7704   }
7705
7706   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7707     return key->HashForObject(object);
7708   }
7709
7710   static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7711
7712   static const int kPrefixSize = 0;
7713   static const int kEntrySize = 2;
7714 };
7715
7716
7717 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7718                                            CodeCacheHashTableShape,
7719                                            HashTableKey*> {
7720  public:
7721   Object* Lookup(Name* name, Code::Flags flags);
7722   static Handle<CodeCacheHashTable> Put(
7723       Handle<CodeCacheHashTable> table,
7724       Handle<Name> name,
7725       Handle<Code> code);
7726
7727   int GetIndex(Name* name, Code::Flags flags);
7728   void RemoveByIndex(int index);
7729
7730   DECLARE_CAST(CodeCacheHashTable)
7731
7732   // Initial size of the fixed array backing the hash table.
7733   static const int kInitialSize = 64;
7734
7735  private:
7736   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7737 };
7738
7739
7740 class PolymorphicCodeCache: public Struct {
7741  public:
7742   DECL_ACCESSORS(cache, Object)
7743
7744   static void Update(Handle<PolymorphicCodeCache> cache,
7745                      MapHandleList* maps,
7746                      Code::Flags flags,
7747                      Handle<Code> code);
7748
7749
7750   // Returns an undefined value if the entry is not found.
7751   Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7752
7753   DECLARE_CAST(PolymorphicCodeCache)
7754
7755   // Dispatched behavior.
7756   DECLARE_PRINTER(PolymorphicCodeCache)
7757   DECLARE_VERIFIER(PolymorphicCodeCache)
7758
7759   static const int kCacheOffset = HeapObject::kHeaderSize;
7760   static const int kSize = kCacheOffset + kPointerSize;
7761
7762  private:
7763   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7764 };
7765
7766
7767 class PolymorphicCodeCacheHashTable
7768     : public HashTable<PolymorphicCodeCacheHashTable,
7769                        CodeCacheHashTableShape,
7770                        HashTableKey*> {
7771  public:
7772   Object* Lookup(MapHandleList* maps, int code_kind);
7773
7774   static Handle<PolymorphicCodeCacheHashTable> Put(
7775       Handle<PolymorphicCodeCacheHashTable> hash_table,
7776       MapHandleList* maps,
7777       int code_kind,
7778       Handle<Code> code);
7779
7780   DECLARE_CAST(PolymorphicCodeCacheHashTable)
7781
7782   static const int kInitialSize = 64;
7783  private:
7784   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7785 };
7786
7787
7788 class TypeFeedbackInfo: public Struct {
7789  public:
7790   inline int ic_total_count();
7791   inline void set_ic_total_count(int count);
7792
7793   inline int ic_with_type_info_count();
7794   inline void change_ic_with_type_info_count(int delta);
7795
7796   inline int ic_generic_count();
7797   inline void change_ic_generic_count(int delta);
7798
7799   inline void initialize_storage();
7800
7801   inline void change_own_type_change_checksum();
7802   inline int own_type_change_checksum();
7803
7804   inline void set_inlined_type_change_checksum(int checksum);
7805   inline bool matches_inlined_type_change_checksum(int checksum);
7806
7807   DECLARE_CAST(TypeFeedbackInfo)
7808
7809   // Dispatched behavior.
7810   DECLARE_PRINTER(TypeFeedbackInfo)
7811   DECLARE_VERIFIER(TypeFeedbackInfo)
7812
7813   static const int kStorage1Offset = HeapObject::kHeaderSize;
7814   static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7815   static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7816   static const int kSize = kStorage3Offset + kPointerSize;
7817
7818  private:
7819   static const int kTypeChangeChecksumBits = 7;
7820
7821   class ICTotalCountField: public BitField<int, 0,
7822       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
7823   class OwnTypeChangeChecksum: public BitField<int,
7824       kSmiValueSize - kTypeChangeChecksumBits,
7825       kTypeChangeChecksumBits> {};  // NOLINT
7826   class ICsWithTypeInfoCountField: public BitField<int, 0,
7827       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
7828   class InlinedTypeChangeChecksum: public BitField<int,
7829       kSmiValueSize - kTypeChangeChecksumBits,
7830       kTypeChangeChecksumBits> {};  // NOLINT
7831
7832   DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7833 };
7834
7835
7836 enum AllocationSiteMode {
7837   DONT_TRACK_ALLOCATION_SITE,
7838   TRACK_ALLOCATION_SITE,
7839   LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7840 };
7841
7842
7843 class AllocationSite: public Struct {
7844  public:
7845   static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7846   static const double kPretenureRatio;
7847   static const int kPretenureMinimumCreated = 100;
7848
7849   // Values for pretenure decision field.
7850   enum PretenureDecision {
7851     kUndecided = 0,
7852     kDontTenure = 1,
7853     kMaybeTenure = 2,
7854     kTenure = 3,
7855     kZombie = 4,
7856     kLastPretenureDecisionValue = kZombie
7857   };
7858
7859   const char* PretenureDecisionName(PretenureDecision decision);
7860
7861   DECL_ACCESSORS(transition_info, Object)
7862   // nested_site threads a list of sites that represent nested literals
7863   // walked in a particular order. So [[1, 2], 1, 2] will have one
7864   // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7865   DECL_ACCESSORS(nested_site, Object)
7866   DECL_ACCESSORS(pretenure_data, Smi)
7867   DECL_ACCESSORS(pretenure_create_count, Smi)
7868   DECL_ACCESSORS(dependent_code, DependentCode)
7869   DECL_ACCESSORS(weak_next, Object)
7870
7871   inline void Initialize();
7872
7873   // This method is expensive, it should only be called for reporting.
7874   bool IsNestedSite();
7875
7876   // transition_info bitfields, for constructed array transition info.
7877   class ElementsKindBits:       public BitField<ElementsKind, 0,  15> {};
7878   class UnusedBits:             public BitField<int,          15, 14> {};
7879   class DoNotInlineBit:         public BitField<bool,         29,  1> {};
7880
7881   // Bitfields for pretenure_data
7882   class MementoFoundCountBits:  public BitField<int,               0, 26> {};
7883   class PretenureDecisionBits:  public BitField<PretenureDecision, 26, 3> {};
7884   class DeoptDependentCodeBit:  public BitField<bool,              29, 1> {};
7885   STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7886
7887   // Increments the mementos found counter and returns true when the first
7888   // memento was found for a given allocation site.
7889   inline bool IncrementMementoFoundCount();
7890
7891   inline void IncrementMementoCreateCount();
7892
7893   PretenureFlag GetPretenureMode();
7894
7895   void ResetPretenureDecision();
7896
7897   inline PretenureDecision pretenure_decision();
7898   inline void set_pretenure_decision(PretenureDecision decision);
7899
7900   inline bool deopt_dependent_code();
7901   inline void set_deopt_dependent_code(bool deopt);
7902
7903   inline int memento_found_count();
7904   inline void set_memento_found_count(int count);
7905
7906   inline int memento_create_count();
7907   inline void set_memento_create_count(int count);
7908
7909   // The pretenuring decision is made during gc, and the zombie state allows
7910   // us to recognize when an allocation site is just being kept alive because
7911   // a later traversal of new space may discover AllocationMementos that point
7912   // to this AllocationSite.
7913   inline bool IsZombie();
7914
7915   inline bool IsMaybeTenure();
7916
7917   inline void MarkZombie();
7918
7919   inline bool MakePretenureDecision(PretenureDecision current_decision,
7920                                     double ratio,
7921                                     bool maximum_size_scavenge);
7922
7923   inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7924
7925   inline ElementsKind GetElementsKind();
7926   inline void SetElementsKind(ElementsKind kind);
7927
7928   inline bool CanInlineCall();
7929   inline void SetDoNotInlineCall();
7930
7931   inline bool SitePointsToLiteral();
7932
7933   static void DigestTransitionFeedback(Handle<AllocationSite> site,
7934                                        ElementsKind to_kind);
7935
7936   DECLARE_PRINTER(AllocationSite)
7937   DECLARE_VERIFIER(AllocationSite)
7938
7939   DECLARE_CAST(AllocationSite)
7940   static inline AllocationSiteMode GetMode(
7941       ElementsKind boilerplate_elements_kind);
7942   static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7943   static inline bool CanTrack(InstanceType type);
7944
7945   static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7946   static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7947   static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7948   static const int kPretenureCreateCountOffset =
7949       kPretenureDataOffset + kPointerSize;
7950   static const int kDependentCodeOffset =
7951       kPretenureCreateCountOffset + kPointerSize;
7952   static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7953   static const int kSize = kWeakNextOffset + kPointerSize;
7954
7955   // During mark compact we need to take special care for the dependent code
7956   // field.
7957   static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7958   static const int kPointerFieldsEndOffset = kWeakNextOffset;
7959
7960   // For other visitors, use the fixed body descriptor below.
7961   typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7962                               kDependentCodeOffset + kPointerSize,
7963                               kSize> BodyDescriptor;
7964
7965  private:
7966   inline bool PretenuringDecisionMade();
7967
7968   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7969 };
7970
7971
7972 class AllocationMemento: public Struct {
7973  public:
7974   static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7975   static const int kSize = kAllocationSiteOffset + kPointerSize;
7976
7977   DECL_ACCESSORS(allocation_site, Object)
7978
7979   inline bool IsValid();
7980   inline AllocationSite* GetAllocationSite();
7981
7982   DECLARE_PRINTER(AllocationMemento)
7983   DECLARE_VERIFIER(AllocationMemento)
7984
7985   DECLARE_CAST(AllocationMemento)
7986
7987  private:
7988   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7989 };
7990
7991
7992 // Representation of a slow alias as part of a sloppy arguments objects.
7993 // For fast aliases (if HasSloppyArgumentsElements()):
7994 // - the parameter map contains an index into the context
7995 // - all attributes of the element have default values
7996 // For slow aliases (if HasDictionaryArgumentsElements()):
7997 // - the parameter map contains no fast alias mapping (i.e. the hole)
7998 // - this struct (in the slow backing store) contains an index into the context
7999 // - all attributes are available as part if the property details
8000 class AliasedArgumentsEntry: public Struct {
8001  public:
8002   inline int aliased_context_slot() const;
8003   inline void set_aliased_context_slot(int count);
8004
8005   DECLARE_CAST(AliasedArgumentsEntry)
8006
8007   // Dispatched behavior.
8008   DECLARE_PRINTER(AliasedArgumentsEntry)
8009   DECLARE_VERIFIER(AliasedArgumentsEntry)
8010
8011   static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8012   static const int kSize = kAliasedContextSlot + kPointerSize;
8013
8014  private:
8015   DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8016 };
8017
8018
8019 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8020 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8021
8022
8023 class StringHasher {
8024  public:
8025   explicit inline StringHasher(int length, uint32_t seed);
8026
8027   template <typename schar>
8028   static inline uint32_t HashSequentialString(const schar* chars,
8029                                               int length,
8030                                               uint32_t seed);
8031
8032   // Reads all the data, even for long strings and computes the utf16 length.
8033   static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8034                                   uint32_t seed,
8035                                   int* utf16_length_out);
8036
8037   // Calculated hash value for a string consisting of 1 to
8038   // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8039   // value is represented decimal value.
8040   static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8041
8042   // No string is allowed to have a hash of zero.  That value is reserved
8043   // for internal properties.  If the hash calculation yields zero then we
8044   // use 27 instead.
8045   static const int kZeroHash = 27;
8046
8047   // Reusable parts of the hashing algorithm.
8048   INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8049   INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8050   INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8051                                             const uc16* chars, int length));
8052   INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8053                                                    const char* chars,
8054                                                    int length));
8055
8056  protected:
8057   // Returns the value to store in the hash field of a string with
8058   // the given length and contents.
8059   uint32_t GetHashField();
8060   // Returns true if the hash of this string can be computed without
8061   // looking at the contents.
8062   inline bool has_trivial_hash();
8063   // Adds a block of characters to the hash.
8064   template<typename Char>
8065   inline void AddCharacters(const Char* chars, int len);
8066
8067  private:
8068   // Add a character to the hash.
8069   inline void AddCharacter(uint16_t c);
8070   // Update index. Returns true if string is still an index.
8071   inline bool UpdateIndex(uint16_t c);
8072
8073   int length_;
8074   uint32_t raw_running_hash_;
8075   uint32_t array_index_;
8076   bool is_array_index_;
8077   bool is_first_char_;
8078   DISALLOW_COPY_AND_ASSIGN(StringHasher);
8079 };
8080
8081
8082 class IteratingStringHasher : public StringHasher {
8083  public:
8084   static inline uint32_t Hash(String* string, uint32_t seed);
8085   inline void VisitOneByteString(const uint8_t* chars, int length);
8086   inline void VisitTwoByteString(const uint16_t* chars, int length);
8087
8088  private:
8089   inline IteratingStringHasher(int len, uint32_t seed);
8090   void VisitConsString(ConsString* cons_string);
8091   DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8092 };
8093
8094
8095 // The characteristics of a string are stored in its map.  Retrieving these
8096 // few bits of information is moderately expensive, involving two memory
8097 // loads where the second is dependent on the first.  To improve efficiency
8098 // the shape of the string is given its own class so that it can be retrieved
8099 // once and used for several string operations.  A StringShape is small enough
8100 // to be passed by value and is immutable, but be aware that flattening a
8101 // string can potentially alter its shape.  Also be aware that a GC caused by
8102 // something else can alter the shape of a string due to ConsString
8103 // shortcutting.  Keeping these restrictions in mind has proven to be error-
8104 // prone and so we no longer put StringShapes in variables unless there is a
8105 // concrete performance benefit at that particular point in the code.
8106 class StringShape BASE_EMBEDDED {
8107  public:
8108   inline explicit StringShape(const String* s);
8109   inline explicit StringShape(Map* s);
8110   inline explicit StringShape(InstanceType t);
8111   inline bool IsSequential();
8112   inline bool IsExternal();
8113   inline bool IsCons();
8114   inline bool IsSliced();
8115   inline bool IsIndirect();
8116   inline bool IsExternalOneByte();
8117   inline bool IsExternalTwoByte();
8118   inline bool IsSequentialOneByte();
8119   inline bool IsSequentialTwoByte();
8120   inline bool IsInternalized();
8121   inline StringRepresentationTag representation_tag();
8122   inline uint32_t encoding_tag();
8123   inline uint32_t full_representation_tag();
8124   inline uint32_t size_tag();
8125 #ifdef DEBUG
8126   inline uint32_t type() { return type_; }
8127   inline void invalidate() { valid_ = false; }
8128   inline bool valid() { return valid_; }
8129 #else
8130   inline void invalidate() { }
8131 #endif
8132
8133  private:
8134   uint32_t type_;
8135 #ifdef DEBUG
8136   inline void set_valid() { valid_ = true; }
8137   bool valid_;
8138 #else
8139   inline void set_valid() { }
8140 #endif
8141 };
8142
8143
8144 // The Name abstract class captures anything that can be used as a property
8145 // name, i.e., strings and symbols.  All names store a hash value.
8146 class Name: public HeapObject {
8147  public:
8148   // Get and set the hash field of the name.
8149   inline uint32_t hash_field();
8150   inline void set_hash_field(uint32_t value);
8151
8152   // Tells whether the hash code has been computed.
8153   inline bool HasHashCode();
8154
8155   // Returns a hash value used for the property table
8156   inline uint32_t Hash();
8157
8158   // Equality operations.
8159   inline bool Equals(Name* other);
8160   inline static bool Equals(Handle<Name> one, Handle<Name> two);
8161
8162   // Conversion.
8163   inline bool AsArrayIndex(uint32_t* index);
8164
8165   // If the name is private, it can only name own properties.
8166   inline bool IsPrivate();
8167
8168   // If the name is a non-flat string, this method returns a flat version of the
8169   // string. Otherwise it'll just return the input.
8170   static inline Handle<Name> Flatten(Handle<Name> name,
8171                                      PretenureFlag pretenure = NOT_TENURED);
8172
8173   // Return a string version of this name that is converted according to the
8174   // rules described in ES6 section 9.2.11.
8175   MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8176
8177   DECLARE_CAST(Name)
8178
8179   DECLARE_PRINTER(Name)
8180 #if TRACE_MAPS
8181   void NameShortPrint();
8182   int NameShortPrint(Vector<char> str);
8183 #endif
8184
8185   // Layout description.
8186   static const int kHashFieldSlot = HeapObject::kHeaderSize;
8187 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8188   static const int kHashFieldOffset = kHashFieldSlot;
8189 #else
8190   static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8191 #endif
8192   static const int kSize = kHashFieldSlot + kPointerSize;
8193
8194   // Mask constant for checking if a name has a computed hash code
8195   // and if it is a string that is an array index.  The least significant bit
8196   // indicates whether a hash code has been computed.  If the hash code has
8197   // been computed the 2nd bit tells whether the string can be used as an
8198   // array index.
8199   static const int kHashNotComputedMask = 1;
8200   static const int kIsNotArrayIndexMask = 1 << 1;
8201   static const int kNofHashBitFields = 2;
8202
8203   // Shift constant retrieving hash code from hash field.
8204   static const int kHashShift = kNofHashBitFields;
8205
8206   // Only these bits are relevant in the hash, since the top two are shifted
8207   // out.
8208   static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8209
8210   // Array index strings this short can keep their index in the hash field.
8211   static const int kMaxCachedArrayIndexLength = 7;
8212
8213   // For strings which are array indexes the hash value has the string length
8214   // mixed into the hash, mainly to avoid a hash value of zero which would be
8215   // the case for the string '0'. 24 bits are used for the array index value.
8216   static const int kArrayIndexValueBits = 24;
8217   static const int kArrayIndexLengthBits =
8218       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8219
8220   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8221
8222   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8223       kArrayIndexValueBits> {};  // NOLINT
8224   class ArrayIndexLengthBits : public BitField<unsigned int,
8225       kNofHashBitFields + kArrayIndexValueBits,
8226       kArrayIndexLengthBits> {};  // NOLINT
8227
8228   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8229   // could use a mask to test if the length of string is less than or equal to
8230   // kMaxCachedArrayIndexLength.
8231   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8232
8233   static const unsigned int kContainsCachedArrayIndexMask =
8234       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8235        << ArrayIndexLengthBits::kShift) |
8236       kIsNotArrayIndexMask;
8237
8238   // Value of empty hash field indicating that the hash is not computed.
8239   static const int kEmptyHashField =
8240       kIsNotArrayIndexMask | kHashNotComputedMask;
8241
8242  protected:
8243   static inline bool IsHashFieldComputed(uint32_t field);
8244
8245  private:
8246   DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8247 };
8248
8249
8250 // ES6 symbols.
8251 class Symbol: public Name {
8252  public:
8253   // [name]: The print name of a symbol, or undefined if none.
8254   DECL_ACCESSORS(name, Object)
8255
8256   DECL_ACCESSORS(flags, Smi)
8257
8258   // [is_private]: Whether this is a private symbol.  Private symbols can only
8259   // be used to designate own properties of objects.
8260   DECL_BOOLEAN_ACCESSORS(is_private)
8261
8262   DECLARE_CAST(Symbol)
8263
8264   // Dispatched behavior.
8265   DECLARE_PRINTER(Symbol)
8266   DECLARE_VERIFIER(Symbol)
8267
8268   // Layout description.
8269   static const int kNameOffset = Name::kSize;
8270   static const int kFlagsOffset = kNameOffset + kPointerSize;
8271   static const int kSize = kFlagsOffset + kPointerSize;
8272
8273   typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8274
8275   void SymbolShortPrint(std::ostream& os);
8276
8277  private:
8278   static const int kPrivateBit = 0;
8279
8280   const char* PrivateSymbolToName() const;
8281
8282 #if TRACE_MAPS
8283   friend class Name;  // For PrivateSymbolToName.
8284 #endif
8285
8286   DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8287 };
8288
8289
8290 class ConsString;
8291
8292 // The String abstract class captures JavaScript string values:
8293 //
8294 // Ecma-262:
8295 //  4.3.16 String Value
8296 //    A string value is a member of the type String and is a finite
8297 //    ordered sequence of zero or more 16-bit unsigned integer values.
8298 //
8299 // All string values have a length field.
8300 class String: public Name {
8301  public:
8302   enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8303
8304   // Array index strings this short can keep their index in the hash field.
8305   static const int kMaxCachedArrayIndexLength = 7;
8306
8307   // For strings which are array indexes the hash value has the string length
8308   // mixed into the hash, mainly to avoid a hash value of zero which would be
8309   // the case for the string '0'. 24 bits are used for the array index value.
8310   static const int kArrayIndexValueBits = 24;
8311   static const int kArrayIndexLengthBits =
8312       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8313
8314   STATIC_ASSERT((kArrayIndexLengthBits > 0));
8315
8316   class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8317       kArrayIndexValueBits> {};  // NOLINT
8318   class ArrayIndexLengthBits : public BitField<unsigned int,
8319       kNofHashBitFields + kArrayIndexValueBits,
8320       kArrayIndexLengthBits> {};  // NOLINT
8321
8322   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8323   // could use a mask to test if the length of string is less than or equal to
8324   // kMaxCachedArrayIndexLength.
8325   STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8326
8327   static const unsigned int kContainsCachedArrayIndexMask =
8328       (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8329        << ArrayIndexLengthBits::kShift) |
8330       kIsNotArrayIndexMask;
8331
8332   class SubStringRange {
8333    public:
8334     explicit inline SubStringRange(String* string, int first = 0,
8335                                    int length = -1);
8336     class iterator;
8337     inline iterator begin();
8338     inline iterator end();
8339
8340    private:
8341     String* string_;
8342     int first_;
8343     int length_;
8344   };
8345
8346   // Representation of the flat content of a String.
8347   // A non-flat string doesn't have flat content.
8348   // A flat string has content that's encoded as a sequence of either
8349   // one-byte chars or two-byte UC16.
8350   // Returned by String::GetFlatContent().
8351   class FlatContent {
8352    public:
8353     // Returns true if the string is flat and this structure contains content.
8354     bool IsFlat() { return state_ != NON_FLAT; }
8355     // Returns true if the structure contains one-byte content.
8356     bool IsOneByte() { return state_ == ONE_BYTE; }
8357     // Returns true if the structure contains two-byte content.
8358     bool IsTwoByte() { return state_ == TWO_BYTE; }
8359
8360     // Return the one byte content of the string. Only use if IsOneByte()
8361     // returns true.
8362     Vector<const uint8_t> ToOneByteVector() {
8363       DCHECK_EQ(ONE_BYTE, state_);
8364       return Vector<const uint8_t>(onebyte_start, length_);
8365     }
8366     // Return the two-byte content of the string. Only use if IsTwoByte()
8367     // returns true.
8368     Vector<const uc16> ToUC16Vector() {
8369       DCHECK_EQ(TWO_BYTE, state_);
8370       return Vector<const uc16>(twobyte_start, length_);
8371     }
8372
8373     uc16 Get(int i) {
8374       DCHECK(i < length_);
8375       DCHECK(state_ != NON_FLAT);
8376       if (state_ == ONE_BYTE) return onebyte_start[i];
8377       return twobyte_start[i];
8378     }
8379
8380     bool UsesSameString(const FlatContent& other) const {
8381       return onebyte_start == other.onebyte_start;
8382     }
8383
8384    private:
8385     enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8386
8387     // Constructors only used by String::GetFlatContent().
8388     explicit FlatContent(const uint8_t* start, int length)
8389         : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8390     explicit FlatContent(const uc16* start, int length)
8391         : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8392     FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8393
8394     union {
8395       const uint8_t* onebyte_start;
8396       const uc16* twobyte_start;
8397     };
8398     int length_;
8399     State state_;
8400
8401     friend class String;
8402     friend class IterableSubString;
8403   };
8404
8405   template <typename Char>
8406   INLINE(Vector<const Char> GetCharVector());
8407
8408   // Get and set the length of the string.
8409   inline int length() const;
8410   inline void set_length(int value);
8411
8412   // Get and set the length of the string using acquire loads and release
8413   // stores.
8414   inline int synchronized_length() const;
8415   inline void synchronized_set_length(int value);
8416
8417   // Returns whether this string has only one-byte chars, i.e. all of them can
8418   // be one-byte encoded.  This might be the case even if the string is
8419   // two-byte.  Such strings may appear when the embedder prefers
8420   // two-byte external representations even for one-byte data.
8421   inline bool IsOneByteRepresentation() const;
8422   inline bool IsTwoByteRepresentation() const;
8423
8424   // Cons and slices have an encoding flag that may not represent the actual
8425   // encoding of the underlying string.  This is taken into account here.
8426   // Requires: this->IsFlat()
8427   inline bool IsOneByteRepresentationUnderneath();
8428   inline bool IsTwoByteRepresentationUnderneath();
8429
8430   // NOTE: this should be considered only a hint.  False negatives are
8431   // possible.
8432   inline bool HasOnlyOneByteChars();
8433
8434   // Get and set individual two byte chars in the string.
8435   inline void Set(int index, uint16_t value);
8436   // Get individual two byte char in the string.  Repeated calls
8437   // to this method are not efficient unless the string is flat.
8438   INLINE(uint16_t Get(int index));
8439
8440   // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8441   static Handle<Object> ToNumber(Handle<String> subject);
8442
8443   // Flattens the string.  Checks first inline to see if it is
8444   // necessary.  Does nothing if the string is not a cons string.
8445   // Flattening allocates a sequential string with the same data as
8446   // the given string and mutates the cons string to a degenerate
8447   // form, where the first component is the new sequential string and
8448   // the second component is the empty string.  If allocation fails,
8449   // this function returns a failure.  If flattening succeeds, this
8450   // function returns the sequential string that is now the first
8451   // component of the cons string.
8452   //
8453   // Degenerate cons strings are handled specially by the garbage
8454   // collector (see IsShortcutCandidate).
8455
8456   static inline Handle<String> Flatten(Handle<String> string,
8457                                        PretenureFlag pretenure = NOT_TENURED);
8458
8459   // Tries to return the content of a flat string as a structure holding either
8460   // a flat vector of char or of uc16.
8461   // If the string isn't flat, and therefore doesn't have flat content, the
8462   // returned structure will report so, and can't provide a vector of either
8463   // kind.
8464   FlatContent GetFlatContent();
8465
8466   // Returns the parent of a sliced string or first part of a flat cons string.
8467   // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8468   inline String* GetUnderlying();
8469
8470   // String equality operations.
8471   inline bool Equals(String* other);
8472   inline static bool Equals(Handle<String> one, Handle<String> two);
8473   bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8474   bool IsOneByteEqualTo(Vector<const uint8_t> str);
8475   bool IsTwoByteEqualTo(Vector<const uc16> str);
8476
8477   // Return a UTF8 representation of the string.  The string is null
8478   // terminated but may optionally contain nulls.  Length is returned
8479   // in length_output if length_output is not a null pointer  The string
8480   // should be nearly flat, otherwise the performance of this method may
8481   // be very slow (quadratic in the length).  Setting robustness_flag to
8482   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
8483   // handles unexpected data without causing assert failures and it does not
8484   // do any heap allocations.  This is useful when printing stack traces.
8485   base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8486                                           RobustnessFlag robustness_flag,
8487                                           int offset, int length,
8488                                           int* length_output = 0);
8489   base::SmartArrayPointer<char> ToCString(
8490       AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8491       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8492       int* length_output = 0);
8493
8494   // Return a 16 bit Unicode representation of the string.
8495   // The string should be nearly flat, otherwise the performance of
8496   // of this method may be very bad.  Setting robustness_flag to
8497   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
8498   // handles unexpected data without causing assert failures and it does not
8499   // do any heap allocations.  This is useful when printing stack traces.
8500   base::SmartArrayPointer<uc16> ToWideCString(
8501       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8502
8503   bool ComputeArrayIndex(uint32_t* index);
8504
8505   // Externalization.
8506   bool MakeExternal(v8::String::ExternalStringResource* resource);
8507   bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8508
8509   // Conversion.
8510   inline bool AsArrayIndex(uint32_t* index);
8511
8512   DECLARE_CAST(String)
8513
8514   void PrintOn(FILE* out);
8515
8516   // For use during stack traces.  Performs rudimentary sanity check.
8517   bool LooksValid();
8518
8519   // Dispatched behavior.
8520   void StringShortPrint(StringStream* accumulator);
8521   void PrintUC16(std::ostream& os, int start = 0, int end = -1);  // NOLINT
8522 #if defined(DEBUG) || defined(OBJECT_PRINT)
8523   char* ToAsciiArray();
8524 #endif
8525   DECLARE_PRINTER(String)
8526   DECLARE_VERIFIER(String)
8527
8528   inline bool IsFlat();
8529
8530   // Layout description.
8531   static const int kLengthOffset = Name::kSize;
8532   static const int kSize = kLengthOffset + kPointerSize;
8533
8534   // Maximum number of characters to consider when trying to convert a string
8535   // value into an array index.
8536   static const int kMaxArrayIndexSize = 10;
8537   STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8538
8539   // Max char codes.
8540   static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8541   static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8542   static const int kMaxUtf16CodeUnit = 0xffff;
8543   static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8544
8545   // Value of hash field containing computed hash equal to zero.
8546   static const int kEmptyStringHash = kIsNotArrayIndexMask;
8547
8548   // Maximal string length.
8549   static const int kMaxLength = (1 << 28) - 16;
8550
8551   // Max length for computing hash. For strings longer than this limit the
8552   // string length is used as the hash value.
8553   static const int kMaxHashCalcLength = 16383;
8554
8555   // Limit for truncation in short printing.
8556   static const int kMaxShortPrintLength = 1024;
8557
8558   // Support for regular expressions.
8559   const uc16* GetTwoByteData(unsigned start);
8560
8561   // Helper function for flattening strings.
8562   template <typename sinkchar>
8563   static void WriteToFlat(String* source,
8564                           sinkchar* sink,
8565                           int from,
8566                           int to);
8567
8568   // The return value may point to the first aligned word containing the first
8569   // non-one-byte character, rather than directly to the non-one-byte character.
8570   // If the return value is >= the passed length, the entire string was
8571   // one-byte.
8572   static inline int NonAsciiStart(const char* chars, int length) {
8573     const char* start = chars;
8574     const char* limit = chars + length;
8575
8576     if (length >= kIntptrSize) {
8577       // Check unaligned bytes.
8578       while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8579         if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8580           return static_cast<int>(chars - start);
8581         }
8582         ++chars;
8583       }
8584       // Check aligned words.
8585       DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8586       const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8587       while (chars + sizeof(uintptr_t) <= limit) {
8588         if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8589           return static_cast<int>(chars - start);
8590         }
8591         chars += sizeof(uintptr_t);
8592       }
8593     }
8594     // Check remaining unaligned bytes.
8595     while (chars < limit) {
8596       if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8597         return static_cast<int>(chars - start);
8598       }
8599       ++chars;
8600     }
8601
8602     return static_cast<int>(chars - start);
8603   }
8604
8605   static inline bool IsAscii(const char* chars, int length) {
8606     return NonAsciiStart(chars, length) >= length;
8607   }
8608
8609   static inline bool IsAscii(const uint8_t* chars, int length) {
8610     return
8611         NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8612   }
8613
8614   static inline int NonOneByteStart(const uc16* chars, int length) {
8615     const uc16* limit = chars + length;
8616     const uc16* start = chars;
8617     while (chars < limit) {
8618       if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8619       ++chars;
8620     }
8621     return static_cast<int>(chars - start);
8622   }
8623
8624   static inline bool IsOneByte(const uc16* chars, int length) {
8625     return NonOneByteStart(chars, length) >= length;
8626   }
8627
8628   template<class Visitor>
8629   static inline ConsString* VisitFlat(Visitor* visitor,
8630                                       String* string,
8631                                       int offset = 0);
8632
8633   static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8634                                               bool include_ending_line);
8635
8636   // Use the hash field to forward to the canonical internalized string
8637   // when deserializing an internalized string.
8638   inline void SetForwardedInternalizedString(String* string);
8639   inline String* GetForwardedInternalizedString();
8640
8641  private:
8642   friend class Name;
8643   friend class StringTableInsertionKey;
8644
8645   static Handle<String> SlowFlatten(Handle<ConsString> cons,
8646                                     PretenureFlag tenure);
8647
8648   // Slow case of String::Equals.  This implementation works on any strings
8649   // but it is most efficient on strings that are almost flat.
8650   bool SlowEquals(String* other);
8651
8652   static bool SlowEquals(Handle<String> one, Handle<String> two);
8653
8654   // Slow case of AsArrayIndex.
8655   bool SlowAsArrayIndex(uint32_t* index);
8656
8657   // Compute and set the hash code.
8658   uint32_t ComputeAndSetHash();
8659
8660   DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8661 };
8662
8663
8664 // The SeqString abstract class captures sequential string values.
8665 class SeqString: public String {
8666  public:
8667   DECLARE_CAST(SeqString)
8668
8669   // Layout description.
8670   static const int kHeaderSize = String::kSize;
8671
8672   // Truncate the string in-place if possible and return the result.
8673   // In case of new_length == 0, the empty string is returned without
8674   // truncating the original string.
8675   MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8676                                                  int new_length);
8677  private:
8678   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8679 };
8680
8681
8682 // The OneByteString class captures sequential one-byte string objects.
8683 // Each character in the OneByteString is an one-byte character.
8684 class SeqOneByteString: public SeqString {
8685  public:
8686   static const bool kHasOneByteEncoding = true;
8687
8688   // Dispatched behavior.
8689   inline uint16_t SeqOneByteStringGet(int index);
8690   inline void SeqOneByteStringSet(int index, uint16_t value);
8691
8692   // Get the address of the characters in this string.
8693   inline Address GetCharsAddress();
8694
8695   inline uint8_t* GetChars();
8696
8697   DECLARE_CAST(SeqOneByteString)
8698
8699   // Garbage collection support.  This method is called by the
8700   // garbage collector to compute the actual size of an OneByteString
8701   // instance.
8702   inline int SeqOneByteStringSize(InstanceType instance_type);
8703
8704   // Computes the size for an OneByteString instance of a given length.
8705   static int SizeFor(int length) {
8706     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8707   }
8708
8709   // Maximal memory usage for a single sequential one-byte string.
8710   static const int kMaxSize = 512 * MB - 1;
8711   STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8712
8713  private:
8714   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8715 };
8716
8717
8718 // The TwoByteString class captures sequential unicode string objects.
8719 // Each character in the TwoByteString is a two-byte uint16_t.
8720 class SeqTwoByteString: public SeqString {
8721  public:
8722   static const bool kHasOneByteEncoding = false;
8723
8724   // Dispatched behavior.
8725   inline uint16_t SeqTwoByteStringGet(int index);
8726   inline void SeqTwoByteStringSet(int index, uint16_t value);
8727
8728   // Get the address of the characters in this string.
8729   inline Address GetCharsAddress();
8730
8731   inline uc16* GetChars();
8732
8733   // For regexp code.
8734   const uint16_t* SeqTwoByteStringGetData(unsigned start);
8735
8736   DECLARE_CAST(SeqTwoByteString)
8737
8738   // Garbage collection support.  This method is called by the
8739   // garbage collector to compute the actual size of a TwoByteString
8740   // instance.
8741   inline int SeqTwoByteStringSize(InstanceType instance_type);
8742
8743   // Computes the size for a TwoByteString instance of a given length.
8744   static int SizeFor(int length) {
8745     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8746   }
8747
8748   // Maximal memory usage for a single sequential two-byte string.
8749   static const int kMaxSize = 512 * MB - 1;
8750   STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8751                String::kMaxLength);
8752
8753  private:
8754   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8755 };
8756
8757
8758 // The ConsString class describes string values built by using the
8759 // addition operator on strings.  A ConsString is a pair where the
8760 // first and second components are pointers to other string values.
8761 // One or both components of a ConsString can be pointers to other
8762 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8763 // are non-ConsString string values.  The string value represented by
8764 // a ConsString can be obtained by concatenating the leaf string
8765 // values in a left-to-right depth-first traversal of the tree.
8766 class ConsString: public String {
8767  public:
8768   // First string of the cons cell.
8769   inline String* first();
8770   // Doesn't check that the result is a string, even in debug mode.  This is
8771   // useful during GC where the mark bits confuse the checks.
8772   inline Object* unchecked_first();
8773   inline void set_first(String* first,
8774                         WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8775
8776   // Second string of the cons cell.
8777   inline String* second();
8778   // Doesn't check that the result is a string, even in debug mode.  This is
8779   // useful during GC where the mark bits confuse the checks.
8780   inline Object* unchecked_second();
8781   inline void set_second(String* second,
8782                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8783
8784   // Dispatched behavior.
8785   uint16_t ConsStringGet(int index);
8786
8787   DECLARE_CAST(ConsString)
8788
8789   // Layout description.
8790   static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8791   static const int kSecondOffset = kFirstOffset + kPointerSize;
8792   static const int kSize = kSecondOffset + kPointerSize;
8793
8794   // Minimum length for a cons string.
8795   static const int kMinLength = 13;
8796
8797   typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8798           BodyDescriptor;
8799
8800   DECLARE_VERIFIER(ConsString)
8801
8802  private:
8803   DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8804 };
8805
8806
8807 // The Sliced String class describes strings that are substrings of another
8808 // sequential string.  The motivation is to save time and memory when creating
8809 // a substring.  A Sliced String is described as a pointer to the parent,
8810 // the offset from the start of the parent string and the length.  Using
8811 // a Sliced String therefore requires unpacking of the parent string and
8812 // adding the offset to the start address.  A substring of a Sliced String
8813 // are not nested since the double indirection is simplified when creating
8814 // such a substring.
8815 // Currently missing features are:
8816 //  - handling externalized parent strings
8817 //  - external strings as parent
8818 //  - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8819 class SlicedString: public String {
8820  public:
8821   inline String* parent();
8822   inline void set_parent(String* parent,
8823                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8824   inline int offset() const;
8825   inline void set_offset(int offset);
8826
8827   // Dispatched behavior.
8828   uint16_t SlicedStringGet(int index);
8829
8830   DECLARE_CAST(SlicedString)
8831
8832   // Layout description.
8833   static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8834   static const int kOffsetOffset = kParentOffset + kPointerSize;
8835   static const int kSize = kOffsetOffset + kPointerSize;
8836
8837   // Minimum length for a sliced string.
8838   static const int kMinLength = 13;
8839
8840   typedef FixedBodyDescriptor<kParentOffset,
8841                               kOffsetOffset + kPointerSize, kSize>
8842           BodyDescriptor;
8843
8844   DECLARE_VERIFIER(SlicedString)
8845
8846  private:
8847   DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8848 };
8849
8850
8851 // The ExternalString class describes string values that are backed by
8852 // a string resource that lies outside the V8 heap.  ExternalStrings
8853 // consist of the length field common to all strings, a pointer to the
8854 // external resource.  It is important to ensure (externally) that the
8855 // resource is not deallocated while the ExternalString is live in the
8856 // V8 heap.
8857 //
8858 // The API expects that all ExternalStrings are created through the
8859 // API.  Therefore, ExternalStrings should not be used internally.
8860 class ExternalString: public String {
8861  public:
8862   DECLARE_CAST(ExternalString)
8863
8864   // Layout description.
8865   static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8866   static const int kShortSize = kResourceOffset + kPointerSize;
8867   static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8868   static const int kSize = kResourceDataOffset + kPointerSize;
8869
8870   static const int kMaxShortLength =
8871       (kShortSize - SeqString::kHeaderSize) / kCharSize;
8872
8873   // Return whether external string is short (data pointer is not cached).
8874   inline bool is_short();
8875
8876   STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8877
8878  private:
8879   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8880 };
8881
8882
8883 // The ExternalOneByteString class is an external string backed by an
8884 // one-byte string.
8885 class ExternalOneByteString : public ExternalString {
8886  public:
8887   static const bool kHasOneByteEncoding = true;
8888
8889   typedef v8::String::ExternalOneByteStringResource Resource;
8890
8891   // The underlying resource.
8892   inline const Resource* resource();
8893   inline void set_resource(const Resource* buffer);
8894
8895   // Update the pointer cache to the external character array.
8896   // The cached pointer is always valid, as the external character array does =
8897   // not move during lifetime.  Deserialization is the only exception, after
8898   // which the pointer cache has to be refreshed.
8899   inline void update_data_cache();
8900
8901   inline const uint8_t* GetChars();
8902
8903   // Dispatched behavior.
8904   inline uint16_t ExternalOneByteStringGet(int index);
8905
8906   DECLARE_CAST(ExternalOneByteString)
8907
8908   // Garbage collection support.
8909   inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8910
8911   template <typename StaticVisitor>
8912   inline void ExternalOneByteStringIterateBody();
8913
8914  private:
8915   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8916 };
8917
8918
8919 // The ExternalTwoByteString class is an external string backed by a UTF-16
8920 // encoded string.
8921 class ExternalTwoByteString: public ExternalString {
8922  public:
8923   static const bool kHasOneByteEncoding = false;
8924
8925   typedef v8::String::ExternalStringResource Resource;
8926
8927   // The underlying string resource.
8928   inline const Resource* resource();
8929   inline void set_resource(const Resource* buffer);
8930
8931   // Update the pointer cache to the external character array.
8932   // The cached pointer is always valid, as the external character array does =
8933   // not move during lifetime.  Deserialization is the only exception, after
8934   // which the pointer cache has to be refreshed.
8935   inline void update_data_cache();
8936
8937   inline const uint16_t* GetChars();
8938
8939   // Dispatched behavior.
8940   inline uint16_t ExternalTwoByteStringGet(int index);
8941
8942   // For regexp code.
8943   inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8944
8945   DECLARE_CAST(ExternalTwoByteString)
8946
8947   // Garbage collection support.
8948   inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8949
8950   template<typename StaticVisitor>
8951   inline void ExternalTwoByteStringIterateBody();
8952
8953  private:
8954   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8955 };
8956
8957
8958 // Utility superclass for stack-allocated objects that must be updated
8959 // on gc.  It provides two ways for the gc to update instances, either
8960 // iterating or updating after gc.
8961 class Relocatable BASE_EMBEDDED {
8962  public:
8963   explicit inline Relocatable(Isolate* isolate);
8964   inline virtual ~Relocatable();
8965   virtual void IterateInstance(ObjectVisitor* v) { }
8966   virtual void PostGarbageCollection() { }
8967
8968   static void PostGarbageCollectionProcessing(Isolate* isolate);
8969   static int ArchiveSpacePerThread();
8970   static char* ArchiveState(Isolate* isolate, char* to);
8971   static char* RestoreState(Isolate* isolate, char* from);
8972   static void Iterate(Isolate* isolate, ObjectVisitor* v);
8973   static void Iterate(ObjectVisitor* v, Relocatable* top);
8974   static char* Iterate(ObjectVisitor* v, char* t);
8975
8976  private:
8977   Isolate* isolate_;
8978   Relocatable* prev_;
8979 };
8980
8981
8982 // A flat string reader provides random access to the contents of a
8983 // string independent of the character width of the string.  The handle
8984 // must be valid as long as the reader is being used.
8985 class FlatStringReader : public Relocatable {
8986  public:
8987   FlatStringReader(Isolate* isolate, Handle<String> str);
8988   FlatStringReader(Isolate* isolate, Vector<const char> input);
8989   void PostGarbageCollection();
8990   inline uc32 Get(int index);
8991   template <typename Char>
8992   inline Char Get(int index);
8993   int length() { return length_; }
8994  private:
8995   String** str_;
8996   bool is_one_byte_;
8997   int length_;
8998   const void* start_;
8999 };
9000
9001
9002 // This maintains an off-stack representation of the stack frames required
9003 // to traverse a ConsString, allowing an entirely iterative and restartable
9004 // traversal of the entire string
9005 class ConsStringIterator {
9006  public:
9007   inline ConsStringIterator() {}
9008   inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9009     Reset(cons_string, offset);
9010   }
9011   inline void Reset(ConsString* cons_string, int offset = 0) {
9012     depth_ = 0;
9013     // Next will always return NULL.
9014     if (cons_string == NULL) return;
9015     Initialize(cons_string, offset);
9016   }
9017   // Returns NULL when complete.
9018   inline String* Next(int* offset_out) {
9019     *offset_out = 0;
9020     if (depth_ == 0) return NULL;
9021     return Continue(offset_out);
9022   }
9023
9024  private:
9025   static const int kStackSize = 32;
9026   // Use a mask instead of doing modulo operations for stack wrapping.
9027   static const int kDepthMask = kStackSize-1;
9028   STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9029   static inline int OffsetForDepth(int depth);
9030
9031   inline void PushLeft(ConsString* string);
9032   inline void PushRight(ConsString* string);
9033   inline void AdjustMaximumDepth();
9034   inline void Pop();
9035   inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9036   void Initialize(ConsString* cons_string, int offset);
9037   String* Continue(int* offset_out);
9038   String* NextLeaf(bool* blew_stack);
9039   String* Search(int* offset_out);
9040
9041   // Stack must always contain only frames for which right traversal
9042   // has not yet been performed.
9043   ConsString* frames_[kStackSize];
9044   ConsString* root_;
9045   int depth_;
9046   int maximum_depth_;
9047   int consumed_;
9048   DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9049 };
9050
9051
9052 class StringCharacterStream {
9053  public:
9054   inline StringCharacterStream(String* string,
9055                                int offset = 0);
9056   inline uint16_t GetNext();
9057   inline bool HasMore();
9058   inline void Reset(String* string, int offset = 0);
9059   inline void VisitOneByteString(const uint8_t* chars, int length);
9060   inline void VisitTwoByteString(const uint16_t* chars, int length);
9061
9062  private:
9063   ConsStringIterator iter_;
9064   bool is_one_byte_;
9065   union {
9066     const uint8_t* buffer8_;
9067     const uint16_t* buffer16_;
9068   };
9069   const uint8_t* end_;
9070   DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9071 };
9072
9073
9074 template <typename T>
9075 class VectorIterator {
9076  public:
9077   VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9078   explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9079   T GetNext() { return data_[index_++]; }
9080   bool has_more() { return index_ < data_.length(); }
9081  private:
9082   Vector<const T> data_;
9083   int index_;
9084 };
9085
9086
9087 // The Oddball describes objects null, undefined, true, and false.
9088 class Oddball: public HeapObject {
9089  public:
9090   // [to_string]: Cached to_string computed at startup.
9091   DECL_ACCESSORS(to_string, String)
9092
9093   // [to_number]: Cached to_number computed at startup.
9094   DECL_ACCESSORS(to_number, Object)
9095
9096   // [typeof]: Cached type_of computed at startup.
9097   DECL_ACCESSORS(type_of, String)
9098
9099   inline byte kind() const;
9100   inline void set_kind(byte kind);
9101
9102   DECLARE_CAST(Oddball)
9103
9104   // Dispatched behavior.
9105   DECLARE_VERIFIER(Oddball)
9106
9107   // Initialize the fields.
9108   static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9109                          const char* to_string, Handle<Object> to_number,
9110                          const char* type_of, byte kind);
9111
9112   // Layout description.
9113   static const int kToStringOffset = HeapObject::kHeaderSize;
9114   static const int kToNumberOffset = kToStringOffset + kPointerSize;
9115   static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9116   static const int kKindOffset = kTypeOfOffset + kPointerSize;
9117   static const int kSize = kKindOffset + kPointerSize;
9118
9119   static const byte kFalse = 0;
9120   static const byte kTrue = 1;
9121   static const byte kNotBooleanMask = ~1;
9122   static const byte kTheHole = 2;
9123   static const byte kNull = 3;
9124   static const byte kArgumentMarker = 4;
9125   static const byte kUndefined = 5;
9126   static const byte kUninitialized = 6;
9127   static const byte kOther = 7;
9128   static const byte kException = 8;
9129
9130   typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9131                               kSize> BodyDescriptor;
9132
9133   STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9134   STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9135   STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9136
9137  private:
9138   DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9139 };
9140
9141
9142 class Cell: public HeapObject {
9143  public:
9144   // [value]: value of the cell.
9145   DECL_ACCESSORS(value, Object)
9146
9147   DECLARE_CAST(Cell)
9148
9149   static inline Cell* FromValueAddress(Address value) {
9150     Object* result = FromAddress(value - kValueOffset);
9151     return static_cast<Cell*>(result);
9152   }
9153
9154   inline Address ValueAddress() {
9155     return address() + kValueOffset;
9156   }
9157
9158   // Dispatched behavior.
9159   DECLARE_PRINTER(Cell)
9160   DECLARE_VERIFIER(Cell)
9161
9162   // Layout description.
9163   static const int kValueOffset = HeapObject::kHeaderSize;
9164   static const int kSize = kValueOffset + kPointerSize;
9165
9166   typedef FixedBodyDescriptor<kValueOffset,
9167                               kValueOffset + kPointerSize,
9168                               kSize> BodyDescriptor;
9169
9170  private:
9171   DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9172 };
9173
9174
9175 class PropertyCell : public HeapObject {
9176  public:
9177   // [property_details]: details of the global property.
9178   DECL_ACCESSORS(property_details_raw, Object)
9179   // [value]: value of the global property.
9180   DECL_ACCESSORS(value, Object)
9181   // [dependent_code]: dependent code that depends on the type of the global
9182   // property.
9183   DECL_ACCESSORS(dependent_code, DependentCode)
9184
9185   inline PropertyDetails property_details();
9186   inline void set_property_details(PropertyDetails details);
9187
9188   PropertyCellConstantType GetConstantType();
9189
9190   // Computes the new type of the cell's contents for the given value, but
9191   // without actually modifying the details.
9192   static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9193                                       Handle<Object> value,
9194                                       PropertyDetails details);
9195   static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9196                          Handle<Object> value, PropertyDetails details);
9197
9198   static Handle<PropertyCell> InvalidateEntry(
9199       Handle<GlobalDictionary> dictionary, int entry);
9200
9201   static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9202                                        Handle<Object> new_value);
9203
9204   DECLARE_CAST(PropertyCell)
9205
9206   // Dispatched behavior.
9207   DECLARE_PRINTER(PropertyCell)
9208   DECLARE_VERIFIER(PropertyCell)
9209
9210   // Layout description.
9211   static const int kDetailsOffset = HeapObject::kHeaderSize;
9212   static const int kValueOffset = kDetailsOffset + kPointerSize;
9213   static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9214   static const int kSize = kDependentCodeOffset + kPointerSize;
9215
9216   static const int kPointerFieldsBeginOffset = kValueOffset;
9217   static const int kPointerFieldsEndOffset = kSize;
9218
9219   typedef FixedBodyDescriptor<kValueOffset,
9220                               kSize,
9221                               kSize> BodyDescriptor;
9222
9223  private:
9224   DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9225 };
9226
9227
9228 class WeakCell : public HeapObject {
9229  public:
9230   inline Object* value() const;
9231
9232   // This should not be called by anyone except GC.
9233   inline void clear();
9234
9235   // This should not be called by anyone except allocator.
9236   inline void initialize(HeapObject* value);
9237
9238   inline bool cleared() const;
9239
9240   DECL_ACCESSORS(next, Object)
9241
9242   inline void clear_next(Heap* heap);
9243
9244   inline bool next_cleared();
9245
9246   DECLARE_CAST(WeakCell)
9247
9248   DECLARE_PRINTER(WeakCell)
9249   DECLARE_VERIFIER(WeakCell)
9250
9251   // Layout description.
9252   static const int kValueOffset = HeapObject::kHeaderSize;
9253   static const int kNextOffset = kValueOffset + kPointerSize;
9254   static const int kSize = kNextOffset + kPointerSize;
9255
9256   typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9257
9258  private:
9259   DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9260 };
9261
9262
9263 // The JSProxy describes EcmaScript Harmony proxies
9264 class JSProxy: public JSReceiver {
9265  public:
9266   // [handler]: The handler property.
9267   DECL_ACCESSORS(handler, Object)
9268
9269   // [hash]: The hash code property (undefined if not initialized yet).
9270   DECL_ACCESSORS(hash, Object)
9271
9272   DECLARE_CAST(JSProxy)
9273
9274   MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9275       Handle<JSProxy> proxy,
9276       Handle<Object> receiver,
9277       Handle<Name> name);
9278
9279   // If the handler defines an accessor property with a setter, invoke it.
9280   // If it defines an accessor property without a setter, or a data property
9281   // that is read-only, throw. In all these cases set '*done' to true,
9282   // otherwise set it to false.
9283   MUST_USE_RESULT
9284   static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9285       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9286       Handle<Object> value, LanguageMode language_mode, bool* done);
9287
9288   MUST_USE_RESULT static Maybe<PropertyAttributes>
9289       GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9290                                        Handle<Object> receiver,
9291                                        Handle<Name> name);
9292   MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9293       Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9294       Handle<Object> value, LanguageMode language_mode);
9295
9296   // Turn the proxy into an (empty) JSObject.
9297   static void Fix(Handle<JSProxy> proxy);
9298
9299   // Initializes the body after the handler slot.
9300   inline void InitializeBody(int object_size, Object* value);
9301
9302   // Invoke a trap by name. If the trap does not exist on this's handler,
9303   // but derived_trap is non-NULL, invoke that instead.  May cause GC.
9304   MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9305       Handle<JSProxy> proxy,
9306       const char* name,
9307       Handle<Object> derived_trap,
9308       int argc,
9309       Handle<Object> args[]);
9310
9311   // Dispatched behavior.
9312   DECLARE_PRINTER(JSProxy)
9313   DECLARE_VERIFIER(JSProxy)
9314
9315   // Layout description. We add padding so that a proxy has the same
9316   // size as a virgin JSObject. This is essential for becoming a JSObject
9317   // upon freeze.
9318   static const int kHandlerOffset = HeapObject::kHeaderSize;
9319   static const int kHashOffset = kHandlerOffset + kPointerSize;
9320   static const int kPaddingOffset = kHashOffset + kPointerSize;
9321   static const int kSize = JSObject::kHeaderSize;
9322   static const int kHeaderSize = kPaddingOffset;
9323   static const int kPaddingSize = kSize - kPaddingOffset;
9324
9325   STATIC_ASSERT(kPaddingSize >= 0);
9326
9327   typedef FixedBodyDescriptor<kHandlerOffset,
9328                               kPaddingOffset,
9329                               kSize> BodyDescriptor;
9330
9331  private:
9332   friend class JSReceiver;
9333
9334   MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9335       Handle<JSProxy> proxy, Handle<Name> name);
9336
9337   MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9338       Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9339
9340   MUST_USE_RESULT Object* GetIdentityHash();
9341
9342   static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9343
9344   DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9345 };
9346
9347
9348 class JSFunctionProxy: public JSProxy {
9349  public:
9350   // [call_trap]: The call trap.
9351   DECL_ACCESSORS(call_trap, JSReceiver)
9352
9353   // [construct_trap]: The construct trap.
9354   DECL_ACCESSORS(construct_trap, Object)
9355
9356   DECLARE_CAST(JSFunctionProxy)
9357
9358   // Dispatched behavior.
9359   DECLARE_PRINTER(JSFunctionProxy)
9360   DECLARE_VERIFIER(JSFunctionProxy)
9361
9362   // Layout description.
9363   static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9364   static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9365   static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9366   static const int kSize = JSFunction::kSize;
9367   static const int kPaddingSize = kSize - kPaddingOffset;
9368
9369   STATIC_ASSERT(kPaddingSize >= 0);
9370
9371   typedef FixedBodyDescriptor<kHandlerOffset,
9372                               kConstructTrapOffset + kPointerSize,
9373                               kSize> BodyDescriptor;
9374
9375  private:
9376   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9377 };
9378
9379
9380 class JSCollection : public JSObject {
9381  public:
9382   // [table]: the backing hash table
9383   DECL_ACCESSORS(table, Object)
9384
9385   static const int kTableOffset = JSObject::kHeaderSize;
9386   static const int kSize = kTableOffset + kPointerSize;
9387
9388  private:
9389   DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9390 };
9391
9392
9393 // The JSSet describes EcmaScript Harmony sets
9394 class JSSet : public JSCollection {
9395  public:
9396   DECLARE_CAST(JSSet)
9397
9398   static void Initialize(Handle<JSSet> set, Isolate* isolate);
9399   static void Clear(Handle<JSSet> set);
9400
9401   // Dispatched behavior.
9402   DECLARE_PRINTER(JSSet)
9403   DECLARE_VERIFIER(JSSet)
9404
9405  private:
9406   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9407 };
9408
9409
9410 // The JSMap describes EcmaScript Harmony maps
9411 class JSMap : public JSCollection {
9412  public:
9413   DECLARE_CAST(JSMap)
9414
9415   static void Initialize(Handle<JSMap> map, Isolate* isolate);
9416   static void Clear(Handle<JSMap> map);
9417
9418   // Dispatched behavior.
9419   DECLARE_PRINTER(JSMap)
9420   DECLARE_VERIFIER(JSMap)
9421
9422  private:
9423   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9424 };
9425
9426
9427 // OrderedHashTableIterator is an iterator that iterates over the keys and
9428 // values of an OrderedHashTable.
9429 //
9430 // The iterator has a reference to the underlying OrderedHashTable data,
9431 // [table], as well as the current [index] the iterator is at.
9432 //
9433 // When the OrderedHashTable is rehashed it adds a reference from the old table
9434 // to the new table as well as storing enough data about the changes so that the
9435 // iterator [index] can be adjusted accordingly.
9436 //
9437 // When the [Next] result from the iterator is requested, the iterator checks if
9438 // there is a newer table that it needs to transition to.
9439 template<class Derived, class TableType>
9440 class OrderedHashTableIterator: public JSObject {
9441  public:
9442   // [table]: the backing hash table mapping keys to values.
9443   DECL_ACCESSORS(table, Object)
9444
9445   // [index]: The index into the data table.
9446   DECL_ACCESSORS(index, Object)
9447
9448   // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9449   DECL_ACCESSORS(kind, Object)
9450
9451 #ifdef OBJECT_PRINT
9452   void OrderedHashTableIteratorPrint(std::ostream& os);  // NOLINT
9453 #endif
9454
9455   static const int kTableOffset = JSObject::kHeaderSize;
9456   static const int kIndexOffset = kTableOffset + kPointerSize;
9457   static const int kKindOffset = kIndexOffset + kPointerSize;
9458   static const int kSize = kKindOffset + kPointerSize;
9459
9460   enum Kind {
9461     kKindKeys = 1,
9462     kKindValues = 2,
9463     kKindEntries = 3
9464   };
9465
9466   // Whether the iterator has more elements. This needs to be called before
9467   // calling |CurrentKey| and/or |CurrentValue|.
9468   bool HasMore();
9469
9470   // Move the index forward one.
9471   void MoveNext() {
9472     set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9473   }
9474
9475   // Populates the array with the next key and value and then moves the iterator
9476   // forward.
9477   // This returns the |kind| or 0 if the iterator is already at the end.
9478   Smi* Next(JSArray* value_array);
9479
9480   // Returns the current key of the iterator. This should only be called when
9481   // |HasMore| returns true.
9482   inline Object* CurrentKey();
9483
9484  private:
9485   // Transitions the iterator to the non obsolete backing store. This is a NOP
9486   // if the [table] is not obsolete.
9487   void Transition();
9488
9489   DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9490 };
9491
9492
9493 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9494                                                      OrderedHashSet> {
9495  public:
9496   // Dispatched behavior.
9497   DECLARE_PRINTER(JSSetIterator)
9498   DECLARE_VERIFIER(JSSetIterator)
9499
9500   DECLARE_CAST(JSSetIterator)
9501
9502   // Called by |Next| to populate the array. This allows the subclasses to
9503   // populate the array differently.
9504   inline void PopulateValueArray(FixedArray* array);
9505
9506  private:
9507   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9508 };
9509
9510
9511 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9512                                                      OrderedHashMap> {
9513  public:
9514   // Dispatched behavior.
9515   DECLARE_PRINTER(JSMapIterator)
9516   DECLARE_VERIFIER(JSMapIterator)
9517
9518   DECLARE_CAST(JSMapIterator)
9519
9520   // Called by |Next| to populate the array. This allows the subclasses to
9521   // populate the array differently.
9522   inline void PopulateValueArray(FixedArray* array);
9523
9524  private:
9525   // Returns the current value of the iterator. This should only be called when
9526   // |HasMore| returns true.
9527   inline Object* CurrentValue();
9528
9529   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9530 };
9531
9532
9533 // ES6 section 25.1.1.3 The IteratorResult Interface
9534 class JSIteratorResult final : public JSObject {
9535  public:
9536   // [done]: This is the result status of an iterator next method call.  If the
9537   // end of the iterator was reached done is true.  If the end was not reached
9538   // done is false and a [value] is available.
9539   DECL_ACCESSORS(done, Object)
9540
9541   // [value]: If [done] is false, this is the current iteration element value.
9542   // If [done] is true, this is the return value of the iterator, if it supplied
9543   // one.  If the iterator does not have a return value, value is undefined.
9544   // In that case, the value property may be absent from the conforming object
9545   // if it does not inherit an explicit value property.
9546   DECL_ACCESSORS(value, Object)
9547
9548   // Dispatched behavior.
9549   DECLARE_PRINTER(JSIteratorResult)
9550   DECLARE_VERIFIER(JSIteratorResult)
9551
9552   DECLARE_CAST(JSIteratorResult)
9553
9554   static const int kValueOffset = JSObject::kHeaderSize;
9555   static const int kDoneOffset = kValueOffset + kPointerSize;
9556   static const int kSize = kDoneOffset + kPointerSize;
9557
9558   // Indices of in-object properties.
9559   static const int kValueIndex = 0;
9560   static const int kDoneIndex = 1;
9561
9562  private:
9563   DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9564 };
9565
9566
9567 // Base class for both JSWeakMap and JSWeakSet
9568 class JSWeakCollection: public JSObject {
9569  public:
9570   // [table]: the backing hash table mapping keys to values.
9571   DECL_ACCESSORS(table, Object)
9572
9573   // [next]: linked list of encountered weak maps during GC.
9574   DECL_ACCESSORS(next, Object)
9575
9576   static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9577   static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9578                   Handle<Object> value, int32_t hash);
9579   static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9580                      int32_t hash);
9581
9582   static const int kTableOffset = JSObject::kHeaderSize;
9583   static const int kNextOffset = kTableOffset + kPointerSize;
9584   static const int kSize = kNextOffset + kPointerSize;
9585
9586  private:
9587   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9588 };
9589
9590
9591 // The JSWeakMap describes EcmaScript Harmony weak maps
9592 class JSWeakMap: public JSWeakCollection {
9593  public:
9594   DECLARE_CAST(JSWeakMap)
9595
9596   // Dispatched behavior.
9597   DECLARE_PRINTER(JSWeakMap)
9598   DECLARE_VERIFIER(JSWeakMap)
9599
9600  private:
9601   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9602 };
9603
9604
9605 // The JSWeakSet describes EcmaScript Harmony weak sets
9606 class JSWeakSet: public JSWeakCollection {
9607  public:
9608   DECLARE_CAST(JSWeakSet)
9609
9610   // Dispatched behavior.
9611   DECLARE_PRINTER(JSWeakSet)
9612   DECLARE_VERIFIER(JSWeakSet)
9613
9614  private:
9615   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9616 };
9617
9618
9619 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9620 enum class SharedFlag { kNotShared, kShared };
9621
9622
9623 class JSArrayBuffer: public JSObject {
9624  public:
9625   // [backing_store]: backing memory for this array
9626   DECL_ACCESSORS(backing_store, void)
9627
9628   // [byte_length]: length in bytes
9629   DECL_ACCESSORS(byte_length, Object)
9630
9631   inline uint32_t bit_field() const;
9632   inline void set_bit_field(uint32_t bits);
9633
9634   inline bool is_external();
9635   inline void set_is_external(bool value);
9636
9637   inline bool is_neuterable();
9638   inline void set_is_neuterable(bool value);
9639
9640   inline bool was_neutered();
9641   inline void set_was_neutered(bool value);
9642
9643   inline bool is_shared();
9644   inline void set_is_shared(bool value);
9645
9646   DECLARE_CAST(JSArrayBuffer)
9647
9648   void Neuter();
9649
9650   static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9651                     bool is_external, void* data, size_t allocated_length,
9652                     SharedFlag shared = SharedFlag::kNotShared);
9653
9654   static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9655                                   Isolate* isolate, size_t allocated_length,
9656                                   bool initialize = true,
9657                                   SharedFlag shared = SharedFlag::kNotShared);
9658
9659   // Dispatched behavior.
9660   DECLARE_PRINTER(JSArrayBuffer)
9661   DECLARE_VERIFIER(JSArrayBuffer)
9662
9663   static const int kBackingStoreOffset = JSObject::kHeaderSize;
9664   static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9665   static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9666 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9667   static const int kBitFieldOffset = kBitFieldSlot;
9668 #else
9669   static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9670 #endif
9671   static const int kSize = kBitFieldSlot + kPointerSize;
9672
9673   static const int kSizeWithInternalFields =
9674       kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9675
9676   class IsExternal : public BitField<bool, 1, 1> {};
9677   class IsNeuterable : public BitField<bool, 2, 1> {};
9678   class WasNeutered : public BitField<bool, 3, 1> {};
9679   class IsShared : public BitField<bool, 4, 1> {};
9680
9681  private:
9682   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9683 };
9684
9685
9686 class JSArrayBufferView: public JSObject {
9687  public:
9688   // [buffer]: ArrayBuffer that this typed array views.
9689   DECL_ACCESSORS(buffer, Object)
9690
9691   // [byte_offset]: offset of typed array in bytes.
9692   DECL_ACCESSORS(byte_offset, Object)
9693
9694   // [byte_length]: length of typed array in bytes.
9695   DECL_ACCESSORS(byte_length, Object)
9696
9697   DECLARE_CAST(JSArrayBufferView)
9698
9699   DECLARE_VERIFIER(JSArrayBufferView)
9700
9701   inline bool WasNeutered() const;
9702
9703   static const int kBufferOffset = JSObject::kHeaderSize;
9704   static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9705   static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9706   static const int kViewSize = kByteLengthOffset + kPointerSize;
9707
9708  private:
9709 #ifdef VERIFY_HEAP
9710   DECL_ACCESSORS(raw_byte_offset, Object)
9711   DECL_ACCESSORS(raw_byte_length, Object)
9712 #endif
9713
9714   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9715 };
9716
9717
9718 class JSTypedArray: public JSArrayBufferView {
9719  public:
9720   // [length]: length of typed array in elements.
9721   DECL_ACCESSORS(length, Object)
9722   inline uint32_t length_value() const;
9723
9724   DECLARE_CAST(JSTypedArray)
9725
9726   ExternalArrayType type();
9727   size_t element_size();
9728
9729   Handle<JSArrayBuffer> GetBuffer();
9730
9731   // Dispatched behavior.
9732   DECLARE_PRINTER(JSTypedArray)
9733   DECLARE_VERIFIER(JSTypedArray)
9734
9735   static const int kLengthOffset = kViewSize + kPointerSize;
9736   static const int kSize = kLengthOffset + kPointerSize;
9737
9738   static const int kSizeWithInternalFields =
9739       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9740
9741  private:
9742   static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9743       Handle<JSTypedArray> typed_array);
9744 #ifdef VERIFY_HEAP
9745   DECL_ACCESSORS(raw_length, Object)
9746 #endif
9747
9748   DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9749 };
9750
9751
9752 class JSDataView: public JSArrayBufferView {
9753  public:
9754   DECLARE_CAST(JSDataView)
9755
9756   // Dispatched behavior.
9757   DECLARE_PRINTER(JSDataView)
9758   DECLARE_VERIFIER(JSDataView)
9759
9760   static const int kSize = kViewSize;
9761
9762   static const int kSizeWithInternalFields =
9763       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9764
9765  private:
9766   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9767 };
9768
9769
9770 // Foreign describes objects pointing from JavaScript to C structures.
9771 class Foreign: public HeapObject {
9772  public:
9773   // [address]: field containing the address.
9774   inline Address foreign_address();
9775   inline void set_foreign_address(Address value);
9776
9777   DECLARE_CAST(Foreign)
9778
9779   // Dispatched behavior.
9780   inline void ForeignIterateBody(ObjectVisitor* v);
9781
9782   template<typename StaticVisitor>
9783   inline void ForeignIterateBody();
9784
9785   // Dispatched behavior.
9786   DECLARE_PRINTER(Foreign)
9787   DECLARE_VERIFIER(Foreign)
9788
9789   // Layout description.
9790
9791   static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9792   static const int kSize = kForeignAddressOffset + kPointerSize;
9793
9794   STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9795
9796  private:
9797   DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9798 };
9799
9800
9801 // The JSArray describes JavaScript Arrays
9802 //  Such an array can be in one of two modes:
9803 //    - fast, backing storage is a FixedArray and length <= elements.length();
9804 //       Please note: push and pop can be used to grow and shrink the array.
9805 //    - slow, backing storage is a HashTable with numbers as keys.
9806 class JSArray: public JSObject {
9807  public:
9808   // [length]: The length property.
9809   DECL_ACCESSORS(length, Object)
9810
9811   // Overload the length setter to skip write barrier when the length
9812   // is set to a smi. This matches the set function on FixedArray.
9813   inline void set_length(Smi* length);
9814
9815   static bool HasReadOnlyLength(Handle<JSArray> array);
9816   static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9817   static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9818
9819   // Initialize the array with the given capacity. The function may
9820   // fail due to out-of-memory situations, but only if the requested
9821   // capacity is non-zero.
9822   static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9823
9824   // If the JSArray has fast elements, and new_length would result in
9825   // normalization, returns true.
9826   bool SetLengthWouldNormalize(uint32_t new_length);
9827   static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9828
9829   // Initializes the array to a certain length.
9830   inline bool AllowsSetLength();
9831
9832   static void SetLength(Handle<JSArray> array, uint32_t length);
9833   // Same as above but will also queue splice records if |array| is observed.
9834   static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9835                                                  uint32_t length);
9836
9837   // Set the content of the array to the content of storage.
9838   static inline void SetContent(Handle<JSArray> array,
9839                                 Handle<FixedArrayBase> storage);
9840
9841   DECLARE_CAST(JSArray)
9842
9843   // Dispatched behavior.
9844   DECLARE_PRINTER(JSArray)
9845   DECLARE_VERIFIER(JSArray)
9846
9847   // Number of element slots to pre-allocate for an empty array.
9848   static const int kPreallocatedArrayElements = 4;
9849
9850   // Layout description.
9851   static const int kLengthOffset = JSObject::kHeaderSize;
9852   static const int kSize = kLengthOffset + kPointerSize;
9853
9854  private:
9855   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9856 };
9857
9858
9859 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9860                                        Handle<Map> initial_map);
9861
9862
9863 // JSRegExpResult is just a JSArray with a specific initial map.
9864 // This initial map adds in-object properties for "index" and "input"
9865 // properties, as assigned by RegExp.prototype.exec, which allows
9866 // faster creation of RegExp exec results.
9867 // This class just holds constants used when creating the result.
9868 // After creation the result must be treated as a JSArray in all regards.
9869 class JSRegExpResult: public JSArray {
9870  public:
9871   // Offsets of object fields.
9872   static const int kIndexOffset = JSArray::kSize;
9873   static const int kInputOffset = kIndexOffset + kPointerSize;
9874   static const int kSize = kInputOffset + kPointerSize;
9875   // Indices of in-object properties.
9876   static const int kIndexIndex = 0;
9877   static const int kInputIndex = 1;
9878  private:
9879   DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9880 };
9881
9882
9883 class AccessorInfo: public Struct {
9884  public:
9885   DECL_ACCESSORS(name, Object)
9886   DECL_ACCESSORS(flag, Smi)
9887   DECL_ACCESSORS(expected_receiver_type, Object)
9888
9889   inline bool all_can_read();
9890   inline void set_all_can_read(bool value);
9891
9892   inline bool all_can_write();
9893   inline void set_all_can_write(bool value);
9894
9895   inline bool is_special_data_property();
9896   inline void set_is_special_data_property(bool value);
9897
9898   inline PropertyAttributes property_attributes();
9899   inline void set_property_attributes(PropertyAttributes attributes);
9900
9901   // Checks whether the given receiver is compatible with this accessor.
9902   static bool IsCompatibleReceiverMap(Isolate* isolate,
9903                                       Handle<AccessorInfo> info,
9904                                       Handle<Map> map);
9905   inline bool IsCompatibleReceiver(Object* receiver);
9906
9907   DECLARE_CAST(AccessorInfo)
9908
9909   // Dispatched behavior.
9910   DECLARE_VERIFIER(AccessorInfo)
9911
9912   // Append all descriptors to the array that are not already there.
9913   // Return number added.
9914   static int AppendUnique(Handle<Object> descriptors,
9915                           Handle<FixedArray> array,
9916                           int valid_descriptors);
9917
9918   static const int kNameOffset = HeapObject::kHeaderSize;
9919   static const int kFlagOffset = kNameOffset + kPointerSize;
9920   static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9921   static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9922
9923  private:
9924   inline bool HasExpectedReceiverType();
9925
9926   // Bit positions in flag.
9927   static const int kAllCanReadBit = 0;
9928   static const int kAllCanWriteBit = 1;
9929   static const int kSpecialDataProperty = 2;
9930   class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9931
9932   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9933 };
9934
9935
9936 // An accessor must have a getter, but can have no setter.
9937 //
9938 // When setting a property, V8 searches accessors in prototypes.
9939 // If an accessor was found and it does not have a setter,
9940 // the request is ignored.
9941 //
9942 // If the accessor in the prototype has the READ_ONLY property attribute, then
9943 // a new value is added to the derived object when the property is set.
9944 // This shadows the accessor in the prototype.
9945 class ExecutableAccessorInfo: public AccessorInfo {
9946  public:
9947   DECL_ACCESSORS(getter, Object)
9948   DECL_ACCESSORS(setter, Object)
9949   DECL_ACCESSORS(data, Object)
9950
9951   DECLARE_CAST(ExecutableAccessorInfo)
9952
9953   // Dispatched behavior.
9954   DECLARE_PRINTER(ExecutableAccessorInfo)
9955   DECLARE_VERIFIER(ExecutableAccessorInfo)
9956
9957   static const int kGetterOffset = AccessorInfo::kSize;
9958   static const int kSetterOffset = kGetterOffset + kPointerSize;
9959   static const int kDataOffset = kSetterOffset + kPointerSize;
9960   static const int kSize = kDataOffset + kPointerSize;
9961
9962   static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9963
9964  private:
9965   DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9966 };
9967
9968
9969 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9970 // accessor can either be
9971 //   * a pointer to a JavaScript function or proxy: a real accessor
9972 //   * undefined: considered an accessor by the spec, too, strangely enough
9973 //   * the hole: an accessor which has not been set
9974 //   * a pointer to a map: a transition used to ensure map sharing
9975 class AccessorPair: public Struct {
9976  public:
9977   DECL_ACCESSORS(getter, Object)
9978   DECL_ACCESSORS(setter, Object)
9979
9980   DECLARE_CAST(AccessorPair)
9981
9982   static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9983
9984   inline Object* get(AccessorComponent component);
9985   inline void set(AccessorComponent component, Object* value);
9986
9987   // Note: Returns undefined instead in case of a hole.
9988   Object* GetComponent(AccessorComponent component);
9989
9990   // Set both components, skipping arguments which are a JavaScript null.
9991   inline void SetComponents(Object* getter, Object* setter);
9992
9993   inline bool Equals(AccessorPair* pair);
9994   inline bool Equals(Object* getter_value, Object* setter_value);
9995
9996   inline bool ContainsAccessor();
9997
9998   // Dispatched behavior.
9999   DECLARE_PRINTER(AccessorPair)
10000   DECLARE_VERIFIER(AccessorPair)
10001
10002   static const int kGetterOffset = HeapObject::kHeaderSize;
10003   static const int kSetterOffset = kGetterOffset + kPointerSize;
10004   static const int kSize = kSetterOffset + kPointerSize;
10005
10006  private:
10007   // Strangely enough, in addition to functions and harmony proxies, the spec
10008   // requires us to consider undefined as a kind of accessor, too:
10009   //    var obj = {};
10010   //    Object.defineProperty(obj, "foo", {get: undefined});
10011   //    assertTrue("foo" in obj);
10012   inline bool IsJSAccessor(Object* obj);
10013
10014   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10015 };
10016
10017
10018 class AccessCheckInfo: public Struct {
10019  public:
10020   DECL_ACCESSORS(named_callback, Object)
10021   DECL_ACCESSORS(indexed_callback, Object)
10022   DECL_ACCESSORS(data, Object)
10023
10024   DECLARE_CAST(AccessCheckInfo)
10025
10026   // Dispatched behavior.
10027   DECLARE_PRINTER(AccessCheckInfo)
10028   DECLARE_VERIFIER(AccessCheckInfo)
10029
10030   static const int kNamedCallbackOffset   = HeapObject::kHeaderSize;
10031   static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10032   static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10033   static const int kSize = kDataOffset + kPointerSize;
10034
10035  private:
10036   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10037 };
10038
10039
10040 class InterceptorInfo: public Struct {
10041  public:
10042   DECL_ACCESSORS(getter, Object)
10043   DECL_ACCESSORS(setter, Object)
10044   DECL_ACCESSORS(query, Object)
10045   DECL_ACCESSORS(deleter, Object)
10046   DECL_ACCESSORS(enumerator, Object)
10047   DECL_ACCESSORS(data, Object)
10048   DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10049   DECL_BOOLEAN_ACCESSORS(all_can_read)
10050   DECL_BOOLEAN_ACCESSORS(non_masking)
10051
10052   inline int flags() const;
10053   inline void set_flags(int flags);
10054
10055   DECLARE_CAST(InterceptorInfo)
10056
10057   // Dispatched behavior.
10058   DECLARE_PRINTER(InterceptorInfo)
10059   DECLARE_VERIFIER(InterceptorInfo)
10060
10061   static const int kGetterOffset = HeapObject::kHeaderSize;
10062   static const int kSetterOffset = kGetterOffset + kPointerSize;
10063   static const int kQueryOffset = kSetterOffset + kPointerSize;
10064   static const int kDeleterOffset = kQueryOffset + kPointerSize;
10065   static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10066   static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10067   static const int kFlagsOffset = kDataOffset + kPointerSize;
10068   static const int kSize = kFlagsOffset + kPointerSize;
10069
10070   static const int kCanInterceptSymbolsBit = 0;
10071   static const int kAllCanReadBit = 1;
10072   static const int kNonMasking = 2;
10073
10074  private:
10075   DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10076 };
10077
10078
10079 class CallHandlerInfo: public Struct {
10080  public:
10081   DECL_ACCESSORS(callback, Object)
10082   DECL_ACCESSORS(data, Object)
10083
10084   DECLARE_CAST(CallHandlerInfo)
10085
10086   // Dispatched behavior.
10087   DECLARE_PRINTER(CallHandlerInfo)
10088   DECLARE_VERIFIER(CallHandlerInfo)
10089
10090   static const int kCallbackOffset = HeapObject::kHeaderSize;
10091   static const int kDataOffset = kCallbackOffset + kPointerSize;
10092   static const int kSize = kDataOffset + kPointerSize;
10093
10094  private:
10095   DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10096 };
10097
10098
10099 class TemplateInfo: public Struct {
10100  public:
10101   DECL_ACCESSORS(tag, Object)
10102   inline int number_of_properties() const;
10103   inline void set_number_of_properties(int value);
10104   DECL_ACCESSORS(property_list, Object)
10105   DECL_ACCESSORS(property_accessors, Object)
10106
10107   DECLARE_VERIFIER(TemplateInfo)
10108
10109   static const int kTagOffset = HeapObject::kHeaderSize;
10110   static const int kNumberOfProperties = kTagOffset + kPointerSize;
10111   static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10112   static const int kPropertyAccessorsOffset =
10113       kPropertyListOffset + kPointerSize;
10114   static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10115
10116  private:
10117   DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10118 };
10119
10120
10121 class FunctionTemplateInfo: public TemplateInfo {
10122  public:
10123   DECL_ACCESSORS(serial_number, Object)
10124   DECL_ACCESSORS(call_code, Object)
10125   DECL_ACCESSORS(prototype_template, Object)
10126   DECL_ACCESSORS(parent_template, Object)
10127   DECL_ACCESSORS(named_property_handler, Object)
10128   DECL_ACCESSORS(indexed_property_handler, Object)
10129   DECL_ACCESSORS(instance_template, Object)
10130   DECL_ACCESSORS(class_name, Object)
10131   DECL_ACCESSORS(signature, Object)
10132   DECL_ACCESSORS(instance_call_handler, Object)
10133   DECL_ACCESSORS(access_check_info, Object)
10134   DECL_ACCESSORS(flag, Smi)
10135
10136   inline int length() const;
10137   inline void set_length(int value);
10138
10139   // Following properties use flag bits.
10140   DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10141   DECL_BOOLEAN_ACCESSORS(undetectable)
10142   // If the bit is set, object instances created by this function
10143   // requires access check.
10144   DECL_BOOLEAN_ACCESSORS(needs_access_check)
10145   DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10146   DECL_BOOLEAN_ACCESSORS(remove_prototype)
10147   DECL_BOOLEAN_ACCESSORS(do_not_cache)
10148   DECL_BOOLEAN_ACCESSORS(instantiated)
10149   DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10150
10151   DECLARE_CAST(FunctionTemplateInfo)
10152
10153   // Dispatched behavior.
10154   DECLARE_PRINTER(FunctionTemplateInfo)
10155   DECLARE_VERIFIER(FunctionTemplateInfo)
10156
10157   static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10158   static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10159   static const int kPrototypeTemplateOffset =
10160       kCallCodeOffset + kPointerSize;
10161   static const int kParentTemplateOffset =
10162       kPrototypeTemplateOffset + kPointerSize;
10163   static const int kNamedPropertyHandlerOffset =
10164       kParentTemplateOffset + kPointerSize;
10165   static const int kIndexedPropertyHandlerOffset =
10166       kNamedPropertyHandlerOffset + kPointerSize;
10167   static const int kInstanceTemplateOffset =
10168       kIndexedPropertyHandlerOffset + kPointerSize;
10169   static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10170   static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10171   static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10172   static const int kAccessCheckInfoOffset =
10173       kInstanceCallHandlerOffset + kPointerSize;
10174   static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10175   static const int kLengthOffset = kFlagOffset + kPointerSize;
10176   static const int kSize = kLengthOffset + kPointerSize;
10177
10178   // Returns true if |object| is an instance of this function template.
10179   bool IsTemplateFor(Object* object);
10180   bool IsTemplateFor(Map* map);
10181
10182   // Returns the holder JSObject if the function can legally be called with this
10183   // receiver.  Returns Heap::null_value() if the call is illegal.
10184   Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10185
10186  private:
10187   // Bit position in the flag, from least significant bit position.
10188   static const int kHiddenPrototypeBit   = 0;
10189   static const int kUndetectableBit      = 1;
10190   static const int kNeedsAccessCheckBit  = 2;
10191   static const int kReadOnlyPrototypeBit = 3;
10192   static const int kRemovePrototypeBit   = 4;
10193   static const int kDoNotCacheBit        = 5;
10194   static const int kInstantiatedBit      = 6;
10195   static const int kAcceptAnyReceiver = 7;
10196
10197   DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10198 };
10199
10200
10201 class ObjectTemplateInfo: public TemplateInfo {
10202  public:
10203   DECL_ACCESSORS(constructor, Object)
10204   DECL_ACCESSORS(internal_field_count, Object)
10205
10206   DECLARE_CAST(ObjectTemplateInfo)
10207
10208   // Dispatched behavior.
10209   DECLARE_PRINTER(ObjectTemplateInfo)
10210   DECLARE_VERIFIER(ObjectTemplateInfo)
10211
10212   static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10213   static const int kInternalFieldCountOffset =
10214       kConstructorOffset + kPointerSize;
10215   static const int kSize = kInternalFieldCountOffset + kPointerSize;
10216 };
10217
10218
10219 class TypeSwitchInfo: public Struct {
10220  public:
10221   DECL_ACCESSORS(types, Object)
10222
10223   DECLARE_CAST(TypeSwitchInfo)
10224
10225   // Dispatched behavior.
10226   DECLARE_PRINTER(TypeSwitchInfo)
10227   DECLARE_VERIFIER(TypeSwitchInfo)
10228
10229   static const int kTypesOffset = Struct::kHeaderSize;
10230   static const int kSize        = kTypesOffset + kPointerSize;
10231 };
10232
10233
10234 // The DebugInfo class holds additional information for a function being
10235 // debugged.
10236 class DebugInfo: public Struct {
10237  public:
10238   // The shared function info for the source being debugged.
10239   DECL_ACCESSORS(shared, SharedFunctionInfo)
10240   // Code object for the patched code. This code object is the code object
10241   // currently active for the function.
10242   DECL_ACCESSORS(code, Code)
10243   // Fixed array holding status information for each active break point.
10244   DECL_ACCESSORS(break_points, FixedArray)
10245
10246   // Check if there is a break point at a code position.
10247   bool HasBreakPoint(int code_position);
10248   // Get the break point info object for a code position.
10249   Object* GetBreakPointInfo(int code_position);
10250   // Clear a break point.
10251   static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10252                               int code_position,
10253                               Handle<Object> break_point_object);
10254   // Set a break point.
10255   static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10256                             int source_position, int statement_position,
10257                             Handle<Object> break_point_object);
10258   // Get the break point objects for a code position.
10259   Handle<Object> GetBreakPointObjects(int code_position);
10260   // Find the break point info holding this break point object.
10261   static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10262                                            Handle<Object> break_point_object);
10263   // Get the number of break points for this function.
10264   int GetBreakPointCount();
10265
10266   DECLARE_CAST(DebugInfo)
10267
10268   // Dispatched behavior.
10269   DECLARE_PRINTER(DebugInfo)
10270   DECLARE_VERIFIER(DebugInfo)
10271
10272   static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10273   static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10274   static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10275   static const int kSize = kBreakPointsStateIndex + kPointerSize;
10276
10277   static const int kEstimatedNofBreakPointsInFunction = 16;
10278
10279  private:
10280   static const int kNoBreakPointInfo = -1;
10281
10282   // Lookup the index in the break_points array for a code position.
10283   int GetBreakPointInfoIndex(int code_position);
10284
10285   DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10286 };
10287
10288
10289 // The BreakPointInfo class holds information for break points set in a
10290 // function. The DebugInfo object holds a BreakPointInfo object for each code
10291 // position with one or more break points.
10292 class BreakPointInfo: public Struct {
10293  public:
10294   // The position in the code for the break point.
10295   DECL_ACCESSORS(code_position, Smi)
10296   // The position in the source for the break position.
10297   DECL_ACCESSORS(source_position, Smi)
10298   // The position in the source for the last statement before this break
10299   // position.
10300   DECL_ACCESSORS(statement_position, Smi)
10301   // List of related JavaScript break points.
10302   DECL_ACCESSORS(break_point_objects, Object)
10303
10304   // Removes a break point.
10305   static void ClearBreakPoint(Handle<BreakPointInfo> info,
10306                               Handle<Object> break_point_object);
10307   // Set a break point.
10308   static void SetBreakPoint(Handle<BreakPointInfo> info,
10309                             Handle<Object> break_point_object);
10310   // Check if break point info has this break point object.
10311   static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10312                                   Handle<Object> break_point_object);
10313   // Get the number of break points for this code position.
10314   int GetBreakPointCount();
10315
10316   DECLARE_CAST(BreakPointInfo)
10317
10318   // Dispatched behavior.
10319   DECLARE_PRINTER(BreakPointInfo)
10320   DECLARE_VERIFIER(BreakPointInfo)
10321
10322   static const int kCodePositionIndex = Struct::kHeaderSize;
10323   static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10324   static const int kStatementPositionIndex =
10325       kSourcePositionIndex + kPointerSize;
10326   static const int kBreakPointObjectsIndex =
10327       kStatementPositionIndex + kPointerSize;
10328   static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10329
10330  private:
10331   DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10332 };
10333
10334
10335 #undef DECL_BOOLEAN_ACCESSORS
10336 #undef DECL_ACCESSORS
10337 #undef DECLARE_CAST
10338 #undef DECLARE_VERIFIER
10339
10340 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V)                               \
10341   V(kStringTable, "string_table", "(Internalized strings)")                \
10342   V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10343   V(kStrongRootList, "strong_root_list", "(Strong roots)")                 \
10344   V(kSmiRootList, "smi_root_list", "(Smi roots)")                          \
10345   V(kBootstrapper, "bootstrapper", "(Bootstrapper)")                       \
10346   V(kTop, "top", "(Isolate)")                                              \
10347   V(kRelocatable, "relocatable", "(Relocatable)")                          \
10348   V(kDebug, "debug", "(Debugger)")                                         \
10349   V(kCompilationCache, "compilationcache", "(Compilation cache)")          \
10350   V(kHandleScope, "handlescope", "(Handle scope)")                         \
10351   V(kBuiltins, "builtins", "(Builtins)")                                   \
10352   V(kGlobalHandles, "globalhandles", "(Global handles)")                   \
10353   V(kEternalHandles, "eternalhandles", "(Eternal handles)")                \
10354   V(kThreadManager, "threadmanager", "(Thread manager)")                   \
10355   V(kStrongRoots, "strong roots", "(Strong roots)")                        \
10356   V(kExtensions, "Extensions", "(Extensions)")
10357
10358 class VisitorSynchronization : public AllStatic {
10359  public:
10360 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10361   enum SyncTag {
10362     VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10363     kNumberOfSyncTags
10364   };
10365 #undef DECLARE_ENUM
10366
10367   static const char* const kTags[kNumberOfSyncTags];
10368   static const char* const kTagNames[kNumberOfSyncTags];
10369 };
10370
10371 // Abstract base class for visiting, and optionally modifying, the
10372 // pointers contained in Objects. Used in GC and serialization/deserialization.
10373 class ObjectVisitor BASE_EMBEDDED {
10374  public:
10375   virtual ~ObjectVisitor() {}
10376
10377   // Visits a contiguous arrays of pointers in the half-open range
10378   // [start, end). Any or all of the values may be modified on return.
10379   virtual void VisitPointers(Object** start, Object** end) = 0;
10380
10381   // Handy shorthand for visiting a single pointer.
10382   virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10383
10384   // Visit weak next_code_link in Code object.
10385   virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10386
10387   // To allow lazy clearing of inline caches the visitor has
10388   // a rich interface for iterating over Code objects..
10389
10390   // Visits a code target in the instruction stream.
10391   virtual void VisitCodeTarget(RelocInfo* rinfo);
10392
10393   // Visits a code entry in a JS function.
10394   virtual void VisitCodeEntry(Address entry_address);
10395
10396   // Visits a global property cell reference in the instruction stream.
10397   virtual void VisitCell(RelocInfo* rinfo);
10398
10399   // Visits a runtime entry in the instruction stream.
10400   virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10401
10402   // Visits the resource of an one-byte or two-byte string.
10403   virtual void VisitExternalOneByteString(
10404       v8::String::ExternalOneByteStringResource** resource) {}
10405   virtual void VisitExternalTwoByteString(
10406       v8::String::ExternalStringResource** resource) {}
10407
10408   // Visits a debug call target in the instruction stream.
10409   virtual void VisitDebugTarget(RelocInfo* rinfo);
10410
10411   // Visits the byte sequence in a function's prologue that contains information
10412   // about the code's age.
10413   virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10414
10415   // Visit pointer embedded into a code object.
10416   virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10417
10418   // Visits an external reference embedded into a code object.
10419   virtual void VisitExternalReference(RelocInfo* rinfo);
10420
10421   // Visits an external reference.
10422   virtual void VisitExternalReference(Address* p) {}
10423
10424   // Visits an (encoded) internal reference.
10425   virtual void VisitInternalReference(RelocInfo* rinfo) {}
10426
10427   // Visits a handle that has an embedder-assigned class ID.
10428   virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10429
10430   // Intended for serialization/deserialization checking: insert, or
10431   // check for the presence of, a tag at this position in the stream.
10432   // Also used for marking up GC roots in heap snapshots.
10433   virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10434 };
10435
10436
10437 class StructBodyDescriptor : public
10438   FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10439  public:
10440   static inline int SizeOf(Map* map, HeapObject* object);
10441 };
10442
10443
10444 // BooleanBit is a helper class for setting and getting a bit in an
10445 // integer or Smi.
10446 class BooleanBit : public AllStatic {
10447  public:
10448   static inline bool get(Smi* smi, int bit_position) {
10449     return get(smi->value(), bit_position);
10450   }
10451
10452   static inline bool get(int value, int bit_position) {
10453     return (value & (1 << bit_position)) != 0;
10454   }
10455
10456   static inline Smi* set(Smi* smi, int bit_position, bool v) {
10457     return Smi::FromInt(set(smi->value(), bit_position, v));
10458   }
10459
10460   static inline int set(int value, int bit_position, bool v) {
10461     if (v) {
10462       value |= (1 << bit_position);
10463     } else {
10464       value &= ~(1 << bit_position);
10465     }
10466     return value;
10467   }
10468 };
10469
10470 } }  // namespace v8::internal
10471
10472 #endif  // V8_OBJECTS_H_