Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / v8 / src / objects.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #ifndef V8_OBJECTS_H_
29 #define V8_OBJECTS_H_
30
31 #include "allocation.h"
32 #include "assert-scope.h"
33 #include "builtins.h"
34 #include "elements-kind.h"
35 #include "flags.h"
36 #include "list.h"
37 #include "property-details.h"
38 #include "smart-pointers.h"
39 #include "unicode-inl.h"
40 #if V8_TARGET_ARCH_ARM64
41 #include "arm64/constants-arm64.h"
42 #elif V8_TARGET_ARCH_ARM
43 #include "arm/constants-arm.h"
44 #elif V8_TARGET_ARCH_MIPS
45 #include "mips/constants-mips.h"
46 #endif
47 #include "v8checks.h"
48 #include "zone.h"
49
50
51 //
52 // Most object types in the V8 JavaScript are described in this file.
53 //
54 // Inheritance hierarchy:
55 // - MaybeObject    (an object or a failure)
56 //   - Failure      (immediate for marking failed operation)
57 //   - Object
58 //     - Smi          (immediate small integer)
59 //     - HeapObject   (superclass for everything allocated in the heap)
60 //       - JSReceiver  (suitable for property access)
61 //         - JSObject
62 //           - JSArray
63 //           - JSArrayBuffer
64 //           - JSArrayBufferView
65 //             - JSTypedArray
66 //             - JSDataView
67 //           - JSSet
68 //           - JSMap
69 //           - JSWeakCollection
70 //             - JSWeakMap
71 //             - JSWeakSet
72 //           - JSRegExp
73 //           - JSFunction
74 //           - JSGeneratorObject
75 //           - JSModule
76 //           - GlobalObject
77 //             - JSGlobalObject
78 //             - JSBuiltinsObject
79 //           - JSGlobalProxy
80 //           - JSValue
81 //             - JSDate
82 //           - JSMessageObject
83 //         - JSProxy
84 //           - JSFunctionProxy
85 //       - FixedArrayBase
86 //         - ByteArray
87 //         - FixedArray
88 //           - DescriptorArray
89 //           - HashTable
90 //             - Dictionary
91 //             - StringTable
92 //             - CompilationCacheTable
93 //             - CodeCacheHashTable
94 //             - MapCache
95 //           - Context
96 //           - JSFunctionResultCache
97 //           - ScopeInfo
98 //           - TransitionArray
99 //         - FixedDoubleArray
100 //         - ExternalArray
101 //           - ExternalUint8ClampedArray
102 //           - ExternalInt8Array
103 //           - ExternalUint8Array
104 //           - ExternalInt16Array
105 //           - ExternalUint16Array
106 //           - ExternalInt32Array
107 //           - ExternalUint32Array
108 //           - ExternalFloat32Array
109 //           - ExternalFloat32x4Array
110 //           - ExternalInt32x4Array
111 //       - Name
112 //         - String
113 //           - SeqString
114 //             - SeqOneByteString
115 //             - SeqTwoByteString
116 //           - SlicedString
117 //           - ConsString
118 //           - ExternalString
119 //             - ExternalAsciiString
120 //             - ExternalTwoByteString
121 //           - InternalizedString
122 //             - SeqInternalizedString
123 //               - SeqOneByteInternalizedString
124 //               - SeqTwoByteInternalizedString
125 //             - ConsInternalizedString
126 //             - ExternalInternalizedString
127 //               - ExternalAsciiInternalizedString
128 //               - ExternalTwoByteInternalizedString
129 //         - Symbol
130 //       - HeapNumber
131 //       - Float32x4
132 //       - Int32x4
133 //       - Cell
134 //         - PropertyCell
135 //       - Code
136 //       - Map
137 //       - Oddball
138 //       - Foreign
139 //       - SharedFunctionInfo
140 //       - Struct
141 //         - Box
142 //         - DeclaredAccessorDescriptor
143 //         - AccessorInfo
144 //           - DeclaredAccessorInfo
145 //           - ExecutableAccessorInfo
146 //         - AccessorPair
147 //         - AccessCheckInfo
148 //         - InterceptorInfo
149 //         - CallHandlerInfo
150 //         - TemplateInfo
151 //           - FunctionTemplateInfo
152 //           - ObjectTemplateInfo
153 //         - Script
154 //         - SignatureInfo
155 //         - TypeSwitchInfo
156 //         - DebugInfo
157 //         - BreakPointInfo
158 //         - CodeCache
159 //
160 // Formats of Object*:
161 //  Smi:        [31 bit signed int] 0
162 //  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
163 //  Failure:    [30 bit signed int] 11
164
165 namespace v8 {
166 namespace internal {
167
168 enum KeyedAccessStoreMode {
169   STANDARD_STORE,
170   STORE_TRANSITION_SMI_TO_OBJECT,
171   STORE_TRANSITION_SMI_TO_DOUBLE,
172   STORE_TRANSITION_DOUBLE_TO_OBJECT,
173   STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
174   STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
175   STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
176   STORE_AND_GROW_NO_TRANSITION,
177   STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
178   STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
179   STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
180   STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
181   STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
182   STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
183   STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
184   STORE_NO_TRANSITION_HANDLE_COW
185 };
186
187
188 enum ContextualMode {
189   NOT_CONTEXTUAL,
190   CONTEXTUAL
191 };
192
193
194 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
195     STANDARD_STORE;
196 STATIC_ASSERT(STANDARD_STORE == 0);
197 STATIC_ASSERT(kGrowICDelta ==
198               STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
199               STORE_TRANSITION_SMI_TO_OBJECT);
200 STATIC_ASSERT(kGrowICDelta ==
201               STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
202               STORE_TRANSITION_SMI_TO_DOUBLE);
203 STATIC_ASSERT(kGrowICDelta ==
204               STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
205               STORE_TRANSITION_DOUBLE_TO_OBJECT);
206
207
208 static inline KeyedAccessStoreMode GetGrowStoreMode(
209     KeyedAccessStoreMode store_mode) {
210   if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
211     store_mode = static_cast<KeyedAccessStoreMode>(
212         static_cast<int>(store_mode) + kGrowICDelta);
213   }
214   return store_mode;
215 }
216
217
218 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
219   return store_mode > STANDARD_STORE &&
220       store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
221       store_mode != STORE_AND_GROW_NO_TRANSITION;
222 }
223
224
225 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
226     KeyedAccessStoreMode store_mode) {
227   if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
228     return store_mode;
229   }
230   if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
231     return STORE_AND_GROW_NO_TRANSITION;
232   }
233   return STANDARD_STORE;
234 }
235
236
237 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
238   return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
239       store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
240 }
241
242
243 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
244 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
245
246
247 // Indicates whether a value can be loaded as a constant.
248 enum StoreMode {
249   ALLOW_AS_CONSTANT,
250   FORCE_FIELD
251 };
252
253
254 // PropertyNormalizationMode is used to specify whether to keep
255 // inobject properties when normalizing properties of a JSObject.
256 enum PropertyNormalizationMode {
257   CLEAR_INOBJECT_PROPERTIES,
258   KEEP_INOBJECT_PROPERTIES
259 };
260
261
262 // NormalizedMapSharingMode is used to specify whether a map may be shared
263 // by different objects with normalized properties.
264 enum NormalizedMapSharingMode {
265   UNIQUE_NORMALIZED_MAP,
266   SHARED_NORMALIZED_MAP
267 };
268
269
270 // Indicates whether transitions can be added to a source map or not.
271 enum TransitionFlag {
272   INSERT_TRANSITION,
273   OMIT_TRANSITION
274 };
275
276
277 enum DebugExtraICState {
278   DEBUG_BREAK,
279   DEBUG_PREPARE_STEP_IN
280 };
281
282
283 // Indicates whether the transition is simple: the target map of the transition
284 // either extends the current map with a new property, or it modifies the
285 // property that was added last to the current map.
286 enum SimpleTransitionFlag {
287   SIMPLE_TRANSITION,
288   FULL_TRANSITION
289 };
290
291
292 // Indicates whether we are only interested in the descriptors of a particular
293 // map, or in all descriptors in the descriptor array.
294 enum DescriptorFlag {
295   ALL_DESCRIPTORS,
296   OWN_DESCRIPTORS
297 };
298
299 // The GC maintains a bit of information, the MarkingParity, which toggles
300 // from odd to even and back every time marking is completed. Incremental
301 // marking can visit an object twice during a marking phase, so algorithms that
302 // that piggy-back on marking can use the parity to ensure that they only
303 // perform an operation on an object once per marking phase: they record the
304 // MarkingParity when they visit an object, and only re-visit the object when it
305 // is marked again and the MarkingParity changes.
306 enum MarkingParity {
307   NO_MARKING_PARITY,
308   ODD_MARKING_PARITY,
309   EVEN_MARKING_PARITY
310 };
311
312 // ICs store extra state in a Code object. The default extra state is
313 // kNoExtraICState.
314 typedef int ExtraICState;
315 static const ExtraICState kNoExtraICState = 0;
316
317 // Instance size sentinel for objects of variable size.
318 const int kVariableSizeSentinel = 0;
319
320 const int kStubMajorKeyBits = 7;
321 const int kStubMinorKeyBits = kBitsPerInt - kSmiTagSize - kStubMajorKeyBits;
322
323 // All Maps have a field instance_type containing a InstanceType.
324 // It describes the type of the instances.
325 //
326 // As an example, a JavaScript object is a heap object and its map
327 // instance_type is JS_OBJECT_TYPE.
328 //
329 // The names of the string instance types are intended to systematically
330 // mirror their encoding in the instance_type field of the map.  The default
331 // encoding is considered TWO_BYTE.  It is not mentioned in the name.  ASCII
332 // encoding is mentioned explicitly in the name.  Likewise, the default
333 // representation is considered sequential.  It is not mentioned in the
334 // name.  The other representations (e.g. CONS, EXTERNAL) are explicitly
335 // mentioned.  Finally, the string is either a STRING_TYPE (if it is a normal
336 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
337 //
338 // NOTE: The following things are some that depend on the string types having
339 // instance_types that are less than those of all other types:
340 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
341 // Object::IsString.
342 //
343 // NOTE: Everything following JS_VALUE_TYPE is considered a
344 // JSObject for GC purposes. The first four entries here have typeof
345 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
346 #define INSTANCE_TYPE_LIST(V)                                                  \
347   V(STRING_TYPE)                                                               \
348   V(ASCII_STRING_TYPE)                                                         \
349   V(CONS_STRING_TYPE)                                                          \
350   V(CONS_ASCII_STRING_TYPE)                                                    \
351   V(SLICED_STRING_TYPE)                                                        \
352   V(SLICED_ASCII_STRING_TYPE)                                                  \
353   V(EXTERNAL_STRING_TYPE)                                                      \
354   V(EXTERNAL_ASCII_STRING_TYPE)                                                \
355   V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE)                                   \
356   V(SHORT_EXTERNAL_STRING_TYPE)                                                \
357   V(SHORT_EXTERNAL_ASCII_STRING_TYPE)                                          \
358   V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE)                             \
359                                                                                \
360   V(INTERNALIZED_STRING_TYPE)                                                  \
361   V(ASCII_INTERNALIZED_STRING_TYPE)                                            \
362   V(CONS_INTERNALIZED_STRING_TYPE)                                             \
363   V(CONS_ASCII_INTERNALIZED_STRING_TYPE)                                       \
364   V(EXTERNAL_INTERNALIZED_STRING_TYPE)                                         \
365   V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE)                                   \
366   V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE)                      \
367   V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE)                                   \
368   V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE)                             \
369   V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE)                \
370                                                                                \
371   V(SYMBOL_TYPE)                                                               \
372                                                                                \
373   V(MAP_TYPE)                                                                  \
374   V(CODE_TYPE)                                                                 \
375   V(ODDBALL_TYPE)                                                              \
376   V(CELL_TYPE)                                                                 \
377   V(PROPERTY_CELL_TYPE)                                                        \
378                                                                                \
379   V(HEAP_NUMBER_TYPE)                                                          \
380   V(FLOAT32x4_TYPE)                                                            \
381   V(INT32x4_TYPE)                                                              \
382   V(FOREIGN_TYPE)                                                              \
383   V(BYTE_ARRAY_TYPE)                                                           \
384   V(FREE_SPACE_TYPE)                                                           \
385   /* Note: the order of these external array */                                \
386   /* types is relied upon in */                                                \
387   /* Object::IsExternalArray(). */                                             \
388   V(EXTERNAL_INT8_ARRAY_TYPE)                                                  \
389   V(EXTERNAL_UINT8_ARRAY_TYPE)                                                 \
390   V(EXTERNAL_INT16_ARRAY_TYPE)                                                 \
391   V(EXTERNAL_UINT16_ARRAY_TYPE)                                                \
392   V(EXTERNAL_INT32_ARRAY_TYPE)                                                 \
393   V(EXTERNAL_UINT32_ARRAY_TYPE)                                                \
394   V(EXTERNAL_FLOAT32_ARRAY_TYPE)                                               \
395   V(EXTERNAL_FLOAT32x4_ARRAY_TYPE)                                             \
396   V(EXTERNAL_INT32x4_ARRAY_TYPE)                                               \
397   V(EXTERNAL_FLOAT64_ARRAY_TYPE)                                               \
398   V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE)                                         \
399                                                                                \
400   V(FIXED_INT8_ARRAY_TYPE)                                                     \
401   V(FIXED_UINT8_ARRAY_TYPE)                                                    \
402   V(FIXED_INT16_ARRAY_TYPE)                                                    \
403   V(FIXED_UINT16_ARRAY_TYPE)                                                   \
404   V(FIXED_INT32_ARRAY_TYPE)                                                    \
405   V(FIXED_INT32x4_ARRAY_TYPE)                                                  \
406   V(FIXED_UINT32_ARRAY_TYPE)                                                   \
407   V(FIXED_FLOAT32_ARRAY_TYPE)                                                  \
408   V(FIXED_FLOAT32x4_ARRAY_TYPE)                                                \
409   V(FIXED_FLOAT64_ARRAY_TYPE)                                                  \
410   V(FIXED_UINT8_CLAMPED_ARRAY_TYPE)                                            \
411                                                                                \
412   V(FILLER_TYPE)                                                               \
413                                                                                \
414   V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE)                                         \
415   V(DECLARED_ACCESSOR_INFO_TYPE)                                               \
416   V(EXECUTABLE_ACCESSOR_INFO_TYPE)                                             \
417   V(ACCESSOR_PAIR_TYPE)                                                        \
418   V(ACCESS_CHECK_INFO_TYPE)                                                    \
419   V(INTERCEPTOR_INFO_TYPE)                                                     \
420   V(CALL_HANDLER_INFO_TYPE)                                                    \
421   V(FUNCTION_TEMPLATE_INFO_TYPE)                                               \
422   V(OBJECT_TEMPLATE_INFO_TYPE)                                                 \
423   V(SIGNATURE_INFO_TYPE)                                                       \
424   V(TYPE_SWITCH_INFO_TYPE)                                                     \
425   V(ALLOCATION_MEMENTO_TYPE)                                                   \
426   V(ALLOCATION_SITE_TYPE)                                                      \
427   V(SCRIPT_TYPE)                                                               \
428   V(CODE_CACHE_TYPE)                                                           \
429   V(POLYMORPHIC_CODE_CACHE_TYPE)                                               \
430   V(TYPE_FEEDBACK_INFO_TYPE)                                                   \
431   V(ALIASED_ARGUMENTS_ENTRY_TYPE)                                              \
432   V(BOX_TYPE)                                                                  \
433                                                                                \
434   V(FIXED_ARRAY_TYPE)                                                          \
435   V(FIXED_DOUBLE_ARRAY_TYPE)                                                   \
436   V(CONSTANT_POOL_ARRAY_TYPE)                                                  \
437   V(SHARED_FUNCTION_INFO_TYPE)                                                 \
438                                                                                \
439   V(JS_MESSAGE_OBJECT_TYPE)                                                    \
440                                                                                \
441   V(JS_VALUE_TYPE)                                                             \
442   V(JS_DATE_TYPE)                                                              \
443   V(JS_OBJECT_TYPE)                                                            \
444   V(JS_CONTEXT_EXTENSION_OBJECT_TYPE)                                          \
445   V(JS_GENERATOR_OBJECT_TYPE)                                                  \
446   V(JS_MODULE_TYPE)                                                            \
447   V(JS_GLOBAL_OBJECT_TYPE)                                                     \
448   V(JS_BUILTINS_OBJECT_TYPE)                                                   \
449   V(JS_GLOBAL_PROXY_TYPE)                                                      \
450   V(JS_ARRAY_TYPE)                                                             \
451   V(JS_ARRAY_BUFFER_TYPE)                                                      \
452   V(JS_TYPED_ARRAY_TYPE)                                                       \
453   V(JS_DATA_VIEW_TYPE)                                                         \
454   V(JS_PROXY_TYPE)                                                             \
455   V(JS_SET_TYPE)                                                               \
456   V(JS_MAP_TYPE)                                                               \
457   V(JS_WEAK_MAP_TYPE)                                                          \
458   V(JS_WEAK_SET_TYPE)                                                          \
459   V(JS_REGEXP_TYPE)                                                            \
460                                                                                \
461   V(JS_FUNCTION_TYPE)                                                          \
462   V(JS_FUNCTION_PROXY_TYPE)                                                    \
463   V(DEBUG_INFO_TYPE)                                                           \
464   V(BREAK_POINT_INFO_TYPE)
465
466
467 // Since string types are not consecutive, this macro is used to
468 // iterate over them.
469 #define STRING_TYPE_LIST(V)                                                    \
470   V(STRING_TYPE,                                                               \
471     kVariableSizeSentinel,                                                     \
472     string,                                                                    \
473     String)                                                                    \
474   V(ASCII_STRING_TYPE,                                                         \
475     kVariableSizeSentinel,                                                     \
476     ascii_string,                                                              \
477     AsciiString)                                                               \
478   V(CONS_STRING_TYPE,                                                          \
479     ConsString::kSize,                                                         \
480     cons_string,                                                               \
481     ConsString)                                                                \
482   V(CONS_ASCII_STRING_TYPE,                                                    \
483     ConsString::kSize,                                                         \
484     cons_ascii_string,                                                         \
485     ConsAsciiString)                                                           \
486   V(SLICED_STRING_TYPE,                                                        \
487     SlicedString::kSize,                                                       \
488     sliced_string,                                                             \
489     SlicedString)                                                              \
490   V(SLICED_ASCII_STRING_TYPE,                                                  \
491     SlicedString::kSize,                                                       \
492     sliced_ascii_string,                                                       \
493     SlicedAsciiString)                                                         \
494   V(EXTERNAL_STRING_TYPE,                                                      \
495     ExternalTwoByteString::kSize,                                              \
496     external_string,                                                           \
497     ExternalString)                                                            \
498   V(EXTERNAL_ASCII_STRING_TYPE,                                                \
499     ExternalAsciiString::kSize,                                                \
500     external_ascii_string,                                                     \
501     ExternalAsciiString)                                                       \
502   V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE,                                   \
503     ExternalTwoByteString::kSize,                                              \
504     external_string_with_one_byte_data,                                        \
505     ExternalStringWithOneByteData)                                             \
506   V(SHORT_EXTERNAL_STRING_TYPE,                                                \
507     ExternalTwoByteString::kShortSize,                                         \
508     short_external_string,                                                     \
509     ShortExternalString)                                                       \
510   V(SHORT_EXTERNAL_ASCII_STRING_TYPE,                                          \
511     ExternalAsciiString::kShortSize,                                           \
512     short_external_ascii_string,                                               \
513     ShortExternalAsciiString)                                                  \
514   V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE,                             \
515     ExternalTwoByteString::kShortSize,                                         \
516     short_external_string_with_one_byte_data,                                  \
517     ShortExternalStringWithOneByteData)                                        \
518                                                                                \
519   V(INTERNALIZED_STRING_TYPE,                                                  \
520     kVariableSizeSentinel,                                                     \
521     internalized_string,                                                       \
522     InternalizedString)                                                        \
523   V(ASCII_INTERNALIZED_STRING_TYPE,                                            \
524     kVariableSizeSentinel,                                                     \
525     ascii_internalized_string,                                                 \
526     AsciiInternalizedString)                                                   \
527   V(CONS_INTERNALIZED_STRING_TYPE,                                             \
528     ConsString::kSize,                                                         \
529     cons_internalized_string,                                                  \
530     ConsInternalizedString)                                                    \
531   V(CONS_ASCII_INTERNALIZED_STRING_TYPE,                                       \
532     ConsString::kSize,                                                         \
533     cons_ascii_internalized_string,                                            \
534     ConsAsciiInternalizedString)                                               \
535   V(EXTERNAL_INTERNALIZED_STRING_TYPE,                                         \
536     ExternalTwoByteString::kSize,                                              \
537     external_internalized_string,                                              \
538     ExternalInternalizedString)                                                \
539   V(EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE,                                   \
540     ExternalAsciiString::kSize,                                                \
541     external_ascii_internalized_string,                                        \
542     ExternalAsciiInternalizedString)                                           \
543   V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE,                      \
544     ExternalTwoByteString::kSize,                                              \
545     external_internalized_string_with_one_byte_data,                           \
546     ExternalInternalizedStringWithOneByteData)                                 \
547   V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE,                                   \
548     ExternalTwoByteString::kShortSize,                                         \
549     short_external_internalized_string,                                        \
550     ShortExternalInternalizedString)                                           \
551   V(SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE,                             \
552     ExternalAsciiString::kShortSize,                                           \
553     short_external_ascii_internalized_string,                                  \
554     ShortExternalAsciiInternalizedString)                                      \
555   V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE,                \
556     ExternalTwoByteString::kShortSize,                                         \
557     short_external_internalized_string_with_one_byte_data,                     \
558     ShortExternalInternalizedStringWithOneByteData)                            \
559
560 // A struct is a simple object a set of object-valued fields.  Including an
561 // object type in this causes the compiler to generate most of the boilerplate
562 // code for the class including allocation and garbage collection routines,
563 // casts and predicates.  All you need to define is the class, methods and
564 // object verification routines.  Easy, no?
565 //
566 // Note that for subtle reasons related to the ordering or numerical values of
567 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
568 // manually.
569 #define STRUCT_LIST_ALL(V)                                                     \
570   V(BOX, Box, box)                                                             \
571   V(DECLARED_ACCESSOR_DESCRIPTOR,                                              \
572     DeclaredAccessorDescriptor,                                                \
573     declared_accessor_descriptor)                                              \
574   V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info)      \
575   V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
576   V(ACCESSOR_PAIR, AccessorPair, accessor_pair)                                \
577   V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info)                     \
578   V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info)                       \
579   V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info)                     \
580   V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info)      \
581   V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info)            \
582   V(SIGNATURE_INFO, SignatureInfo, signature_info)                             \
583   V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info)                        \
584   V(SCRIPT, Script, script)                                                    \
585   V(ALLOCATION_SITE, AllocationSite, allocation_site)                          \
586   V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento)                 \
587   V(CODE_CACHE, CodeCache, code_cache)                                         \
588   V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache)      \
589   V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info)                  \
590   V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
591
592 #ifdef ENABLE_DEBUGGER_SUPPORT
593 #define STRUCT_LIST_DEBUGGER(V)                                                \
594   V(DEBUG_INFO, DebugInfo, debug_info)                                         \
595   V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
596 #else
597 #define STRUCT_LIST_DEBUGGER(V)
598 #endif
599
600 #define STRUCT_LIST(V)                                                         \
601   STRUCT_LIST_ALL(V)                                                           \
602   STRUCT_LIST_DEBUGGER(V)
603
604 // We use the full 8 bits of the instance_type field to encode heap object
605 // instance types.  The high-order bit (bit 7) is set if the object is not a
606 // string, and cleared if it is a string.
607 const uint32_t kIsNotStringMask = 0x80;
608 const uint32_t kStringTag = 0x0;
609 const uint32_t kNotStringTag = 0x80;
610
611 // Bit 6 indicates that the object is an internalized string (if set) or not.
612 // Bit 7 has to be clear as well.
613 const uint32_t kIsNotInternalizedMask = 0x40;
614 const uint32_t kNotInternalizedTag = 0x40;
615 const uint32_t kInternalizedTag = 0x0;
616
617 // If bit 7 is clear then bit 2 indicates whether the string consists of
618 // two-byte characters or one-byte characters.
619 const uint32_t kStringEncodingMask = 0x4;
620 const uint32_t kTwoByteStringTag = 0x0;
621 const uint32_t kOneByteStringTag = 0x4;
622
623 // If bit 7 is clear, the low-order 2 bits indicate the representation
624 // of the string.
625 const uint32_t kStringRepresentationMask = 0x03;
626 enum StringRepresentationTag {
627   kSeqStringTag = 0x0,
628   kConsStringTag = 0x1,
629   kExternalStringTag = 0x2,
630   kSlicedStringTag = 0x3
631 };
632 const uint32_t kIsIndirectStringMask = 0x1;
633 const uint32_t kIsIndirectStringTag = 0x1;
634 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
635 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
636 STATIC_ASSERT(
637     (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
638 STATIC_ASSERT(
639     (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
640
641 // Use this mask to distinguish between cons and slice only after making
642 // sure that the string is one of the two (an indirect string).
643 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
644 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
645
646 // If bit 7 is clear, then bit 3 indicates whether this two-byte
647 // string actually contains one byte data.
648 const uint32_t kOneByteDataHintMask = 0x08;
649 const uint32_t kOneByteDataHintTag = 0x08;
650
651 // If bit 7 is clear and string representation indicates an external string,
652 // then bit 4 indicates whether the data pointer is cached.
653 const uint32_t kShortExternalStringMask = 0x10;
654 const uint32_t kShortExternalStringTag = 0x10;
655
656
657 // A ConsString with an empty string as the right side is a candidate
658 // for being shortcut by the garbage collector unless it is internalized.
659 // It's not common to have non-flat internalized strings, so we do not
660 // shortcut them thereby avoiding turning internalized strings into strings.
661 // See heap.cc and mark-compact.cc.
662 const uint32_t kShortcutTypeMask =
663     kIsNotStringMask |
664     kIsNotInternalizedMask |
665     kStringRepresentationMask;
666 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
667
668
669 enum InstanceType {
670   // String types.
671   INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag
672       | kInternalizedTag,
673   ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kSeqStringTag
674       | kInternalizedTag,
675   CONS_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kConsStringTag
676       | kInternalizedTag,
677   CONS_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag | kConsStringTag
678       | kInternalizedTag,
679   EXTERNAL_INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kExternalStringTag
680       | kInternalizedTag,
681   EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE = kOneByteStringTag
682       | kExternalStringTag | kInternalizedTag,
683   EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
684       EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag
685       | kInternalizedTag,
686   SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE =
687       EXTERNAL_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
688       | kInternalizedTag,
689   SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE =
690       EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kShortExternalStringTag
691       | kInternalizedTag,
692   SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
693       EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
694       | kShortExternalStringTag | kInternalizedTag,
695
696   STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
697   ASCII_STRING_TYPE = ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
698   CONS_STRING_TYPE = CONS_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
699   CONS_ASCII_STRING_TYPE =
700       CONS_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
701
702   SLICED_STRING_TYPE =
703       kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
704   SLICED_ASCII_STRING_TYPE =
705       kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
706   EXTERNAL_STRING_TYPE =
707   EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
708   EXTERNAL_ASCII_STRING_TYPE =
709   EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
710   EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
711       EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
712       | kNotInternalizedTag,
713   SHORT_EXTERNAL_STRING_TYPE =
714       SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
715   SHORT_EXTERNAL_ASCII_STRING_TYPE =
716       SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
717   SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
718       SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE
719       | kNotInternalizedTag,
720
721   // Non-string names
722   SYMBOL_TYPE = kNotStringTag,  // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
723
724   // Objects allocated in their own spaces (never in new space).
725   MAP_TYPE,
726   CODE_TYPE,
727   ODDBALL_TYPE,
728   CELL_TYPE,
729   PROPERTY_CELL_TYPE,
730
731   // "Data", objects that cannot contain non-map-word pointers to heap
732   // objects.
733   HEAP_NUMBER_TYPE,
734   FLOAT32x4_TYPE,
735   INT32x4_TYPE,
736   FOREIGN_TYPE,
737   BYTE_ARRAY_TYPE,
738   FREE_SPACE_TYPE,
739
740   EXTERNAL_INT8_ARRAY_TYPE,  // FIRST_EXTERNAL_ARRAY_TYPE
741   EXTERNAL_UINT8_ARRAY_TYPE,
742   EXTERNAL_INT16_ARRAY_TYPE,
743   EXTERNAL_UINT16_ARRAY_TYPE,
744   EXTERNAL_INT32_ARRAY_TYPE,
745   EXTERNAL_UINT32_ARRAY_TYPE,
746   EXTERNAL_FLOAT32_ARRAY_TYPE,
747   EXTERNAL_FLOAT32x4_ARRAY_TYPE,
748   EXTERNAL_INT32x4_ARRAY_TYPE,
749   EXTERNAL_FLOAT64_ARRAY_TYPE,
750   EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,  // LAST_EXTERNAL_ARRAY_TYPE
751
752   FIXED_INT8_ARRAY_TYPE,  // FIRST_FIXED_TYPED_ARRAY_TYPE
753   FIXED_UINT8_ARRAY_TYPE,
754   FIXED_INT16_ARRAY_TYPE,
755   FIXED_UINT16_ARRAY_TYPE,
756   FIXED_INT32_ARRAY_TYPE,
757   FIXED_INT32x4_ARRAY_TYPE,
758   FIXED_UINT32_ARRAY_TYPE,
759   FIXED_FLOAT32_ARRAY_TYPE,
760   FIXED_FLOAT32x4_ARRAY_TYPE,
761   FIXED_FLOAT64_ARRAY_TYPE,
762   FIXED_UINT8_CLAMPED_ARRAY_TYPE,  // LAST_FIXED_TYPED_ARRAY_TYPE
763
764   FIXED_DOUBLE_ARRAY_TYPE,
765   FILLER_TYPE,  // LAST_DATA_TYPE
766
767   // Structs.
768   DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
769   DECLARED_ACCESSOR_INFO_TYPE,
770   EXECUTABLE_ACCESSOR_INFO_TYPE,
771   ACCESSOR_PAIR_TYPE,
772   ACCESS_CHECK_INFO_TYPE,
773   INTERCEPTOR_INFO_TYPE,
774   CALL_HANDLER_INFO_TYPE,
775   FUNCTION_TEMPLATE_INFO_TYPE,
776   OBJECT_TEMPLATE_INFO_TYPE,
777   SIGNATURE_INFO_TYPE,
778   TYPE_SWITCH_INFO_TYPE,
779   ALLOCATION_SITE_TYPE,
780   ALLOCATION_MEMENTO_TYPE,
781   SCRIPT_TYPE,
782   CODE_CACHE_TYPE,
783   POLYMORPHIC_CODE_CACHE_TYPE,
784   TYPE_FEEDBACK_INFO_TYPE,
785   ALIASED_ARGUMENTS_ENTRY_TYPE,
786   BOX_TYPE,
787   // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
788   // is defined. However as include/v8.h contain some of the instance type
789   // constants always having them avoids them getting different numbers
790   // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
791   DEBUG_INFO_TYPE,
792   BREAK_POINT_INFO_TYPE,
793
794   FIXED_ARRAY_TYPE,
795   CONSTANT_POOL_ARRAY_TYPE,
796   SHARED_FUNCTION_INFO_TYPE,
797
798   JS_MESSAGE_OBJECT_TYPE,
799
800   // All the following types are subtypes of JSReceiver, which corresponds to
801   // objects in the JS sense. The first and the last type in this range are
802   // the two forms of function. This organization enables using the same
803   // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
804   // NONCALLABLE_JS_OBJECT range.
805   JS_FUNCTION_PROXY_TYPE,  // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
806   JS_PROXY_TYPE,  // LAST_JS_PROXY_TYPE
807
808   JS_VALUE_TYPE,  // FIRST_JS_OBJECT_TYPE
809   JS_DATE_TYPE,
810   JS_OBJECT_TYPE,
811   JS_CONTEXT_EXTENSION_OBJECT_TYPE,
812   JS_GENERATOR_OBJECT_TYPE,
813   JS_MODULE_TYPE,
814   JS_GLOBAL_OBJECT_TYPE,
815   JS_BUILTINS_OBJECT_TYPE,
816   JS_GLOBAL_PROXY_TYPE,
817   JS_ARRAY_TYPE,
818   JS_ARRAY_BUFFER_TYPE,
819   JS_TYPED_ARRAY_TYPE,
820   JS_DATA_VIEW_TYPE,
821   JS_SET_TYPE,
822   JS_MAP_TYPE,
823   JS_WEAK_MAP_TYPE,
824   JS_WEAK_SET_TYPE,
825
826   JS_REGEXP_TYPE,
827
828   JS_FUNCTION_TYPE,  // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
829
830   // Pseudo-types
831   FIRST_TYPE = 0x0,
832   LAST_TYPE = JS_FUNCTION_TYPE,
833   FIRST_NAME_TYPE = FIRST_TYPE,
834   LAST_NAME_TYPE = SYMBOL_TYPE,
835   FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
836   LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
837   FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
838   // Boundaries for testing for an external array.
839   FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
840   LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
841   // Boundaries for testing for a fixed typed array.
842   FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
843   LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
844   // Boundary for promotion to old data space/old pointer space.
845   LAST_DATA_TYPE = FILLER_TYPE,
846   // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
847   // Note that there is no range for JSObject or JSProxy, since their subtypes
848   // are not continuous in this enum! The enum ranges instead reflect the
849   // external class names, where proxies are treated as either ordinary objects,
850   // or functions.
851   FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
852   LAST_JS_RECEIVER_TYPE = LAST_TYPE,
853   // Boundaries for testing the types represented as JSObject
854   FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
855   LAST_JS_OBJECT_TYPE = LAST_TYPE,
856   // Boundaries for testing the types represented as JSProxy
857   FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
858   LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
859   // Boundaries for testing whether the type is a JavaScript object.
860   FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
861   LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
862   // Boundaries for testing the types for which typeof is "object".
863   FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
864   LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
865   // Note that the types for which typeof is "function" are not continuous.
866   // Define this so that we can put assertions on discrete checks.
867   NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
868 };
869
870 const int kExternalArrayTypeCount =
871     LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
872
873 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
874 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
875 STATIC_CHECK(ODDBALL_TYPE == Internals::kOddballType);
876 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
877
878
879 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
880   V(FAST_ELEMENTS_SUB_TYPE)                   \
881   V(DICTIONARY_ELEMENTS_SUB_TYPE)             \
882   V(FAST_PROPERTIES_SUB_TYPE)                 \
883   V(DICTIONARY_PROPERTIES_SUB_TYPE)           \
884   V(MAP_CODE_CACHE_SUB_TYPE)                  \
885   V(SCOPE_INFO_SUB_TYPE)                      \
886   V(STRING_TABLE_SUB_TYPE)                    \
887   V(DESCRIPTOR_ARRAY_SUB_TYPE)                \
888   V(TRANSITION_ARRAY_SUB_TYPE)
889
890 enum FixedArraySubInstanceType {
891 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
892   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
893 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
894   LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
895 };
896
897
898 enum CompareResult {
899   LESS      = -1,
900   EQUAL     =  0,
901   GREATER   =  1,
902
903   NOT_EQUAL = GREATER
904 };
905
906
907 #define DECL_BOOLEAN_ACCESSORS(name)   \
908   inline bool name();                  \
909   inline void set_##name(bool value);  \
910
911
912 #define DECL_ACCESSORS(name, type)                                      \
913   inline type* name();                                                  \
914   inline void set_##name(type* value,                                   \
915                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
916
917 class AccessorPair;
918 class AllocationSite;
919 class AllocationSiteCreationContext;
920 class AllocationSiteUsageContext;
921 class DictionaryElementsAccessor;
922 class ElementsAccessor;
923 class Failure;
924 class FixedArrayBase;
925 class GlobalObject;
926 class ObjectVisitor;
927 class StringStream;
928 // We cannot just say "class HeapType;" if it is created from a template... =8-?
929 template<class> class TypeImpl;
930 struct HeapTypeConfig;
931 typedef TypeImpl<HeapTypeConfig> HeapType;
932
933
934 // A template-ized version of the IsXXX functions.
935 template <class C> inline bool Is(Object* obj);
936
937 #ifdef VERIFY_HEAP
938 #define DECLARE_VERIFIER(Name) void Name##Verify();
939 #else
940 #define DECLARE_VERIFIER(Name)
941 #endif
942
943 #ifdef OBJECT_PRINT
944 #define DECLARE_PRINTER(Name) void Name##Print(FILE* out = stdout);
945 #else
946 #define DECLARE_PRINTER(Name)
947 #endif
948
949 class MaybeObject BASE_EMBEDDED {
950  public:
951   inline bool IsFailure();
952   inline bool IsRetryAfterGC();
953   inline bool IsException();
954   INLINE(bool IsTheHole());
955   INLINE(bool IsUninitialized());
956   inline bool ToObject(Object** obj) {
957     if (IsFailure()) return false;
958     *obj = reinterpret_cast<Object*>(this);
959     return true;
960   }
961   inline Failure* ToFailureUnchecked() {
962     ASSERT(IsFailure());
963     return reinterpret_cast<Failure*>(this);
964   }
965   inline Object* ToObjectUnchecked() {
966     // TODO(jkummerow): Turn this back into an ASSERT when we can be certain
967     // that it never fires in Release mode in the wild.
968     CHECK(!IsFailure());
969     return reinterpret_cast<Object*>(this);
970   }
971   inline Object* ToObjectChecked() {
972     CHECK(!IsFailure());
973     return reinterpret_cast<Object*>(this);
974   }
975
976   template<typename T>
977   inline bool To(T** obj) {
978     if (IsFailure()) return false;
979     *obj = T::cast(reinterpret_cast<Object*>(this));
980     return true;
981   }
982
983   template<typename T>
984     inline bool ToHandle(Handle<T>* obj, Isolate* isolate) {
985     if (IsFailure()) return false;
986     *obj = handle(T::cast(reinterpret_cast<Object*>(this)), isolate);
987     return true;
988   }
989
990 #ifdef OBJECT_PRINT
991   // Prints this object with details.
992   void Print();
993   void Print(FILE* out);
994   void PrintLn();
995   void PrintLn(FILE* out);
996 #endif
997 #ifdef VERIFY_HEAP
998   // Verifies the object.
999   void Verify();
1000 #endif
1001 };
1002
1003
1004 #define OBJECT_TYPE_LIST(V)                    \
1005   V(Smi)                                       \
1006   V(HeapObject)                                \
1007   V(Number)                                    \
1008
1009 #define HEAP_OBJECT_TYPE_LIST(V)               \
1010   V(HeapNumber)                                \
1011   V(Float32x4)                                 \
1012   V(Int32x4)                                  \
1013   V(Name)                                      \
1014   V(UniqueName)                                \
1015   V(String)                                    \
1016   V(SeqString)                                 \
1017   V(ExternalString)                            \
1018   V(ConsString)                                \
1019   V(SlicedString)                              \
1020   V(ExternalTwoByteString)                     \
1021   V(ExternalAsciiString)                       \
1022   V(SeqTwoByteString)                          \
1023   V(SeqOneByteString)                          \
1024   V(InternalizedString)                        \
1025   V(Symbol)                                    \
1026                                                \
1027   V(ExternalArray)                             \
1028   V(ExternalInt8Array)                         \
1029   V(ExternalUint8Array)                        \
1030   V(ExternalInt16Array)                        \
1031   V(ExternalUint16Array)                       \
1032   V(ExternalInt32Array)                        \
1033   V(ExternalUint32Array)                       \
1034   V(ExternalFloat32Array)                      \
1035   V(ExternalFloat32x4Array)                    \
1036   V(ExternalInt32x4Array)                      \
1037   V(ExternalFloat64Array)                      \
1038   V(ExternalUint8ClampedArray)                 \
1039   V(FixedTypedArrayBase)                       \
1040   V(FixedUint8Array)                           \
1041   V(FixedInt8Array)                            \
1042   V(FixedUint16Array)                          \
1043   V(FixedInt16Array)                           \
1044   V(FixedUint32Array)                          \
1045   V(FixedInt32Array)                           \
1046   V(FixedFloat32Array)                         \
1047   V(FixedFloat32x4Array)                       \
1048   V(FixedInt32x4Array)                         \
1049   V(FixedFloat64Array)                         \
1050   V(FixedUint8ClampedArray)                    \
1051   V(ByteArray)                                 \
1052   V(FreeSpace)                                 \
1053   V(JSReceiver)                                \
1054   V(JSObject)                                  \
1055   V(JSContextExtensionObject)                  \
1056   V(JSGeneratorObject)                         \
1057   V(JSModule)                                  \
1058   V(Map)                                       \
1059   V(DescriptorArray)                           \
1060   V(TransitionArray)                           \
1061   V(DeoptimizationInputData)                   \
1062   V(DeoptimizationOutputData)                  \
1063   V(DependentCode)                             \
1064   V(FixedArray)                                \
1065   V(FixedDoubleArray)                          \
1066   V(ConstantPoolArray)                         \
1067   V(Context)                                   \
1068   V(NativeContext)                             \
1069   V(ScopeInfo)                                 \
1070   V(JSFunction)                                \
1071   V(Code)                                      \
1072   V(Oddball)                                   \
1073   V(SharedFunctionInfo)                        \
1074   V(JSValue)                                   \
1075   V(JSDate)                                    \
1076   V(JSMessageObject)                           \
1077   V(StringWrapper)                             \
1078   V(Foreign)                                   \
1079   V(Boolean)                                   \
1080   V(JSArray)                                   \
1081   V(JSArrayBuffer)                             \
1082   V(JSArrayBufferView)                         \
1083   V(JSTypedArray)                              \
1084   V(JSDataView)                                \
1085   V(JSProxy)                                   \
1086   V(JSFunctionProxy)                           \
1087   V(JSSet)                                     \
1088   V(JSMap)                                     \
1089   V(JSWeakCollection)                          \
1090   V(JSWeakMap)                                 \
1091   V(JSWeakSet)                                 \
1092   V(JSRegExp)                                  \
1093   V(HashTable)                                 \
1094   V(Dictionary)                                \
1095   V(StringTable)                               \
1096   V(JSFunctionResultCache)                     \
1097   V(NormalizedMapCache)                        \
1098   V(CompilationCacheTable)                     \
1099   V(CodeCacheHashTable)                        \
1100   V(PolymorphicCodeCacheHashTable)             \
1101   V(MapCache)                                  \
1102   V(Primitive)                                 \
1103   V(GlobalObject)                              \
1104   V(JSGlobalObject)                            \
1105   V(JSBuiltinsObject)                          \
1106   V(JSGlobalProxy)                             \
1107   V(UndetectableObject)                        \
1108   V(AccessCheckNeeded)                         \
1109   V(Cell)                                      \
1110   V(PropertyCell)                              \
1111   V(ObjectHashTable)                           \
1112   V(WeakHashTable)
1113
1114
1115 #define ERROR_MESSAGES_LIST(V) \
1116   V(kNoReason, "no reason")                                                   \
1117                                                                               \
1118   V(k32BitValueInRegisterIsNotZeroExtended,                                   \
1119     "32 bit value in register is not zero-extended")                          \
1120   V(kAlignmentMarkerExpected, "Alignment marker expected")                    \
1121   V(kAllocationIsNotDoubleAligned, "Allocation is not double aligned")        \
1122   V(kAPICallReturnedInvalidObject, "API call returned invalid object")        \
1123   V(kArgumentsObjectValueInATestContext,                                      \
1124     "Arguments object value in a test context")                               \
1125   V(kArrayBoilerplateCreationFailed, "Array boilerplate creation failed")     \
1126   V(kArrayIndexConstantValueTooBig, "Array index constant value too big")     \
1127   V(kAssignmentToArguments, "Assignment to arguments")                        \
1128   V(kAssignmentToLetVariableBeforeInitialization,                             \
1129     "Assignment to let variable before initialization")                       \
1130   V(kAssignmentToLOOKUPVariable, "Assignment to LOOKUP variable")             \
1131   V(kAssignmentToParameterFunctionUsesArgumentsObject,                        \
1132     "Assignment to parameter, function uses arguments object")                \
1133   V(kAssignmentToParameterInArgumentsObject,                                  \
1134     "Assignment to parameter in arguments object")                            \
1135   V(kAttemptToUseUndefinedCache, "Attempt to use undefined cache")            \
1136   V(kBadValueContextForArgumentsObjectValue,                                  \
1137     "Bad value context for arguments object value")                           \
1138   V(kBadValueContextForArgumentsValue,                                        \
1139     "Bad value context for arguments value")                                  \
1140   V(kBailedOutDueToDependencyChange, "Bailed out due to dependency change")   \
1141   V(kBailoutWasNotPrepared, "Bailout was not prepared")                       \
1142   V(kBinaryStubGenerateFloatingPointCode,                                     \
1143     "BinaryStub_GenerateFloatingPointCode")                                   \
1144   V(kBothRegistersWereSmisInSelectNonSmi,                                     \
1145     "Both registers were smis in SelectNonSmi")                               \
1146   V(kCallToAJavaScriptRuntimeFunction,                                        \
1147     "Call to a JavaScript runtime function")                                  \
1148   V(kCannotTranslatePositionInChangedArea,                                    \
1149     "Cannot translate position in changed area")                              \
1150   V(kCodeGenerationFailed, "Code generation failed")                          \
1151   V(kCodeObjectNotProperlyPatched, "Code object not properly patched")        \
1152   V(kCompoundAssignmentToLookupSlot, "Compound assignment to lookup slot")    \
1153   V(kContextAllocatedArguments, "Context-allocated arguments")                \
1154   V(kCopyBuffersOverlap, "Copy buffers overlap")                              \
1155   V(kCouldNotGenerateZero, "Could not generate +0.0")                         \
1156   V(kCouldNotGenerateNegativeZero, "Could not generate -0.0")                 \
1157   V(kDebuggerIsActive, "Debugger is active")                                  \
1158   V(kDebuggerStatement, "DebuggerStatement")                                  \
1159   V(kDeclarationInCatchContext, "Declaration in catch context")               \
1160   V(kDeclarationInWithContext, "Declaration in with context")                 \
1161   V(kDefaultNaNModeNotSet, "Default NaN mode not set")                        \
1162   V(kDeleteWithGlobalVariable, "Delete with global variable")                 \
1163   V(kDeleteWithNonGlobalVariable, "Delete with non-global variable")          \
1164   V(kDestinationOfCopyNotAligned, "Destination of copy not aligned")          \
1165   V(kDontDeleteCellsCannotContainTheHole,                                     \
1166     "DontDelete cells can't contain the hole")                                \
1167   V(kDoPushArgumentNotImplementedForDoubleType,                               \
1168     "DoPushArgument not implemented for double type")                         \
1169   V(kEliminatedBoundsCheckFailed, "Eliminated bounds check failed")           \
1170   V(kEmitLoadRegisterUnsupportedDoubleImmediate,                              \
1171     "EmitLoadRegister: Unsupported double immediate")                         \
1172   V(kEval, "eval")                                                            \
1173   V(kExpected0AsASmiSentinel, "Expected 0 as a Smi sentinel")                 \
1174   V(kExpectedAlignmentMarker, "Expected alignment marker")                    \
1175   V(kExpectedAllocationSite, "Expected allocation site")                      \
1176   V(kExpectedFunctionObject, "Expected function object in register")          \
1177   V(kExpectedHeapNumber, "Expected HeapNumber")                               \
1178   V(kExpectedNativeContext, "Expected native context")                        \
1179   V(kExpectedNonIdenticalObjects, "Expected non-identical objects")           \
1180   V(kExpectedNonNullContext, "Expected non-null context")                     \
1181   V(kExpectedPositiveZero, "Expected +0.0")                                   \
1182   V(kExpectedAllocationSiteInCell,                                            \
1183     "Expected AllocationSite in property cell")                               \
1184   V(kExpectedFixedArrayInFeedbackVector,                                      \
1185     "Expected fixed array in feedback vector")                                \
1186   V(kExpectedFixedArrayInRegisterA2,                                          \
1187     "Expected fixed array in register a2")                                    \
1188   V(kExpectedFixedArrayInRegisterEbx,                                         \
1189     "Expected fixed array in register ebx")                                   \
1190   V(kExpectedFixedArrayInRegisterR2,                                          \
1191     "Expected fixed array in register r2")                                    \
1192   V(kExpectedFixedArrayInRegisterRbx,                                         \
1193     "Expected fixed array in register rbx")                                   \
1194   V(kExpectedSmiOrHeapNumber, "Expected smi or HeapNumber")                   \
1195   V(kExpectedUndefinedOrCell,                                                 \
1196     "Expected undefined or cell in register")                                 \
1197   V(kExpectingAlignmentForCopyBytes,                                          \
1198     "Expecting alignment for CopyBytes")                                      \
1199   V(kExportDeclaration, "Export declaration")                                 \
1200   V(kExternalStringExpectedButNotFound,                                       \
1201     "External string expected, but not found")                                \
1202   V(kFailedBailedOutLastTime, "Failed/bailed out last time")                  \
1203   V(kForInStatementIsNotFastCase, "ForInStatement is not fast case")          \
1204   V(kForInStatementOptimizationIsDisabled,                                    \
1205     "ForInStatement optimization is disabled")                                \
1206   V(kForInStatementWithNonLocalEachVariable,                                  \
1207     "ForInStatement with non-local each variable")                            \
1208   V(kForOfStatement, "ForOfStatement")                                        \
1209   V(kFrameIsExpectedToBeAligned, "Frame is expected to be aligned")           \
1210   V(kFunctionCallsEval, "Function calls eval")                                \
1211   V(kFunctionIsAGenerator, "Function is a generator")                         \
1212   V(kFunctionWithIllegalRedeclaration, "Function with illegal redeclaration") \
1213   V(kGeneratedCodeIsTooLarge, "Generated code is too large")                  \
1214   V(kGeneratorFailedToResume, "Generator failed to resume")                   \
1215   V(kGenerator, "Generator")                                                  \
1216   V(kGlobalFunctionsMustHaveInitialMap,                                       \
1217     "Global functions must have initial map")                                 \
1218   V(kHeapNumberMapRegisterClobbered, "HeapNumberMap register clobbered")      \
1219   V(kHydrogenFilter, "Optimization disabled by filter")                       \
1220   V(kImportDeclaration, "Import declaration")                                 \
1221   V(kImproperObjectOnPrototypeChainForStore,                                  \
1222     "Improper object on prototype chain for store")                           \
1223   V(kIndexIsNegative, "Index is negative")                                    \
1224   V(kIndexIsTooLarge, "Index is too large")                                   \
1225   V(kInlinedRuntimeFunctionClassOf, "Inlined runtime function: ClassOf")      \
1226   V(kInlinedRuntimeFunctionFastAsciiArrayJoin,                                \
1227     "Inlined runtime function: FastAsciiArrayJoin")                           \
1228   V(kInlinedRuntimeFunctionGeneratorNext,                                     \
1229     "Inlined runtime function: GeneratorNext")                                \
1230   V(kInlinedRuntimeFunctionGeneratorThrow,                                    \
1231     "Inlined runtime function: GeneratorThrow")                               \
1232   V(kInlinedRuntimeFunctionGetFromCache,                                      \
1233     "Inlined runtime function: GetFromCache")                                 \
1234   V(kInlinedRuntimeFunctionIsNonNegativeSmi,                                  \
1235     "Inlined runtime function: IsNonNegativeSmi")                             \
1236   V(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf,              \
1237     "Inlined runtime function: IsStringWrapperSafeForDefaultValueOf")         \
1238   V(kInliningBailedOut, "Inlining bailed out")                                \
1239   V(kInputGPRIsExpectedToHaveUpper32Cleared,                                  \
1240     "Input GPR is expected to have upper32 cleared")                          \
1241   V(kInputStringTooLong, "Input string too long")                             \
1242   V(kInstanceofStubUnexpectedCallSiteCacheCheck,                              \
1243     "InstanceofStub unexpected call site cache (check)")                      \
1244   V(kInstanceofStubUnexpectedCallSiteCacheCmp1,                               \
1245     "InstanceofStub unexpected call site cache (cmp 1)")                      \
1246   V(kInstanceofStubUnexpectedCallSiteCacheCmp2,                               \
1247     "InstanceofStub unexpected call site cache (cmp 2)")                      \
1248   V(kInstanceofStubUnexpectedCallSiteCacheMov,                                \
1249     "InstanceofStub unexpected call site cache (mov)")                        \
1250   V(kInteger32ToSmiFieldWritingToNonSmiLocation,                              \
1251     "Integer32ToSmiField writing to non-smi location")                        \
1252   V(kInvalidCaptureReferenced, "Invalid capture referenced")                  \
1253   V(kInvalidElementsKindForInternalArrayOrInternalPackedArray,                \
1254     "Invalid ElementsKind for InternalArray or InternalPackedArray")          \
1255   V(kInvalidFullCodegenState, "invalid full-codegen state")                   \
1256   V(kInvalidHandleScopeLevel, "Invalid HandleScope level")                    \
1257   V(kInvalidLeftHandSideInAssignment, "Invalid left-hand side in assignment") \
1258   V(kInvalidLhsInCompoundAssignment, "Invalid lhs in compound assignment")    \
1259   V(kInvalidLhsInCountOperation, "Invalid lhs in count operation")            \
1260   V(kInvalidMinLength, "Invalid min_length")                                  \
1261   V(kJSGlobalObjectNativeContextShouldBeANativeContext,                       \
1262     "JSGlobalObject::native_context should be a native context")              \
1263   V(kJSGlobalProxyContextShouldNotBeNull,                                     \
1264     "JSGlobalProxy::context() should not be null")                            \
1265   V(kJSObjectWithFastElementsMapHasSlowElements,                              \
1266     "JSObject with fast elements map has slow elements")                      \
1267   V(kLetBindingReInitialization, "Let binding re-initialization")             \
1268   V(kLhsHasBeenClobbered, "lhs has been clobbered")                           \
1269   V(kLiveBytesCountOverflowChunkSize, "Live Bytes Count overflow chunk size") \
1270   V(kLiveEditFrameDroppingIsNotSupportedOnARM64,                              \
1271     "LiveEdit frame dropping is not supported on arm64")                      \
1272   V(kLiveEditFrameDroppingIsNotSupportedOnArm,                                \
1273     "LiveEdit frame dropping is not supported on arm")                        \
1274   V(kLiveEditFrameDroppingIsNotSupportedOnMips,                               \
1275     "LiveEdit frame dropping is not supported on mips")                       \
1276   V(kLiveEdit, "LiveEdit")                                                    \
1277   V(kLookupVariableInCountOperation,                                          \
1278     "Lookup variable in count operation")                                     \
1279   V(kMapIsNoLongerInEax, "Map is no longer in eax")                           \
1280   V(kModuleDeclaration, "Module declaration")                                 \
1281   V(kModuleLiteral, "Module literal")                                         \
1282   V(kModulePath, "Module path")                                               \
1283   V(kModuleStatement, "Module statement")                                     \
1284   V(kModuleVariable, "Module variable")                                       \
1285   V(kModuleUrl, "Module url")                                                 \
1286   V(kNativeFunctionLiteral, "Native function literal")                        \
1287   V(kNoCasesLeft, "No cases left")                                            \
1288   V(kNoEmptyArraysHereInEmitFastAsciiArrayJoin,                               \
1289     "No empty arrays here in EmitFastAsciiArrayJoin")                         \
1290   V(kNonInitializerAssignmentToConst,                                         \
1291     "Non-initializer assignment to const")                                    \
1292   V(kNonSmiIndex, "Non-smi index")                                            \
1293   V(kNonSmiKeyInArrayLiteral, "Non-smi key in array literal")                 \
1294   V(kNonSmiValue, "Non-smi value")                                            \
1295   V(kNonObject, "Non-object value")                                           \
1296   V(kNotEnoughVirtualRegistersForValues,                                      \
1297     "Not enough virtual registers for values")                                \
1298   V(kNotEnoughSpillSlotsForOsr,                                               \
1299     "Not enough spill slots for OSR")                                         \
1300   V(kNotEnoughVirtualRegistersRegalloc,                                       \
1301     "Not enough virtual registers (regalloc)")                                \
1302   V(kObjectFoundInSmiOnlyArray, "Object found in smi-only array")             \
1303   V(kObjectLiteralWithComplexProperty,                                        \
1304     "Object literal with complex property")                                   \
1305   V(kOddballInStringTableIsNotUndefinedOrTheHole,                             \
1306     "Oddball in string table is not undefined or the hole")                   \
1307   V(kOffsetOutOfRange, "Offset out of range")                                 \
1308   V(kOperandIsASmiAndNotAName, "Operand is a smi and not a name")             \
1309   V(kOperandIsASmiAndNotAString, "Operand is a smi and not a string")         \
1310   V(kOperandIsASmi, "Operand is a smi")                                       \
1311   V(kOperandIsNotAName, "Operand is not a name")                              \
1312   V(kOperandIsNotANumber, "Operand is not a number")                          \
1313   V(kOperandIsNotASmi, "Operand is not a smi")                                \
1314   V(kOperandIsNotAString, "Operand is not a string")                          \
1315   V(kOperandIsNotSmi, "Operand is not smi")                                   \
1316   V(kOperandNotANumber, "Operand not a number")                               \
1317   V(kOptimizationDisabled, "Optimization is disabled")                        \
1318   V(kOptimizedTooManyTimes, "Optimized too many times")                       \
1319   V(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister,                  \
1320     "Out of virtual registers while trying to allocate temp register")        \
1321   V(kParseScopeError, "Parse/scope error")                                    \
1322   V(kPossibleDirectCallToEval, "Possible direct call to eval")                \
1323   V(kPreconditionsWereNotMet, "Preconditions were not met")                   \
1324   V(kPropertyAllocationCountFailed, "Property allocation count failed")       \
1325   V(kReceivedInvalidReturnAddress, "Received invalid return address")         \
1326   V(kReferenceToAVariableWhichRequiresDynamicLookup,                          \
1327     "Reference to a variable which requires dynamic lookup")                  \
1328   V(kReferenceToGlobalLexicalVariable,                                        \
1329     "Reference to global lexical variable")                                   \
1330   V(kReferenceToUninitializedVariable, "Reference to uninitialized variable") \
1331   V(kRegisterDidNotMatchExpectedRoot, "Register did not match expected root") \
1332   V(kRegisterWasClobbered, "Register was clobbered")                          \
1333   V(kRememberedSetPointerInNewSpace, "Remembered set pointer is in new space") \
1334   V(kReturnAddressNotFoundInFrame, "Return address not found in frame")       \
1335   V(kRhsHasBeenClobbered, "Rhs has been clobbered")                           \
1336   V(kScopedBlock, "ScopedBlock")                                              \
1337   V(kSmiAdditionOverflow, "Smi addition overflow")                            \
1338   V(kSmiSubtractionOverflow, "Smi subtraction overflow")                      \
1339   V(kStackAccessBelowStackPointer, "Stack access below stack pointer")        \
1340   V(kStackFrameTypesMustMatch, "Stack frame types must match")                \
1341   V(kSwitchStatementMixedOrNonLiteralSwitchLabels,                            \
1342     "SwitchStatement: mixed or non-literal switch labels")                    \
1343   V(kSwitchStatementTooManyClauses, "SwitchStatement: too many clauses")      \
1344   V(kTheCurrentStackPointerIsBelowCsp,                                        \
1345     "The current stack pointer is below csp")                                 \
1346   V(kTheInstructionShouldBeALui, "The instruction should be a lui")           \
1347   V(kTheInstructionShouldBeAnOri, "The instruction should be an ori")         \
1348   V(kTheInstructionToPatchShouldBeALoadFromPc,                                \
1349     "The instruction to patch should be a load from pc")                      \
1350   V(kTheInstructionToPatchShouldBeALoadFromPp,                                \
1351     "The instruction to patch should be a load from pp")                      \
1352   V(kTheInstructionToPatchShouldBeAnLdrLiteral,                               \
1353     "The instruction to patch should be a ldr literal")                       \
1354   V(kTheInstructionToPatchShouldBeALui,                                       \
1355     "The instruction to patch should be a lui")                               \
1356   V(kTheInstructionToPatchShouldBeAnOri,                                      \
1357     "The instruction to patch should be an ori")                              \
1358   V(kTheSourceAndDestinationAreTheSame,                                       \
1359     "The source and destination are the same")                                \
1360   V(kTheStackPointerIsNotAligned, "The stack pointer is not aligned.")        \
1361   V(kTheStackWasCorruptedByMacroAssemblerCall,                                \
1362     "The stack was corrupted by MacroAssembler::Call()")                      \
1363   V(kTooManyParametersLocals, "Too many parameters/locals")                   \
1364   V(kTooManyParameters, "Too many parameters")                                \
1365   V(kTooManySpillSlotsNeededForOSR, "Too many spill slots needed for OSR")    \
1366   V(kToOperand32UnsupportedImmediate, "ToOperand32 unsupported immediate.")   \
1367   V(kToOperandIsDoubleRegisterUnimplemented,                                  \
1368     "ToOperand IsDoubleRegister unimplemented")                               \
1369   V(kToOperandUnsupportedDoubleImmediate,                                     \
1370     "ToOperand Unsupported double immediate")                                 \
1371   V(kTryCatchStatement, "TryCatchStatement")                                  \
1372   V(kTryFinallyStatement, "TryFinallyStatement")                              \
1373   V(kUnableToEncodeValueAsSmi, "Unable to encode value as smi")               \
1374   V(kUnalignedAllocationInNewSpace, "Unaligned allocation in new space")      \
1375   V(kUnalignedCellInWriteBarrier, "Unaligned cell in write barrier")          \
1376   V(kUndefinedValueNotLoaded, "Undefined value not loaded")                   \
1377   V(kUndoAllocationOfNonAllocatedMemory,                                      \
1378     "Undo allocation of non allocated memory")                                \
1379   V(kUnexpectedAllocationTop, "Unexpected allocation top")                    \
1380   V(kUnexpectedColorFound, "Unexpected color bit pattern found")              \
1381   V(kUnexpectedElementsKindInArrayConstructor,                                \
1382     "Unexpected ElementsKind in array constructor")                           \
1383   V(kUnexpectedFallthroughFromCharCodeAtSlowCase,                             \
1384     "Unexpected fallthrough from CharCodeAt slow case")                       \
1385   V(kUnexpectedFallthroughFromCharFromCodeSlowCase,                           \
1386     "Unexpected fallthrough from CharFromCode slow case")                     \
1387   V(kUnexpectedFallThroughFromStringComparison,                               \
1388     "Unexpected fall-through from string comparison")                         \
1389   V(kUnexpectedFallThroughInBinaryStubGenerateFloatingPointCode,              \
1390     "Unexpected fall-through in BinaryStub_GenerateFloatingPointCode")        \
1391   V(kUnexpectedFallthroughToCharCodeAtSlowCase,                               \
1392     "Unexpected fallthrough to CharCodeAt slow case")                         \
1393   V(kUnexpectedFallthroughToCharFromCodeSlowCase,                             \
1394     "Unexpected fallthrough to CharFromCode slow case")                       \
1395   V(kUnexpectedFPUStackDepthAfterInstruction,                                 \
1396     "Unexpected FPU stack depth after instruction")                           \
1397   V(kUnexpectedInitialMapForArrayFunction1,                                   \
1398     "Unexpected initial map for Array function (1)")                          \
1399   V(kUnexpectedInitialMapForArrayFunction2,                                   \
1400     "Unexpected initial map for Array function (2)")                          \
1401   V(kUnexpectedInitialMapForArrayFunction,                                    \
1402     "Unexpected initial map for Array function")                              \
1403   V(kUnexpectedInitialMapForInternalArrayFunction,                            \
1404     "Unexpected initial map for InternalArray function")                      \
1405   V(kUnexpectedLevelAfterReturnFromApiCall,                                   \
1406     "Unexpected level after return from api call")                            \
1407   V(kUnexpectedNegativeValue, "Unexpected negative value")                    \
1408   V(kUnexpectedNumberOfPreAllocatedPropertyFields,                            \
1409     "Unexpected number of pre-allocated property fields")                     \
1410   V(kUnexpectedSmi, "Unexpected smi value")                                   \
1411   V(kUnexpectedStringFunction, "Unexpected String function")                  \
1412   V(kUnexpectedStringType, "Unexpected string type")                          \
1413   V(kUnexpectedStringWrapperInstanceSize,                                     \
1414     "Unexpected string wrapper instance size")                                \
1415   V(kUnexpectedTypeForRegExpDataFixedArrayExpected,                           \
1416     "Unexpected type for RegExp data, FixedArray expected")                   \
1417   V(kUnexpectedValue, "Unexpected value")                                     \
1418   V(kUnexpectedUnusedPropertiesOfStringWrapper,                               \
1419     "Unexpected unused properties of string wrapper")                         \
1420   V(kUnimplemented, "unimplemented")                                          \
1421   V(kUninitializedKSmiConstantRegister, "Uninitialized kSmiConstantRegister") \
1422   V(kUnknown, "Unknown")                                                      \
1423   V(kUnsupportedConstCompoundAssignment,                                      \
1424     "Unsupported const compound assignment")                                  \
1425   V(kUnsupportedCountOperationWithConst,                                      \
1426     "Unsupported count operation with const")                                 \
1427   V(kUnsupportedDoubleImmediate, "Unsupported double immediate")              \
1428   V(kUnsupportedLetCompoundAssignment, "Unsupported let compound assignment") \
1429   V(kUnsupportedLookupSlotInDeclaration,                                      \
1430     "Unsupported lookup slot in declaration")                                 \
1431   V(kUnsupportedNonPrimitiveCompare, "Unsupported non-primitive compare")     \
1432   V(kUnsupportedPhiUseOfArguments, "Unsupported phi use of arguments")        \
1433   V(kUnsupportedPhiUseOfConstVariable,                                        \
1434     "Unsupported phi use of const variable")                                  \
1435   V(kUnsupportedTaggedImmediate, "Unsupported tagged immediate")              \
1436   V(kVariableResolvedToWithContext, "Variable resolved to with context")      \
1437   V(kWeShouldNotHaveAnEmptyLexicalContext,                                    \
1438     "We should not have an empty lexical context")                            \
1439   V(kWithStatement, "WithStatement")                                          \
1440   V(kWrongAddressOrValuePassedToRecordWrite,                                  \
1441     "Wrong address or value passed to RecordWrite")                           \
1442   V(kYield, "Yield")
1443
1444
1445 #define ERROR_MESSAGES_CONSTANTS(C, T) C,
1446 enum BailoutReason {
1447   ERROR_MESSAGES_LIST(ERROR_MESSAGES_CONSTANTS)
1448   kLastErrorMessage
1449 };
1450 #undef ERROR_MESSAGES_CONSTANTS
1451
1452
1453 const char* GetBailoutReason(BailoutReason reason);
1454
1455
1456 // Object is the abstract superclass for all classes in the
1457 // object hierarchy.
1458 // Object does not use any virtual functions to avoid the
1459 // allocation of the C++ vtable.
1460 // Since Smi and Failure are subclasses of Object no
1461 // data members can be present in Object.
1462 class Object : public MaybeObject {
1463  public:
1464   // Type testing.
1465   bool IsObject() { return true; }
1466
1467 #define IS_TYPE_FUNCTION_DECL(type_)  inline bool Is##type_();
1468   OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1469   HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1470 #undef IS_TYPE_FUNCTION_DECL
1471
1472   inline bool IsFixedArrayBase();
1473   inline bool IsExternal();
1474   inline bool IsAccessorInfo();
1475
1476   inline bool IsStruct();
1477 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
1478   STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1479 #undef DECLARE_STRUCT_PREDICATE
1480
1481   INLINE(bool IsSpecObject());
1482   INLINE(bool IsSpecFunction());
1483   bool IsCallable();
1484
1485   // Oddball testing.
1486   INLINE(bool IsUndefined());
1487   INLINE(bool IsNull());
1488   INLINE(bool IsTheHole());  // Shadows MaybeObject's implementation.
1489   INLINE(bool IsUninitialized());
1490   INLINE(bool IsTrue());
1491   INLINE(bool IsFalse());
1492   inline bool IsArgumentsMarker();
1493   inline bool NonFailureIsHeapObject();
1494
1495   // Filler objects (fillers and free space objects).
1496   inline bool IsFiller();
1497
1498   // Extract the number.
1499   inline double Number();
1500   inline bool IsNaN();
1501   bool ToInt32(int32_t* value);
1502   bool ToUint32(uint32_t* value);
1503
1504   // Indicates whether OptimalRepresentation can do its work, or whether it
1505   // always has to return Representation::Tagged().
1506   enum ValueType {
1507     OPTIMAL_REPRESENTATION,
1508     FORCE_TAGGED
1509   };
1510
1511   inline Representation OptimalRepresentation(
1512       ValueType type = OPTIMAL_REPRESENTATION) {
1513     if (!FLAG_track_fields) return Representation::Tagged();
1514     if (type == FORCE_TAGGED) return Representation::Tagged();
1515     if (IsSmi()) {
1516       return Representation::Smi();
1517     } else if (FLAG_track_double_fields && IsHeapNumber()) {
1518       return Representation::Double();
1519     } else if (FLAG_track_computed_fields && IsUninitialized()) {
1520       return Representation::None();
1521     } else if (FLAG_track_heap_object_fields) {
1522       ASSERT(IsHeapObject());
1523       return Representation::HeapObject();
1524     } else {
1525       return Representation::Tagged();
1526     }
1527   }
1528
1529   inline bool FitsRepresentation(Representation representation) {
1530     if (FLAG_track_fields && representation.IsNone()) {
1531       return false;
1532     } else if (FLAG_track_fields && representation.IsSmi()) {
1533       return IsSmi();
1534     } else if (FLAG_track_double_fields && representation.IsDouble()) {
1535       return IsNumber();
1536     } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1537       return IsHeapObject();
1538     }
1539     return true;
1540   }
1541
1542   inline MaybeObject* AllocateNewStorageFor(Heap* heap,
1543                                             Representation representation);
1544
1545   // Returns true if the object is of the correct type to be used as a
1546   // implementation of a JSObject's elements.
1547   inline bool HasValidElements();
1548
1549   inline bool HasSpecificClassOf(String* name);
1550
1551   MUST_USE_RESULT MaybeObject* ToObject(Isolate* isolate);  // ECMA-262 9.9.
1552   bool BooleanValue();                                      // ECMA-262 9.2.
1553
1554   // Convert to a JSObject if needed.
1555   // native_context is used when creating wrapper object.
1556   MUST_USE_RESULT MaybeObject* ToObject(Context* native_context);
1557
1558   // Converts this to a Smi if possible.
1559   // Failure is returned otherwise.
1560   static MUST_USE_RESULT inline Handle<Object> ToSmi(Isolate* isolate,
1561                                                      Handle<Object> object);
1562   MUST_USE_RESULT inline MaybeObject* ToSmi();
1563
1564   void Lookup(Name* name, LookupResult* result);
1565
1566   // Property access.
1567   MUST_USE_RESULT inline MaybeObject* GetProperty(Name* key);
1568   MUST_USE_RESULT inline MaybeObject* GetProperty(
1569       Name* key,
1570       PropertyAttributes* attributes);
1571
1572   // TODO(yangguo): this should eventually replace the non-handlified version.
1573   static Handle<Object> GetPropertyWithReceiver(Handle<Object> object,
1574                                                 Handle<Object> receiver,
1575                                                 Handle<Name> name,
1576                                                 PropertyAttributes* attributes);
1577   MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
1578       Object* receiver,
1579       Name* key,
1580       PropertyAttributes* attributes);
1581
1582   static Handle<Object> GetProperty(Handle<Object> object,
1583                                     Handle<Name> key);
1584   static Handle<Object> GetProperty(Handle<Object> object,
1585                                     Handle<Object> receiver,
1586                                     LookupResult* result,
1587                                     Handle<Name> key,
1588                                     PropertyAttributes* attributes);
1589
1590   MUST_USE_RESULT static MaybeObject* GetPropertyOrFail(
1591       Handle<Object> object,
1592       Handle<Object> receiver,
1593       LookupResult* result,
1594       Handle<Name> key,
1595       PropertyAttributes* attributes);
1596
1597   MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
1598                                            LookupResult* result,
1599                                            Name* key,
1600                                            PropertyAttributes* attributes);
1601
1602   MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
1603                                                             JSReceiver* getter);
1604
1605   static inline Handle<Object> GetElement(Isolate* isolate,
1606                                           Handle<Object> object,
1607                                           uint32_t index);
1608
1609   // For use when we know that no exception can be thrown.
1610   static inline Handle<Object> GetElementNoExceptionThrown(
1611       Isolate* isolate,
1612       Handle<Object> object,
1613       uint32_t index);
1614
1615   static Handle<Object> GetElementWithReceiver(Isolate* isolate,
1616                                                Handle<Object> object,
1617                                                Handle<Object> receiver,
1618                                                uint32_t index);
1619
1620   // Return the object's prototype (might be Heap::null_value()).
1621   Object* GetPrototype(Isolate* isolate);
1622   Map* GetMarkerMap(Isolate* isolate);
1623
1624   // Returns the permanent hash code associated with this object. May return
1625   // undefined if not yet created.
1626   Object* GetHash();
1627
1628   // Returns the permanent hash code associated with this object depending on
1629   // the actual object type. May create and store a hash code if needed and none
1630   // exists.
1631   // TODO(rafaelw): Remove isolate parameter when objects.cc is fully
1632   // handlified.
1633   static Handle<Object> GetOrCreateHash(Handle<Object> object,
1634                                         Isolate* isolate);
1635
1636   // Checks whether this object has the same value as the given one.  This
1637   // function is implemented according to ES5, section 9.12 and can be used
1638   // to implement the Harmony "egal" function.
1639   bool SameValue(Object* other);
1640
1641   // Tries to convert an object to an array index.  Returns true and sets
1642   // the output parameter if it succeeds.
1643   inline bool ToArrayIndex(uint32_t* index);
1644
1645   // Returns true if this is a JSValue containing a string and the index is
1646   // < the length of the string.  Used to implement [] on strings.
1647   inline bool IsStringObjectWithCharacterAt(uint32_t index);
1648
1649 #ifdef VERIFY_HEAP
1650   // Verify a pointer is a valid object pointer.
1651   static void VerifyPointer(Object* p);
1652 #endif
1653
1654   inline void VerifyApiCallResultType();
1655
1656   // Prints this object without details.
1657   void ShortPrint(FILE* out = stdout);
1658
1659   // Prints this object without details to a message accumulator.
1660   void ShortPrint(StringStream* accumulator);
1661
1662   // Casting: This cast is only needed to satisfy macros in objects-inl.h.
1663   static Object* cast(Object* value) { return value; }
1664
1665   // Layout description.
1666   static const int kHeaderSize = 0;  // Object does not take up any space.
1667
1668  private:
1669   DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1670 };
1671
1672
1673 // Smi represents integer Numbers that can be stored in 31 bits.
1674 // Smis are immediate which means they are NOT allocated in the heap.
1675 // The this pointer has the following format: [31 bit signed int] 0
1676 // For long smis it has the following format:
1677 //     [32 bit signed int] [31 bits zero padding] 0
1678 // Smi stands for small integer.
1679 class Smi: public Object {
1680  public:
1681   // Returns the integer value.
1682   inline int value();
1683
1684   // Convert a value to a Smi object.
1685   static inline Smi* FromInt(int value);
1686
1687   static inline Smi* FromIntptr(intptr_t value);
1688
1689   // Returns whether value can be represented in a Smi.
1690   static inline bool IsValid(intptr_t value);
1691
1692   // Casting.
1693   static inline Smi* cast(Object* object);
1694
1695   // Dispatched behavior.
1696   void SmiPrint(FILE* out = stdout);
1697   void SmiPrint(StringStream* accumulator);
1698
1699   DECLARE_VERIFIER(Smi)
1700
1701   static const int kMinValue =
1702       (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1703   static const int kMaxValue = -(kMinValue + 1);
1704
1705  private:
1706   DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1707 };
1708
1709
1710 // Failure is used for reporting out of memory situations and
1711 // propagating exceptions through the runtime system.  Failure objects
1712 // are transient and cannot occur as part of the object graph.
1713 //
1714 // Failures are a single word, encoded as follows:
1715 // +-------------------------+---+--+--+
1716 // |.........unused..........|sss|tt|11|
1717 // +-------------------------+---+--+--+
1718 //                          7 6 4 32 10
1719 //
1720 //
1721 // The low two bits, 0-1, are the failure tag, 11.  The next two bits,
1722 // 2-3, are a failure type tag 'tt' with possible values:
1723 //   00 RETRY_AFTER_GC
1724 //   01 EXCEPTION
1725 //   10 INTERNAL_ERROR
1726 //   11 OUT_OF_MEMORY_EXCEPTION
1727 //
1728 // The next three bits, 4-6, are an allocation space tag 'sss'.  The
1729 // allocation space tag is 000 for all failure types except
1730 // RETRY_AFTER_GC.  For RETRY_AFTER_GC, the possible values are the
1731 // allocation spaces (the encoding is found in globals.h).
1732
1733 // Failure type tag info.
1734 const int kFailureTypeTagSize = 2;
1735 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1736
1737 class Failure: public MaybeObject {
1738  public:
1739   // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1740   enum Type {
1741     RETRY_AFTER_GC = 0,
1742     EXCEPTION = 1,       // Returning this marker tells the real exception
1743                          // is in Isolate::pending_exception.
1744     INTERNAL_ERROR = 2,
1745     OUT_OF_MEMORY_EXCEPTION = 3
1746   };
1747
1748   inline Type type() const;
1749
1750   // Returns the space that needs to be collected for RetryAfterGC failures.
1751   inline AllocationSpace allocation_space() const;
1752
1753   inline bool IsInternalError() const;
1754
1755   static inline Failure* RetryAfterGC(AllocationSpace space);
1756   static inline Failure* RetryAfterGC();  // NEW_SPACE
1757   static inline Failure* Exception();
1758   static inline Failure* InternalError();
1759   // Casting.
1760   static inline Failure* cast(MaybeObject* object);
1761
1762   // Dispatched behavior.
1763   void FailurePrint(FILE* out = stdout);
1764   void FailurePrint(StringStream* accumulator);
1765
1766   DECLARE_VERIFIER(Failure)
1767
1768  private:
1769   inline intptr_t value() const;
1770   static inline Failure* Construct(Type type, intptr_t value = 0);
1771
1772   DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1773 };
1774
1775
1776 // Heap objects typically have a map pointer in their first word.  However,
1777 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1778 // encoded in the first word.  The class MapWord is an abstraction of the
1779 // value in a heap object's first word.
1780 class MapWord BASE_EMBEDDED {
1781  public:
1782   // Normal state: the map word contains a map pointer.
1783
1784   // Create a map word from a map pointer.
1785   static inline MapWord FromMap(Map* map);
1786
1787   // View this map word as a map pointer.
1788   inline Map* ToMap();
1789
1790
1791   // Scavenge collection: the map word of live objects in the from space
1792   // contains a forwarding address (a heap object pointer in the to space).
1793
1794   // True if this map word is a forwarding address for a scavenge
1795   // collection.  Only valid during a scavenge collection (specifically,
1796   // when all map words are heap object pointers, i.e. not during a full GC).
1797   inline bool IsForwardingAddress();
1798
1799   // Create a map word from a forwarding address.
1800   static inline MapWord FromForwardingAddress(HeapObject* object);
1801
1802   // View this map word as a forwarding address.
1803   inline HeapObject* ToForwardingAddress();
1804
1805   static inline MapWord FromRawValue(uintptr_t value) {
1806     return MapWord(value);
1807   }
1808
1809   inline uintptr_t ToRawValue() {
1810     return value_;
1811   }
1812
1813  private:
1814   // HeapObject calls the private constructor and directly reads the value.
1815   friend class HeapObject;
1816
1817   explicit MapWord(uintptr_t value) : value_(value) {}
1818
1819   uintptr_t value_;
1820 };
1821
1822
1823 // HeapObject is the superclass for all classes describing heap allocated
1824 // objects.
1825 class HeapObject: public Object {
1826  public:
1827   // [map]: Contains a map which contains the object's reflective
1828   // information.
1829   inline Map* map();
1830   inline void set_map(Map* value);
1831   // The no-write-barrier version.  This is OK if the object is white and in
1832   // new space, or if the value is an immortal immutable object, like the maps
1833   // of primitive (non-JS) objects like strings, heap numbers etc.
1834   inline void set_map_no_write_barrier(Map* value);
1835
1836   // During garbage collection, the map word of a heap object does not
1837   // necessarily contain a map pointer.
1838   inline MapWord map_word();
1839   inline void set_map_word(MapWord map_word);
1840
1841   // The Heap the object was allocated in. Used also to access Isolate.
1842   inline Heap* GetHeap();
1843
1844   // Convenience method to get current isolate.
1845   inline Isolate* GetIsolate();
1846
1847   // Converts an address to a HeapObject pointer.
1848   static inline HeapObject* FromAddress(Address address);
1849
1850   // Returns the address of this HeapObject.
1851   inline Address address();
1852
1853   // Iterates over pointers contained in the object (including the Map)
1854   void Iterate(ObjectVisitor* v);
1855
1856   // Iterates over all pointers contained in the object except the
1857   // first map pointer.  The object type is given in the first
1858   // parameter. This function does not access the map pointer in the
1859   // object, and so is safe to call while the map pointer is modified.
1860   void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1861
1862   // Returns the heap object's size in bytes
1863   inline int Size();
1864
1865   // Given a heap object's map pointer, returns the heap size in bytes
1866   // Useful when the map pointer field is used for other purposes.
1867   // GC internal.
1868   inline int SizeFromMap(Map* map);
1869
1870   // Returns the field at offset in obj, as a read/write Object* reference.
1871   // Does no checking, and is safe to use during GC, while maps are invalid.
1872   // Does not invoke write barrier, so should only be assigned to
1873   // during marking GC.
1874   static inline Object** RawField(HeapObject* obj, int offset);
1875
1876   // Adds the |code| object related to |name| to the code cache of this map. If
1877   // this map is a dictionary map that is shared, the map copied and installed
1878   // onto the object.
1879   static void UpdateMapCodeCache(Handle<HeapObject> object,
1880                                  Handle<Name> name,
1881                                  Handle<Code> code);
1882
1883   // Casting.
1884   static inline HeapObject* cast(Object* obj);
1885
1886   // Return the write barrier mode for this. Callers of this function
1887   // must be able to present a reference to an DisallowHeapAllocation
1888   // object as a sign that they are not going to use this function
1889   // from code that allocates and thus invalidates the returned write
1890   // barrier mode.
1891   inline WriteBarrierMode GetWriteBarrierMode(
1892       const DisallowHeapAllocation& promise);
1893
1894   // Dispatched behavior.
1895   void HeapObjectShortPrint(StringStream* accumulator);
1896 #ifdef OBJECT_PRINT
1897   void PrintHeader(FILE* out, const char* id);
1898 #endif
1899   DECLARE_PRINTER(HeapObject)
1900   DECLARE_VERIFIER(HeapObject)
1901 #ifdef VERIFY_HEAP
1902   inline void VerifyObjectField(int offset);
1903   inline void VerifySmiField(int offset);
1904
1905   // Verify a pointer is a valid HeapObject pointer that points to object
1906   // areas in the heap.
1907   static void VerifyHeapPointer(Object* p);
1908 #endif
1909
1910   // Layout description.
1911   // First field in a heap object is map.
1912   static const int kMapOffset = Object::kHeaderSize;
1913   static const int kHeaderSize = kMapOffset + kPointerSize;
1914
1915   STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1916
1917  protected:
1918   // helpers for calling an ObjectVisitor to iterate over pointers in the
1919   // half-open range [start, end) specified as integer offsets
1920   inline void IteratePointers(ObjectVisitor* v, int start, int end);
1921   // as above, for the single element at "offset"
1922   inline void IteratePointer(ObjectVisitor* v, int offset);
1923   // as above, for the next code link of a code object.
1924   inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1925
1926  private:
1927   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1928 };
1929
1930
1931 // This class describes a body of an object of a fixed size
1932 // in which all pointer fields are located in the [start_offset, end_offset)
1933 // interval.
1934 template<int start_offset, int end_offset, int size>
1935 class FixedBodyDescriptor {
1936  public:
1937   static const int kStartOffset = start_offset;
1938   static const int kEndOffset = end_offset;
1939   static const int kSize = size;
1940
1941   static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1942
1943   template<typename StaticVisitor>
1944   static inline void IterateBody(HeapObject* obj) {
1945     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1946                                  HeapObject::RawField(obj, end_offset));
1947   }
1948 };
1949
1950
1951 // This class describes a body of an object of a variable size
1952 // in which all pointer fields are located in the [start_offset, object_size)
1953 // interval.
1954 template<int start_offset>
1955 class FlexibleBodyDescriptor {
1956  public:
1957   static const int kStartOffset = start_offset;
1958
1959   static inline void IterateBody(HeapObject* obj,
1960                                  int object_size,
1961                                  ObjectVisitor* v);
1962
1963   template<typename StaticVisitor>
1964   static inline void IterateBody(HeapObject* obj, int object_size) {
1965     StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1966                                  HeapObject::RawField(obj, object_size));
1967   }
1968 };
1969
1970
1971 // The HeapNumber class describes heap allocated numbers that cannot be
1972 // represented in a Smi (small integer)
1973 class HeapNumber: public HeapObject {
1974  public:
1975   // [value]: number value.
1976   inline double value();
1977   inline void set_value(double value);
1978
1979   // Casting.
1980   static inline HeapNumber* cast(Object* obj);
1981
1982   // Dispatched behavior.
1983   bool HeapNumberBooleanValue();
1984
1985   void HeapNumberPrint(FILE* out = stdout);
1986   void HeapNumberPrint(StringStream* accumulator);
1987   DECLARE_VERIFIER(HeapNumber)
1988
1989   inline int get_exponent();
1990   inline int get_sign();
1991
1992   // Layout description.
1993   static const int kValueOffset = HeapObject::kHeaderSize;
1994   // IEEE doubles are two 32 bit words.  The first is just mantissa, the second
1995   // is a mixture of sign, exponent and mantissa.  Our current platforms are all
1996   // little endian apart from non-EABI arm which is little endian with big
1997   // endian floating point word ordering!
1998   static const int kMantissaOffset = kValueOffset;
1999   static const int kExponentOffset = kValueOffset + 4;
2000
2001   static const int kSize = kValueOffset + kDoubleSize;
2002   static const uint32_t kSignMask = 0x80000000u;
2003   static const uint32_t kExponentMask = 0x7ff00000u;
2004   static const uint32_t kMantissaMask = 0xfffffu;
2005   static const int kMantissaBits = 52;
2006   static const int kExponentBits = 11;
2007   static const int kExponentBias = 1023;
2008   static const int kExponentShift = 20;
2009   static const int kInfinityOrNanExponent =
2010       (kExponentMask >> kExponentShift) - kExponentBias;
2011   static const int kMantissaBitsInTopWord = 20;
2012   static const int kNonMantissaBitsInTopWord = 12;
2013
2014  private:
2015   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
2016 };
2017
2018
2019 class Float32x4: public HeapObject {
2020  public:
2021   typedef float32x4_value_t value_t;
2022   static const int kLanes = 4;
2023   static const int kValueSize = kFloat32x4Size;
2024   static const InstanceType kInstanceType = FLOAT32x4_TYPE;
2025   static inline const char* Name();
2026   static inline int kRuntimeAllocatorId();
2027   static inline int kMapRootIndex();
2028
2029   // [value]: float32x4 value.
2030   inline float32x4_value_t value();
2031   inline void set_value(float32x4_value_t value);
2032
2033   // Casting.
2034   static inline Float32x4* cast(Object* obj);
2035
2036   inline void Float32x4Print() {
2037     Float32x4Print(stdout);
2038   }
2039   void Float32x4Print(FILE* out);
2040   void Float32x4Print(StringStream* accumulator);
2041   DECLARE_VERIFIER(Float32x4)
2042
2043   inline float getAt(int index);
2044   inline float x() { return getAt(0); }
2045   inline float y() { return getAt(1); }
2046   inline float z() { return getAt(2); }
2047   inline float w() { return getAt(3); }
2048
2049   // Layout description.
2050   static const int kValueOffset = HeapObject::kHeaderSize;
2051   static const int kSize = kValueOffset + kValueSize;
2052
2053  private:
2054   DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
2055 };
2056
2057
2058 class Int32x4: public HeapObject {
2059  public:
2060   typedef int32x4_value_t value_t;
2061   static const int kValueSize = kInt32x4Size;
2062   static const InstanceType kInstanceType = INT32x4_TYPE;
2063   static inline const char* Name();
2064   static inline int kRuntimeAllocatorId();
2065   static inline int kMapRootIndex();
2066
2067   // [value]: int32x4 value.
2068   inline int32x4_value_t value();
2069   inline void set_value(int32x4_value_t value);
2070
2071   // Casting.
2072   static inline Int32x4* cast(Object* obj);
2073
2074   inline void Int32x4Print() {
2075     Int32x4Print(stdout);
2076   }
2077   void Int32x4Print(FILE* out);
2078   void Int32x4Print(StringStream* accumulator);
2079   DECLARE_VERIFIER(Int32x4)
2080
2081   static const int kLanes = 4;
2082   inline int32_t getAt(int32_t index);
2083   inline int32_t x() { return getAt(0); }
2084   inline int32_t y() { return getAt(1); }
2085   inline int32_t z() { return getAt(2); }
2086   inline int32_t w() { return getAt(3); }
2087
2088   // Layout description.
2089   static const int kValueOffset = HeapObject::kHeaderSize;
2090   static const int kSize = kValueOffset + kValueSize;
2091
2092  private:
2093   DISALLOW_IMPLICIT_CONSTRUCTORS(Int32x4);
2094 };
2095
2096
2097 enum EnsureElementsMode {
2098   DONT_ALLOW_DOUBLE_ELEMENTS,
2099   ALLOW_COPIED_DOUBLE_ELEMENTS,
2100   ALLOW_CONVERTED_DOUBLE_ELEMENTS
2101 };
2102
2103
2104 // Indicates whether a property should be set or (re)defined.  Setting of a
2105 // property causes attributes to remain unchanged, writability to be checked
2106 // and callbacks to be called.  Defining of a property causes attributes to
2107 // be updated and callbacks to be overridden.
2108 enum SetPropertyMode {
2109   SET_PROPERTY,
2110   DEFINE_PROPERTY
2111 };
2112
2113
2114 // Indicator for one component of an AccessorPair.
2115 enum AccessorComponent {
2116   ACCESSOR_GETTER,
2117   ACCESSOR_SETTER
2118 };
2119
2120
2121 // JSReceiver includes types on which properties can be defined, i.e.,
2122 // JSObject and JSProxy.
2123 class JSReceiver: public HeapObject {
2124  public:
2125   enum DeleteMode {
2126     NORMAL_DELETION,
2127     STRICT_DELETION,
2128     FORCE_DELETION
2129   };
2130
2131   // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
2132   // a keyed store is of the form a[expression] = foo.
2133   enum StoreFromKeyed {
2134     MAY_BE_STORE_FROM_KEYED,
2135     CERTAINLY_NOT_STORE_FROM_KEYED
2136   };
2137
2138   // Internal properties (e.g. the hidden properties dictionary) might
2139   // be added even though the receiver is non-extensible.
2140   enum ExtensibilityCheck {
2141     PERFORM_EXTENSIBILITY_CHECK,
2142     OMIT_EXTENSIBILITY_CHECK
2143   };
2144
2145   // Casting.
2146   static inline JSReceiver* cast(Object* obj);
2147
2148   // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
2149   static Handle<Object> SetProperty(Handle<JSReceiver> object,
2150                                     Handle<Name> key,
2151                                     Handle<Object> value,
2152                                     PropertyAttributes attributes,
2153                                     StrictMode strict_mode,
2154                                     StoreFromKeyed store_mode =
2155                                         MAY_BE_STORE_FROM_KEYED);
2156   static Handle<Object> SetElement(Handle<JSReceiver> object,
2157                                    uint32_t index,
2158                                    Handle<Object> value,
2159                                    PropertyAttributes attributes,
2160                                    StrictMode strict_mode);
2161
2162   // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
2163   static inline bool HasProperty(Handle<JSReceiver> object, Handle<Name> name);
2164   static inline bool HasLocalProperty(Handle<JSReceiver>, Handle<Name> name);
2165   static inline bool HasElement(Handle<JSReceiver> object, uint32_t index);
2166   static inline bool HasLocalElement(Handle<JSReceiver> object, uint32_t index);
2167
2168   // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
2169   static Handle<Object> DeleteProperty(Handle<JSReceiver> object,
2170                                        Handle<Name> name,
2171                                        DeleteMode mode = NORMAL_DELETION);
2172   static Handle<Object> DeleteElement(Handle<JSReceiver> object,
2173                                       uint32_t index,
2174                                       DeleteMode mode = NORMAL_DELETION);
2175
2176   // Tests for the fast common case for property enumeration.
2177   bool IsSimpleEnum();
2178
2179   // Returns the class name ([[Class]] property in the specification).
2180   String* class_name();
2181
2182   // Returns the constructor name (the name (possibly, inferred name) of the
2183   // function that was used to instantiate the object).
2184   String* constructor_name();
2185
2186   static inline PropertyAttributes GetPropertyAttribute(
2187       Handle<JSReceiver> object,
2188       Handle<Name> name);
2189   static PropertyAttributes GetPropertyAttributeWithReceiver(
2190       Handle<JSReceiver> object,
2191       Handle<JSReceiver> receiver,
2192       Handle<Name> name);
2193   static PropertyAttributes GetLocalPropertyAttribute(
2194       Handle<JSReceiver> object,
2195       Handle<Name> name);
2196
2197   static inline PropertyAttributes GetElementAttribute(
2198       Handle<JSReceiver> object,
2199       uint32_t index);
2200   static inline PropertyAttributes GetLocalElementAttribute(
2201       Handle<JSReceiver> object,
2202       uint32_t index);
2203
2204   // Return the object's prototype (might be Heap::null_value()).
2205   inline Object* GetPrototype();
2206
2207   // Return the constructor function (may be Heap::null_value()).
2208   inline Object* GetConstructor();
2209
2210   // Retrieves a permanent object identity hash code. The undefined value might
2211   // be returned in case no hash was created yet.
2212   inline Object* GetIdentityHash();
2213
2214   // Retrieves a permanent object identity hash code. May create and store a
2215   // hash code if needed and none exists.
2216   inline static Handle<Object> GetOrCreateIdentityHash(
2217       Handle<JSReceiver> object);
2218
2219   // Lookup a property.  If found, the result is valid and has
2220   // detailed information.
2221   void LocalLookup(Name* name, LookupResult* result,
2222                    bool search_hidden_prototypes = false);
2223   void Lookup(Name* name, LookupResult* result);
2224
2225  protected:
2226   Smi* GenerateIdentityHash();
2227
2228   static Handle<Object> SetPropertyWithDefinedSetter(Handle<JSReceiver> object,
2229                                                      Handle<JSReceiver> setter,
2230                                                      Handle<Object> value);
2231
2232  private:
2233   static PropertyAttributes GetPropertyAttributeForResult(
2234       Handle<JSReceiver> object,
2235       Handle<JSReceiver> receiver,
2236       LookupResult* result,
2237       Handle<Name> name,
2238       bool continue_search);
2239
2240   static Handle<Object> SetProperty(Handle<JSReceiver> receiver,
2241                                     LookupResult* result,
2242                                     Handle<Name> key,
2243                                     Handle<Object> value,
2244                                     PropertyAttributes attributes,
2245                                     StrictMode strict_mode,
2246                                     StoreFromKeyed store_from_keyed);
2247
2248   DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
2249 };
2250
2251 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
2252 class ObjectHashTable;
2253
2254 // The JSObject describes real heap allocated JavaScript objects with
2255 // properties.
2256 // Note that the map of JSObject changes during execution to enable inline
2257 // caching.
2258 class JSObject: public JSReceiver {
2259  public:
2260   // [properties]: Backing storage for properties.
2261   // properties is a FixedArray in the fast case and a Dictionary in the
2262   // slow case.
2263   DECL_ACCESSORS(properties, FixedArray)  // Get and set fast properties.
2264   inline void initialize_properties();
2265   inline bool HasFastProperties();
2266   inline NameDictionary* property_dictionary();  // Gets slow properties.
2267
2268   // [elements]: The elements (properties with names that are integers).
2269   //
2270   // Elements can be in two general modes: fast and slow. Each mode
2271   // corrensponds to a set of object representations of elements that
2272   // have something in common.
2273   //
2274   // In the fast mode elements is a FixedArray and so each element can
2275   // be quickly accessed. This fact is used in the generated code. The
2276   // elements array can have one of three maps in this mode:
2277   // fixed_array_map, sloppy_arguments_elements_map or
2278   // fixed_cow_array_map (for copy-on-write arrays). In the latter case
2279   // the elements array may be shared by a few objects and so before
2280   // writing to any element the array must be copied. Use
2281   // EnsureWritableFastElements in this case.
2282   //
2283   // In the slow mode the elements is either a NumberDictionary, an
2284   // ExternalArray, or a FixedArray parameter map for a (sloppy)
2285   // arguments object.
2286   DECL_ACCESSORS(elements, FixedArrayBase)
2287   inline void initialize_elements();
2288   MUST_USE_RESULT inline MaybeObject* ResetElements();
2289   inline ElementsKind GetElementsKind();
2290   inline ElementsAccessor* GetElementsAccessor();
2291   // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
2292   inline bool HasFastSmiElements();
2293   // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
2294   inline bool HasFastObjectElements();
2295   // Returns true if an object has elements of FAST_ELEMENTS or
2296   // FAST_SMI_ONLY_ELEMENTS.
2297   inline bool HasFastSmiOrObjectElements();
2298   // Returns true if an object has any of the fast elements kinds.
2299   inline bool HasFastElements();
2300   // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
2301   // ElementsKind.
2302   inline bool HasFastDoubleElements();
2303   // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
2304   // ElementsKind.
2305   inline bool HasFastHoleyElements();
2306   inline bool HasSloppyArgumentsElements();
2307   inline bool HasDictionaryElements();
2308
2309   inline bool HasExternalUint8ClampedElements();
2310   inline bool HasExternalArrayElements();
2311   inline bool HasExternalInt8Elements();
2312   inline bool HasExternalUint8Elements();
2313   inline bool HasExternalInt16Elements();
2314   inline bool HasExternalUint16Elements();
2315   inline bool HasExternalInt32Elements();
2316   inline bool HasExternalUint32Elements();
2317   inline bool HasExternalFloat32Elements();
2318   inline bool HasExternalFloat32x4Elements();
2319   inline bool HasExternalInt32x4Elements();
2320   inline bool HasExternalFloat64Elements();
2321
2322   inline bool HasFixedTypedArrayElements();
2323
2324   inline bool HasFixedUint8ClampedElements();
2325   inline bool HasFixedArrayElements();
2326   inline bool HasFixedInt8Elements();
2327   inline bool HasFixedUint8Elements();
2328   inline bool HasFixedInt16Elements();
2329   inline bool HasFixedUint16Elements();
2330   inline bool HasFixedInt32Elements();
2331   inline bool HasFixedUint32Elements();
2332   inline bool HasFixedFloat32Elements();
2333   inline bool HasFixedFloat64Elements();
2334   inline bool HasFixedFloat32x4Elements();
2335   inline bool HasFixedInt32x4Elements();
2336
2337   bool HasFastArgumentsElements();
2338   bool HasDictionaryArgumentsElements();
2339   inline SeededNumberDictionary* element_dictionary();  // Gets slow elements.
2340
2341   inline void set_map_and_elements(
2342       Map* map,
2343       FixedArrayBase* value,
2344       WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
2345
2346   // Requires: HasFastElements().
2347   static Handle<FixedArray> EnsureWritableFastElements(
2348       Handle<JSObject> object);
2349   MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
2350
2351   // Collects elements starting at index 0.
2352   // Undefined values are placed after non-undefined values.
2353   // Returns the number of non-undefined values.
2354   static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
2355                                                uint32_t limit);
2356   // As PrepareElementsForSort, but only on objects where elements is
2357   // a dictionary, and it will stay a dictionary.
2358   static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
2359                                                    uint32_t limit);
2360   MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
2361
2362   static Handle<Object> GetPropertyWithCallback(Handle<JSObject> object,
2363                                                 Handle<Object> receiver,
2364                                                 Handle<Object> structure,
2365                                                 Handle<Name> name);
2366
2367   static Handle<Object> SetPropertyWithCallback(
2368       Handle<JSObject> object,
2369       Handle<Object> structure,
2370       Handle<Name> name,
2371       Handle<Object> value,
2372       Handle<JSObject> holder,
2373       StrictMode strict_mode);
2374
2375   static Handle<Object> SetPropertyWithInterceptor(
2376       Handle<JSObject> object,
2377       Handle<Name> name,
2378       Handle<Object> value,
2379       PropertyAttributes attributes,
2380       StrictMode strict_mode);
2381
2382   static Handle<Object> SetPropertyForResult(
2383       Handle<JSObject> object,
2384       LookupResult* result,
2385       Handle<Name> name,
2386       Handle<Object> value,
2387       PropertyAttributes attributes,
2388       StrictMode strict_mode,
2389       StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2390
2391   static Handle<Object> SetLocalPropertyIgnoreAttributes(
2392       Handle<JSObject> object,
2393       Handle<Name> key,
2394       Handle<Object> value,
2395       PropertyAttributes attributes,
2396       ValueType value_type = OPTIMAL_REPRESENTATION,
2397       StoreMode mode = ALLOW_AS_CONSTANT,
2398       ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK);
2399
2400   static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
2401   static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
2402
2403   // Try to follow an existing transition to a field with attributes NONE. The
2404   // return value indicates whether the transition was successful.
2405   static inline Handle<Map> FindTransitionToField(Handle<Map> map,
2406                                                   Handle<Name> key);
2407
2408   // Extend the receiver with a single fast property appeared first in the
2409   // passed map. This also extends the property backing store if necessary.
2410   static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
2411
2412   // Migrates the given object to a map whose field representations are the
2413   // lowest upper bound of all known representations for that field.
2414   static void MigrateInstance(Handle<JSObject> instance);
2415
2416   // Migrates the given object only if the target map is already available,
2417   // or returns an empty handle if such a map is not yet available.
2418   static Handle<Object> TryMigrateInstance(Handle<JSObject> instance);
2419
2420   // Retrieve a value in a normalized object given a lookup result.
2421   // Handles the special representation of JS global objects.
2422   Object* GetNormalizedProperty(const LookupResult* result);
2423
2424   // Sets the property value in a normalized object given a lookup result.
2425   // Handles the special representation of JS global objects.
2426   static void SetNormalizedProperty(Handle<JSObject> object,
2427                                     const LookupResult* result,
2428                                     Handle<Object> value);
2429
2430   // Sets the property value in a normalized object given (key, value, details).
2431   // Handles the special representation of JS global objects.
2432   static void SetNormalizedProperty(Handle<JSObject> object,
2433                                     Handle<Name> key,
2434                                     Handle<Object> value,
2435                                     PropertyDetails details);
2436
2437   static void OptimizeAsPrototype(Handle<JSObject> object);
2438
2439   // Retrieve interceptors.
2440   InterceptorInfo* GetNamedInterceptor();
2441   InterceptorInfo* GetIndexedInterceptor();
2442
2443   // Used from JSReceiver.
2444   static PropertyAttributes GetPropertyAttributePostInterceptor(
2445       Handle<JSObject> object,
2446       Handle<JSObject> receiver,
2447       Handle<Name> name,
2448       bool continue_search);
2449   static PropertyAttributes GetPropertyAttributeWithInterceptor(
2450       Handle<JSObject> object,
2451       Handle<JSObject> receiver,
2452       Handle<Name> name,
2453       bool continue_search);
2454   static PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
2455       Handle<JSObject> object,
2456       LookupResult* result,
2457       Handle<Name> name,
2458       bool continue_search);
2459   static PropertyAttributes GetElementAttributeWithReceiver(
2460       Handle<JSObject> object,
2461       Handle<JSReceiver> receiver,
2462       uint32_t index,
2463       bool continue_search);
2464
2465   // Retrieves an AccessorPair property from the given object. Might return
2466   // undefined if the property doesn't exist or is of a different kind.
2467   static Handle<Object> GetAccessor(Handle<JSObject> object,
2468                                     Handle<Name> name,
2469                                     AccessorComponent component);
2470
2471   // Defines an AccessorPair property on the given object.
2472   // TODO(mstarzinger): Rename to SetAccessor() and return empty handle on
2473   // exception instead of letting callers check for scheduled exception.
2474   static void DefineAccessor(Handle<JSObject> object,
2475                              Handle<Name> name,
2476                              Handle<Object> getter,
2477                              Handle<Object> setter,
2478                              PropertyAttributes attributes,
2479                              v8::AccessControl access_control = v8::DEFAULT);
2480
2481   // Defines an AccessorInfo property on the given object.
2482   static Handle<Object> SetAccessor(Handle<JSObject> object,
2483                                     Handle<AccessorInfo> info);
2484
2485   static Handle<Object> GetPropertyWithInterceptor(
2486       Handle<JSObject> object,
2487       Handle<Object> receiver,
2488       Handle<Name> name,
2489       PropertyAttributes* attributes);
2490   static Handle<Object> GetPropertyPostInterceptor(
2491       Handle<JSObject> object,
2492       Handle<Object> receiver,
2493       Handle<Name> name,
2494       PropertyAttributes* attributes);
2495   MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
2496       Object* receiver,
2497       Name* name,
2498       PropertyAttributes* attributes);
2499
2500   // Returns true if this is an instance of an api function and has
2501   // been modified since it was created.  May give false positives.
2502   bool IsDirty();
2503
2504   // Accessors for hidden properties object.
2505   //
2506   // Hidden properties are not local properties of the object itself.
2507   // Instead they are stored in an auxiliary structure kept as a local
2508   // property with a special name Heap::hidden_string(). But if the
2509   // receiver is a JSGlobalProxy then the auxiliary object is a property
2510   // of its prototype, and if it's a detached proxy, then you can't have
2511   // hidden properties.
2512
2513   // Sets a hidden property on this object. Returns this object if successful,
2514   // undefined if called on a detached proxy.
2515   static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2516                                           Handle<Name> key,
2517                                           Handle<Object> value);
2518   // Gets the value of a hidden property with the given key. Returns the hole
2519   // if the property doesn't exist (or if called on a detached proxy),
2520   // otherwise returns the value set for the key.
2521   Object* GetHiddenProperty(Name* key);
2522   // Deletes a hidden property. Deleting a non-existing property is
2523   // considered successful.
2524   static void DeleteHiddenProperty(Handle<JSObject> object,
2525                                    Handle<Name> key);
2526   // Returns true if the object has a property with the hidden string as name.
2527   static bool HasHiddenProperties(Handle<JSObject> object);
2528
2529   static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2530
2531   inline void ValidateElements();
2532
2533   // Makes sure that this object can contain HeapObject as elements.
2534   static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2535
2536   // Makes sure that this object can contain the specified elements.
2537   static inline void EnsureCanContainElements(
2538       Handle<JSObject> object,
2539       Object** elements,
2540       uint32_t count,
2541       EnsureElementsMode mode);
2542   static inline void EnsureCanContainElements(
2543       Handle<JSObject> object,
2544       Handle<FixedArrayBase> elements,
2545       uint32_t length,
2546       EnsureElementsMode mode);
2547   static void EnsureCanContainElements(
2548       Handle<JSObject> object,
2549       Arguments* arguments,
2550       uint32_t first_arg,
2551       uint32_t arg_count,
2552       EnsureElementsMode mode);
2553
2554   // Would we convert a fast elements array to dictionary mode given
2555   // an access at key?
2556   bool WouldConvertToSlowElements(Handle<Object> key);
2557   // Do we want to keep the elements in fast case when increasing the
2558   // capacity?
2559   bool ShouldConvertToSlowElements(int new_capacity);
2560   // Returns true if the backing storage for the slow-case elements of
2561   // this object takes up nearly as much space as a fast-case backing
2562   // storage would.  In that case the JSObject should have fast
2563   // elements.
2564   bool ShouldConvertToFastElements();
2565   // Returns true if the elements of JSObject contains only values that can be
2566   // represented in a FixedDoubleArray and has at least one value that can only
2567   // be represented as a double and not a Smi.
2568   bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
2569
2570   // Computes the new capacity when expanding the elements of a JSObject.
2571   static int NewElementsCapacity(int old_capacity) {
2572     // (old_capacity + 50%) + 16
2573     return old_capacity + (old_capacity >> 1) + 16;
2574   }
2575
2576   // These methods do not perform access checks!
2577   AccessorPair* GetLocalPropertyAccessorPair(Name* name);
2578   AccessorPair* GetLocalElementAccessorPair(uint32_t index);
2579
2580   static Handle<Object> SetFastElement(Handle<JSObject> object, uint32_t index,
2581                                        Handle<Object> value,
2582                                        StrictMode strict_mode,
2583                                        bool check_prototype);
2584
2585   static Handle<Object> SetOwnElement(Handle<JSObject> object,
2586                                       uint32_t index,
2587                                       Handle<Object> value,
2588                                       StrictMode strict_mode);
2589
2590   // Empty handle is returned if the element cannot be set to the given value.
2591   static Handle<Object> SetElement(
2592       Handle<JSObject> object,
2593       uint32_t index,
2594       Handle<Object> value,
2595       PropertyAttributes attributes,
2596       StrictMode strict_mode,
2597       bool check_prototype = true,
2598       SetPropertyMode set_mode = SET_PROPERTY);
2599
2600   // Returns the index'th element.
2601   // The undefined object if index is out of bounds.
2602   static Handle<Object> GetElementWithInterceptor(Handle<JSObject> object,
2603                                                   Handle<Object> receiver,
2604                                                   uint32_t index);
2605
2606   enum SetFastElementsCapacitySmiMode {
2607     kAllowSmiElements,
2608     kForceSmiElements,
2609     kDontAllowSmiElements
2610   };
2611
2612   // Replace the elements' backing store with fast elements of the given
2613   // capacity.  Update the length for JSArrays.  Returns the new backing
2614   // store.
2615   static Handle<FixedArray> SetFastElementsCapacityAndLength(
2616       Handle<JSObject> object,
2617       int capacity,
2618       int length,
2619       SetFastElementsCapacitySmiMode smi_mode);
2620   static void SetFastDoubleElementsCapacityAndLength(
2621       Handle<JSObject> object,
2622       int capacity,
2623       int length);
2624   MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
2625       int capacity,
2626       int length);
2627
2628   // Lookup interceptors are used for handling properties controlled by host
2629   // objects.
2630   inline bool HasNamedInterceptor();
2631   inline bool HasIndexedInterceptor();
2632
2633   // Support functions for v8 api (needed for correct interceptor behavior).
2634   static bool HasRealNamedProperty(Handle<JSObject> object,
2635                                    Handle<Name> key);
2636   static bool HasRealElementProperty(Handle<JSObject> object, uint32_t index);
2637   static bool HasRealNamedCallbackProperty(Handle<JSObject> object,
2638                                            Handle<Name> key);
2639
2640   // Get the header size for a JSObject.  Used to compute the index of
2641   // internal fields as well as the number of internal fields.
2642   inline int GetHeaderSize();
2643
2644   inline int GetInternalFieldCount();
2645   inline int GetInternalFieldOffset(int index);
2646   inline Object* GetInternalField(int index);
2647   inline void SetInternalField(int index, Object* value);
2648   inline void SetInternalField(int index, Smi* value);
2649
2650   // The following lookup functions skip interceptors.
2651   void LocalLookupRealNamedProperty(Name* name, LookupResult* result);
2652   void LookupRealNamedProperty(Name* name, LookupResult* result);
2653   void LookupRealNamedPropertyInPrototypes(Name* name, LookupResult* result);
2654   void LookupCallbackProperty(Name* name, LookupResult* result);
2655
2656   // Returns the number of properties on this object filtering out properties
2657   // with the specified attributes (ignoring interceptors).
2658   int NumberOfLocalProperties(PropertyAttributes filter = NONE);
2659   // Fill in details for properties into storage starting at the specified
2660   // index.
2661   void GetLocalPropertyNames(
2662       FixedArray* storage, int index, PropertyAttributes filter = NONE);
2663
2664   // Returns the number of properties on this object filtering out properties
2665   // with the specified attributes (ignoring interceptors).
2666   int NumberOfLocalElements(PropertyAttributes filter);
2667   // Returns the number of enumerable elements (ignoring interceptors).
2668   int NumberOfEnumElements();
2669   // Returns the number of elements on this object filtering out elements
2670   // with the specified attributes (ignoring interceptors).
2671   int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
2672   // Count and fill in the enumerable elements into storage.
2673   // (storage->length() == NumberOfEnumElements()).
2674   // If storage is NULL, will count the elements without adding
2675   // them to any storage.
2676   // Returns the number of enumerable elements.
2677   int GetEnumElementKeys(FixedArray* storage);
2678
2679   // Returns a new map with all transitions dropped from the object's current
2680   // map and the ElementsKind set.
2681   static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2682                                               ElementsKind to_kind);
2683   inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
2684       Isolate* isolate,
2685       ElementsKind elements_kind);
2686   MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
2687       ElementsKind elements_kind);
2688
2689   static void TransitionElementsKind(Handle<JSObject> object,
2690                                      ElementsKind to_kind);
2691
2692   // TODO(mstarzinger): Both public because of ConvertAnsSetLocalProperty().
2693   static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2694   static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2695                                             int modify_index,
2696                                             Representation new_representation,
2697                                             StoreMode store_mode);
2698
2699   // Convert the object to use the canonical dictionary
2700   // representation. If the object is expected to have additional properties
2701   // added this number can be indicated to have the backing store allocated to
2702   // an initial capacity for holding these properties.
2703   static void NormalizeProperties(Handle<JSObject> object,
2704                                   PropertyNormalizationMode mode,
2705                                   int expected_additional_properties);
2706
2707   // Convert and update the elements backing store to be a
2708   // SeededNumberDictionary dictionary.  Returns the backing after conversion.
2709   static Handle<SeededNumberDictionary> NormalizeElements(
2710       Handle<JSObject> object);
2711
2712   // Transform slow named properties to fast variants.
2713   static void TransformToFastProperties(Handle<JSObject> object,
2714                                         int unused_property_fields);
2715
2716   // Access fast-case object properties at index.
2717   MUST_USE_RESULT inline MaybeObject* FastPropertyAt(
2718       Representation representation,
2719       int index);
2720   inline Object* RawFastPropertyAt(int index);
2721   inline void FastPropertyAtPut(int index, Object* value);
2722
2723   // Access to in object properties.
2724   inline int GetInObjectPropertyOffset(int index);
2725   inline Object* InObjectPropertyAt(int index);
2726   inline Object* InObjectPropertyAtPut(int index,
2727                                        Object* value,
2728                                        WriteBarrierMode mode
2729                                        = UPDATE_WRITE_BARRIER);
2730
2731   // Set the object's prototype (only JSReceiver and null are allowed values).
2732   static Handle<Object> SetPrototype(Handle<JSObject> object,
2733                                      Handle<Object> value,
2734                                      bool skip_hidden_prototypes = false);
2735
2736   // Initializes the body after properties slot, properties slot is
2737   // initialized by set_properties.  Fill the pre-allocated fields with
2738   // pre_allocated_value and the rest with filler_value.
2739   // Note: this call does not update write barrier, the caller is responsible
2740   // to ensure that |filler_value| can be collected without WB here.
2741   inline void InitializeBody(Map* map,
2742                              Object* pre_allocated_value,
2743                              Object* filler_value);
2744
2745   // Check whether this object references another object
2746   bool ReferencesObject(Object* obj);
2747
2748   // Disalow further properties to be added to the object.
2749   static Handle<Object> PreventExtensions(Handle<JSObject> object);
2750
2751   // ES5 Object.freeze
2752   static Handle<Object> Freeze(Handle<JSObject> object);
2753
2754   // Called the first time an object is observed with ES7 Object.observe.
2755   static void SetObserved(Handle<JSObject> object);
2756
2757   // Copy object.
2758   enum DeepCopyHints {
2759     kNoHints = 0,
2760     kObjectIsShallowArray = 1
2761   };
2762
2763   static Handle<JSObject> Copy(Handle<JSObject> object);
2764   static Handle<JSObject> DeepCopy(Handle<JSObject> object,
2765                                    AllocationSiteUsageContext* site_context,
2766                                    DeepCopyHints hints = kNoHints);
2767   static Handle<JSObject> DeepWalk(Handle<JSObject> object,
2768                                    AllocationSiteCreationContext* site_context);
2769
2770   // Casting.
2771   static inline JSObject* cast(Object* obj);
2772
2773   // Dispatched behavior.
2774   void JSObjectShortPrint(StringStream* accumulator);
2775   DECLARE_PRINTER(JSObject)
2776   DECLARE_VERIFIER(JSObject)
2777 #ifdef OBJECT_PRINT
2778   void PrintProperties(FILE* out = stdout);
2779   void PrintElements(FILE* out = stdout);
2780   void PrintTransitions(FILE* out = stdout);
2781 #endif
2782
2783   static void PrintElementsTransition(
2784       FILE* file, Handle<JSObject> object,
2785       ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2786       ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2787
2788   void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2789
2790 #ifdef DEBUG
2791   // Structure for collecting spill information about JSObjects.
2792   class SpillInformation {
2793    public:
2794     void Clear();
2795     void Print();
2796     int number_of_objects_;
2797     int number_of_objects_with_fast_properties_;
2798     int number_of_objects_with_fast_elements_;
2799     int number_of_fast_used_fields_;
2800     int number_of_fast_unused_fields_;
2801     int number_of_slow_used_properties_;
2802     int number_of_slow_unused_properties_;
2803     int number_of_fast_used_elements_;
2804     int number_of_fast_unused_elements_;
2805     int number_of_slow_used_elements_;
2806     int number_of_slow_unused_elements_;
2807   };
2808
2809   void IncrementSpillStatistics(SpillInformation* info);
2810 #endif
2811
2812 #ifdef VERIFY_HEAP
2813   // If a GC was caused while constructing this object, the elements pointer
2814   // may point to a one pointer filler map. The object won't be rooted, but
2815   // our heap verification code could stumble across it.
2816   bool ElementsAreSafeToExamine();
2817 #endif
2818
2819   Object* SlowReverseLookup(Object* value);
2820
2821   // Maximal number of fast properties for the JSObject. Used to
2822   // restrict the number of map transitions to avoid an explosion in
2823   // the number of maps for objects used as dictionaries.
2824   inline bool TooManyFastProperties(
2825       StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
2826
2827   // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2828   // Also maximal value of JSArray's length property.
2829   static const uint32_t kMaxElementCount = 0xffffffffu;
2830
2831   // Constants for heuristics controlling conversion of fast elements
2832   // to slow elements.
2833
2834   // Maximal gap that can be introduced by adding an element beyond
2835   // the current elements length.
2836   static const uint32_t kMaxGap = 1024;
2837
2838   // Maximal length of fast elements array that won't be checked for
2839   // being dense enough on expansion.
2840   static const int kMaxUncheckedFastElementsLength = 5000;
2841
2842   // Same as above but for old arrays. This limit is more strict. We
2843   // don't want to be wasteful with long lived objects.
2844   static const int kMaxUncheckedOldFastElementsLength = 500;
2845
2846   // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2847   // permissible values (see the ASSERT in heap.cc).
2848   static const int kInitialMaxFastElementArray = 100000;
2849
2850   static const int kFastPropertiesSoftLimit = 12;
2851   static const int kMaxFastProperties = 64;
2852   static const int kMaxInstanceSize = 255 * kPointerSize;
2853   // When extending the backing storage for property values, we increase
2854   // its size by more than the 1 entry necessary, so sequentially adding fields
2855   // to the same object requires fewer allocations and copies.
2856   static const int kFieldsAdded = 3;
2857
2858   // Layout description.
2859   static const int kPropertiesOffset = HeapObject::kHeaderSize;
2860   static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2861   static const int kHeaderSize = kElementsOffset + kPointerSize;
2862
2863   STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2864
2865   class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2866    public:
2867     static inline int SizeOf(Map* map, HeapObject* object);
2868   };
2869
2870   // Enqueue change record for Object.observe. May cause GC.
2871   static void EnqueueChangeRecord(Handle<JSObject> object,
2872                                   const char* type,
2873                                   Handle<Name> name,
2874                                   Handle<Object> old_value);
2875
2876  private:
2877   friend class DictionaryElementsAccessor;
2878   friend class JSReceiver;
2879   friend class Object;
2880
2881   static void UpdateAllocationSite(Handle<JSObject> object,
2882                                    ElementsKind to_kind);
2883
2884   // Used from Object::GetProperty().
2885   static Handle<Object> GetPropertyWithFailedAccessCheck(
2886       Handle<JSObject> object,
2887       Handle<Object> receiver,
2888       LookupResult* result,
2889       Handle<Name> name,
2890       PropertyAttributes* attributes);
2891
2892   MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2893                                                       Object* structure,
2894                                                       uint32_t index,
2895                                                       Object* holder);
2896   static PropertyAttributes GetElementAttributeWithInterceptor(
2897       Handle<JSObject> object,
2898       Handle<JSReceiver> receiver,
2899       uint32_t index,
2900       bool continue_search);
2901   static PropertyAttributes GetElementAttributeWithoutInterceptor(
2902       Handle<JSObject> object,
2903       Handle<JSReceiver> receiver,
2904       uint32_t index,
2905       bool continue_search);
2906   static Handle<Object> SetElementWithCallback(
2907       Handle<JSObject> object,
2908       Handle<Object> structure,
2909       uint32_t index,
2910       Handle<Object> value,
2911       Handle<JSObject> holder,
2912       StrictMode strict_mode);
2913   static Handle<Object> SetElementWithInterceptor(
2914       Handle<JSObject> object,
2915       uint32_t index,
2916       Handle<Object> value,
2917       PropertyAttributes attributes,
2918       StrictMode strict_mode,
2919       bool check_prototype,
2920       SetPropertyMode set_mode);
2921   static Handle<Object> SetElementWithoutInterceptor(
2922       Handle<JSObject> object,
2923       uint32_t index,
2924       Handle<Object> value,
2925       PropertyAttributes attributes,
2926       StrictMode strict_mode,
2927       bool check_prototype,
2928       SetPropertyMode set_mode);
2929   static Handle<Object> SetElementWithCallbackSetterInPrototypes(
2930       Handle<JSObject> object,
2931       uint32_t index,
2932       Handle<Object> value,
2933       bool* found,
2934       StrictMode strict_mode);
2935   static Handle<Object> SetDictionaryElement(
2936       Handle<JSObject> object,
2937       uint32_t index,
2938       Handle<Object> value,
2939       PropertyAttributes attributes,
2940       StrictMode strict_mode,
2941       bool check_prototype,
2942       SetPropertyMode set_mode = SET_PROPERTY);
2943   static Handle<Object> SetFastDoubleElement(
2944       Handle<JSObject> object,
2945       uint32_t index,
2946       Handle<Object> value,
2947       StrictMode strict_mode,
2948       bool check_prototype = true);
2949
2950   // Searches the prototype chain for property 'name'. If it is found and
2951   // has a setter, invoke it and set '*done' to true. If it is found and is
2952   // read-only, reject and set '*done' to true. Otherwise, set '*done' to
2953   // false. Can throw and return an empty handle with '*done==true'.
2954   static Handle<Object> SetPropertyViaPrototypes(
2955       Handle<JSObject> object,
2956       Handle<Name> name,
2957       Handle<Object> value,
2958       PropertyAttributes attributes,
2959       StrictMode strict_mode,
2960       bool* done);
2961   static Handle<Object> SetPropertyPostInterceptor(
2962       Handle<JSObject> object,
2963       Handle<Name> name,
2964       Handle<Object> value,
2965       PropertyAttributes attributes,
2966       StrictMode strict_mode);
2967   static Handle<Object> SetPropertyUsingTransition(
2968       Handle<JSObject> object,
2969       LookupResult* lookup,
2970       Handle<Name> name,
2971       Handle<Object> value,
2972       PropertyAttributes attributes);
2973   static Handle<Object> SetPropertyWithFailedAccessCheck(
2974       Handle<JSObject> object,
2975       LookupResult* result,
2976       Handle<Name> name,
2977       Handle<Object> value,
2978       bool check_prototype,
2979       StrictMode strict_mode);
2980
2981   // Add a property to an object.
2982   static Handle<Object> AddProperty(
2983       Handle<JSObject> object,
2984       Handle<Name> name,
2985       Handle<Object> value,
2986       PropertyAttributes attributes,
2987       StrictMode strict_mode,
2988       StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED,
2989       ExtensibilityCheck extensibility_check = PERFORM_EXTENSIBILITY_CHECK,
2990       ValueType value_type = OPTIMAL_REPRESENTATION,
2991       StoreMode mode = ALLOW_AS_CONSTANT,
2992       TransitionFlag flag = INSERT_TRANSITION);
2993
2994   // Add a constant function property to a fast-case object.
2995   // This leaves a CONSTANT_TRANSITION in the old map, and
2996   // if it is called on a second object with this map, a
2997   // normal property is added instead, with a map transition.
2998   // This avoids the creation of many maps with the same constant
2999   // function, all orphaned.
3000   static void AddConstantProperty(Handle<JSObject> object,
3001                                   Handle<Name> name,
3002                                   Handle<Object> constant,
3003                                   PropertyAttributes attributes,
3004                                   TransitionFlag flag);
3005
3006   // Add a property to a fast-case object.
3007   static void AddFastProperty(Handle<JSObject> object,
3008                               Handle<Name> name,
3009                               Handle<Object> value,
3010                               PropertyAttributes attributes,
3011                               StoreFromKeyed store_mode,
3012                               ValueType value_type,
3013                               TransitionFlag flag);
3014
3015   // Add a property to a slow-case object.
3016   static void AddSlowProperty(Handle<JSObject> object,
3017                               Handle<Name> name,
3018                               Handle<Object> value,
3019                               PropertyAttributes attributes);
3020
3021   static Handle<Object> DeleteProperty(Handle<JSObject> object,
3022                                        Handle<Name> name,
3023                                        DeleteMode mode);
3024   static Handle<Object> DeletePropertyPostInterceptor(Handle<JSObject> object,
3025                                                       Handle<Name> name,
3026                                                       DeleteMode mode);
3027   static Handle<Object> DeletePropertyWithInterceptor(Handle<JSObject> object,
3028                                                       Handle<Name> name);
3029
3030   // Deletes the named property in a normalized object.
3031   static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
3032                                                  Handle<Name> name,
3033                                                  DeleteMode mode);
3034
3035   static Handle<Object> DeleteElement(Handle<JSObject> object,
3036                                       uint32_t index,
3037                                       DeleteMode mode);
3038   static Handle<Object> DeleteElementWithInterceptor(Handle<JSObject> object,
3039                                                      uint32_t index);
3040
3041   bool ReferencesObjectFromElements(FixedArray* elements,
3042                                     ElementsKind kind,
3043                                     Object* object);
3044
3045   // Returns true if most of the elements backing storage is used.
3046   bool HasDenseElements();
3047
3048   // Gets the current elements capacity and the number of used elements.
3049   void GetElementsCapacityAndUsage(int* capacity, int* used);
3050
3051   static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
3052   static void SetElementCallback(Handle<JSObject> object,
3053                                  uint32_t index,
3054                                  Handle<Object> structure,
3055                                  PropertyAttributes attributes);
3056   static void SetPropertyCallback(Handle<JSObject> object,
3057                                   Handle<Name> name,
3058                                   Handle<Object> structure,
3059                                   PropertyAttributes attributes);
3060   static void DefineElementAccessor(Handle<JSObject> object,
3061                                     uint32_t index,
3062                                     Handle<Object> getter,
3063                                     Handle<Object> setter,
3064                                     PropertyAttributes attributes,
3065                                     v8::AccessControl access_control);
3066   static Handle<AccessorPair> CreateAccessorPairFor(Handle<JSObject> object,
3067                                                     Handle<Name> name);
3068   static void DefinePropertyAccessor(Handle<JSObject> object,
3069                                      Handle<Name> name,
3070                                      Handle<Object> getter,
3071                                      Handle<Object> setter,
3072                                      PropertyAttributes attributes,
3073                                      v8::AccessControl access_control);
3074
3075   // Try to define a single accessor paying attention to map transitions.
3076   // Returns false if this was not possible and we have to use the slow case.
3077   static bool DefineFastAccessor(Handle<JSObject> object,
3078                                  Handle<Name> name,
3079                                  AccessorComponent component,
3080                                  Handle<Object> accessor,
3081                                  PropertyAttributes attributes);
3082
3083
3084   // Return the hash table backing store or the inline stored identity hash,
3085   // whatever is found.
3086   MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
3087
3088   // Return the hash table backing store for hidden properties.  If there is no
3089   // backing store, allocate one.
3090   static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
3091       Handle<JSObject> object);
3092
3093   // Set the hidden property backing store to either a hash table or
3094   // the inline-stored identity hash.
3095   static Handle<Object> SetHiddenPropertiesHashTable(
3096       Handle<JSObject> object,
3097       Handle<Object> value);
3098
3099   MUST_USE_RESULT Object* GetIdentityHash();
3100
3101   static Handle<Object> GetOrCreateIdentityHash(Handle<JSObject> object);
3102
3103   DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
3104 };
3105
3106
3107 // Common superclass for FixedArrays that allow implementations to share
3108 // common accessors and some code paths.
3109 class FixedArrayBase: public HeapObject {
3110  public:
3111   // [length]: length of the array.
3112   inline int length();
3113   inline void set_length(int value);
3114
3115   inline static FixedArrayBase* cast(Object* object);
3116
3117   // Layout description.
3118   // Length is smi tagged when it is stored.
3119   static const int kLengthOffset = HeapObject::kHeaderSize;
3120   static const int kHeaderSize = kLengthOffset + kPointerSize;
3121 };
3122
3123
3124 class FixedDoubleArray;
3125 class IncrementalMarking;
3126
3127
3128 // FixedArray describes fixed-sized arrays with element type Object*.
3129 class FixedArray: public FixedArrayBase {
3130  public:
3131   // Setter and getter for elements.
3132   inline Object* get(int index);
3133   // Setter that uses write barrier.
3134   inline void set(int index, Object* value);
3135   inline bool is_the_hole(int index);
3136
3137   // Setter that doesn't need write barrier.
3138   inline void set(int index, Smi* value);
3139   // Setter with explicit barrier mode.
3140   inline void set(int index, Object* value, WriteBarrierMode mode);
3141
3142   // Setters for frequently used oddballs located in old space.
3143   inline void set_undefined(int index);
3144   inline void set_null(int index);
3145   inline void set_the_hole(int index);
3146
3147   inline Object** GetFirstElementAddress();
3148   inline bool ContainsOnlySmisOrHoles();
3149
3150   // Gives access to raw memory which stores the array's data.
3151   inline Object** data_start();
3152
3153   // Shrink length and insert filler objects.
3154   void Shrink(int length);
3155
3156   // Copy operations.
3157   MUST_USE_RESULT inline MaybeObject* Copy();
3158   MUST_USE_RESULT MaybeObject* CopySize(int new_length,
3159                                         PretenureFlag pretenure = NOT_TENURED);
3160
3161   // Add the elements of a JSArray to this FixedArray.
3162   MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
3163
3164   // Compute the union of this and other.
3165   MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
3166
3167   // Copy a sub array from the receiver to dest.
3168   void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
3169
3170   // Garbage collection support.
3171   static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
3172
3173   // Code Generation support.
3174   static int OffsetOfElementAt(int index) { return SizeFor(index); }
3175
3176   // Garbage collection support.
3177   Object** RawFieldOfElementAt(int index) {
3178     return HeapObject::RawField(this, OffsetOfElementAt(index));
3179   }
3180
3181   // Casting.
3182   static inline FixedArray* cast(Object* obj);
3183
3184   // Maximal allowed size, in bytes, of a single FixedArray.
3185   // Prevents overflowing size computations, as well as extreme memory
3186   // consumption.
3187   static const int kMaxSize = 128 * MB * kPointerSize;
3188   // Maximally allowed length of a FixedArray.
3189   static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
3190
3191   // Dispatched behavior.
3192   DECLARE_PRINTER(FixedArray)
3193   DECLARE_VERIFIER(FixedArray)
3194 #ifdef DEBUG
3195   // Checks if two FixedArrays have identical contents.
3196   bool IsEqualTo(FixedArray* other);
3197 #endif
3198
3199   // Swap two elements in a pair of arrays.  If this array and the
3200   // numbers array are the same object, the elements are only swapped
3201   // once.
3202   void SwapPairs(FixedArray* numbers, int i, int j);
3203
3204   // Sort prefix of this array and the numbers array as pairs wrt. the
3205   // numbers.  If the numbers array and the this array are the same
3206   // object, the prefix of this array is sorted.
3207   void SortPairs(FixedArray* numbers, uint32_t len);
3208
3209   class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
3210    public:
3211     static inline int SizeOf(Map* map, HeapObject* object) {
3212       return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
3213     }
3214   };
3215
3216  protected:
3217   // Set operation on FixedArray without using write barriers. Can
3218   // only be used for storing old space objects or smis.
3219   static inline void NoWriteBarrierSet(FixedArray* array,
3220                                        int index,
3221                                        Object* value);
3222
3223   // Set operation on FixedArray without incremental write barrier. Can
3224   // only be used if the object is guaranteed to be white (whiteness witness
3225   // is present).
3226   static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
3227                                                   int index,
3228                                                   Object* value);
3229
3230  private:
3231   STATIC_CHECK(kHeaderSize == Internals::kFixedArrayHeaderSize);
3232
3233   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
3234 };
3235
3236
3237 // FixedDoubleArray describes fixed-sized arrays with element type double.
3238 class FixedDoubleArray: public FixedArrayBase {
3239  public:
3240   // Setter and getter for elements.
3241   inline double get_scalar(int index);
3242   inline int64_t get_representation(int index);
3243   MUST_USE_RESULT inline MaybeObject* get(int index);
3244   inline void set(int index, double value);
3245   inline void set_the_hole(int index);
3246
3247   // Checking for the hole.
3248   inline bool is_the_hole(int index);
3249
3250   // Copy operations
3251   MUST_USE_RESULT inline MaybeObject* Copy();
3252
3253   // Garbage collection support.
3254   inline static int SizeFor(int length) {
3255     return kHeaderSize + length * kDoubleSize;
3256   }
3257
3258   // Gives access to raw memory which stores the array's data.
3259   inline double* data_start();
3260
3261   // Code Generation support.
3262   static int OffsetOfElementAt(int index) { return SizeFor(index); }
3263
3264   inline static bool is_the_hole_nan(double value);
3265   inline static double hole_nan_as_double();
3266   inline static double canonical_not_the_hole_nan_as_double();
3267
3268   // Casting.
3269   static inline FixedDoubleArray* cast(Object* obj);
3270
3271   // Maximal allowed size, in bytes, of a single FixedDoubleArray.
3272   // Prevents overflowing size computations, as well as extreme memory
3273   // consumption.
3274   static const int kMaxSize = 512 * MB;
3275   // Maximally allowed length of a FixedArray.
3276   static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
3277
3278   // Dispatched behavior.
3279   DECLARE_PRINTER(FixedDoubleArray)
3280   DECLARE_VERIFIER(FixedDoubleArray)
3281
3282  private:
3283   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
3284 };
3285
3286
3287 // ConstantPoolArray describes a fixed-sized array containing constant pool
3288 // entires.
3289 // The format of the pool is:
3290 //   [0]: Field holding the first index which is a raw code target pointer entry
3291 //   [1]: Field holding the first index which is a heap pointer entry
3292 //   [2]: Field holding the first index which is a int32 entry
3293 //   [3]                      ... [first_code_ptr_index() - 1] : 64 bit entries
3294 //   [first_code_ptr_index()] ... [first_heap_ptr_index() - 1] : code pointers
3295 //   [first_heap_ptr_index()] ... [first_int32_index() - 1]    : heap pointers
3296 //   [first_int32_index()]    ... [length - 1]                 : 32 bit entries
3297 class ConstantPoolArray: public FixedArrayBase {
3298  public:
3299   // Getters for the field storing the first index for different type entries.
3300   inline int first_code_ptr_index();
3301   inline int first_heap_ptr_index();
3302   inline int first_int64_index();
3303   inline int first_int32_index();
3304
3305   // Getters for counts of different type entries.
3306   inline int count_of_code_ptr_entries();
3307   inline int count_of_heap_ptr_entries();
3308   inline int count_of_int64_entries();
3309   inline int count_of_int32_entries();
3310
3311   // Setter and getter for pool elements.
3312   inline Address get_code_ptr_entry(int index);
3313   inline Object* get_heap_ptr_entry(int index);
3314   inline int64_t get_int64_entry(int index);
3315   inline int32_t get_int32_entry(int index);
3316   inline double get_int64_entry_as_double(int index);
3317
3318   inline void set(int index, Address value);
3319   inline void set(int index, Object* value);
3320   inline void set(int index, int64_t value);
3321   inline void set(int index, double value);
3322   inline void set(int index, int32_t value);
3323
3324   // Set up initial state.
3325   inline void SetEntryCounts(int number_of_int64_entries,
3326                              int number_of_code_ptr_entries,
3327                              int number_of_heap_ptr_entries,
3328                              int number_of_int32_entries);
3329
3330   // Copy operations
3331   MUST_USE_RESULT inline MaybeObject* Copy();
3332
3333   // Garbage collection support.
3334   inline static int SizeFor(int number_of_int64_entries,
3335                             int number_of_code_ptr_entries,
3336                             int number_of_heap_ptr_entries,
3337                             int number_of_int32_entries) {
3338     return RoundUp(OffsetAt(number_of_int64_entries,
3339                             number_of_code_ptr_entries,
3340                             number_of_heap_ptr_entries,
3341                             number_of_int32_entries),
3342                    kPointerSize);
3343   }
3344
3345   // Code Generation support.
3346   inline int OffsetOfElementAt(int index) {
3347     ASSERT(index < length());
3348     if (index >= first_int32_index()) {
3349       return OffsetAt(count_of_int64_entries(), count_of_code_ptr_entries(),
3350                       count_of_heap_ptr_entries(), index - first_int32_index());
3351     } else if (index >= first_heap_ptr_index()) {
3352       return OffsetAt(count_of_int64_entries(), count_of_code_ptr_entries(),
3353                       index - first_heap_ptr_index(), 0);
3354     } else if (index >= first_code_ptr_index()) {
3355       return OffsetAt(count_of_int64_entries(), index - first_code_ptr_index(),
3356                       0, 0);
3357     } else {
3358       return OffsetAt(index, 0, 0, 0);
3359     }
3360   }
3361
3362   // Casting.
3363   static inline ConstantPoolArray* cast(Object* obj);
3364
3365   // Garbage collection support.
3366   Object** RawFieldOfElementAt(int index) {
3367     return HeapObject::RawField(this, OffsetOfElementAt(index));
3368   }
3369
3370   // Layout description.
3371   static const int kFirstCodePointerIndexOffset = FixedArray::kHeaderSize;
3372   static const int kFirstHeapPointerIndexOffset =
3373       kFirstCodePointerIndexOffset + kPointerSize;
3374   static const int kFirstInt32IndexOffset =
3375       kFirstHeapPointerIndexOffset + kPointerSize;
3376   static const int kFirstOffset = kFirstInt32IndexOffset + kPointerSize;
3377
3378   // Dispatched behavior.
3379   void ConstantPoolIterateBody(ObjectVisitor* v);
3380
3381   DECLARE_PRINTER(ConstantPoolArray)
3382   DECLARE_VERIFIER(ConstantPoolArray)
3383
3384  private:
3385   inline void set_first_code_ptr_index(int value);
3386   inline void set_first_heap_ptr_index(int value);
3387   inline void set_first_int32_index(int value);
3388
3389   inline static int OffsetAt(int number_of_int64_entries,
3390                              int number_of_code_ptr_entries,
3391                              int number_of_heap_ptr_entries,
3392                              int number_of_int32_entries) {
3393     return kFirstOffset
3394         + (number_of_int64_entries * kInt64Size)
3395         + (number_of_code_ptr_entries * kPointerSize)
3396         + (number_of_heap_ptr_entries * kPointerSize)
3397         + (number_of_int32_entries * kInt32Size);
3398   }
3399
3400   DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
3401 };
3402
3403
3404 // DescriptorArrays are fixed arrays used to hold instance descriptors.
3405 // The format of the these objects is:
3406 //   [0]: Number of descriptors
3407 //   [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
3408 //          [0]: pointer to fixed array with enum cache
3409 //          [1]: either Smi(0) or pointer to fixed array with indices
3410 //   [2]: first key
3411 //   [2 + number of descriptors * kDescriptorSize]: start of slack
3412 class DescriptorArray: public FixedArray {
3413  public:
3414   // WhitenessWitness is used to prove that a descriptor array is white
3415   // (unmarked), so incremental write barriers can be skipped because the
3416   // marking invariant cannot be broken and slots pointing into evacuation
3417   // candidates will be discovered when the object is scanned. A witness is
3418   // always stack-allocated right after creating an array. By allocating a
3419   // witness, incremental marking is globally disabled. The witness is then
3420   // passed along wherever needed to statically prove that the array is known to
3421   // be white.
3422   class WhitenessWitness {
3423    public:
3424     inline explicit WhitenessWitness(FixedArray* array);
3425     inline ~WhitenessWitness();
3426
3427    private:
3428     IncrementalMarking* marking_;
3429   };
3430
3431   // Returns true for both shared empty_descriptor_array and for smis, which the
3432   // map uses to encode additional bit fields when the descriptor array is not
3433   // yet used.
3434   inline bool IsEmpty();
3435
3436   // Returns the number of descriptors in the array.
3437   int number_of_descriptors() {
3438     ASSERT(length() >= kFirstIndex || IsEmpty());
3439     int len = length();
3440     return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
3441   }
3442
3443   int number_of_descriptors_storage() {
3444     int len = length();
3445     return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
3446   }
3447
3448   int NumberOfSlackDescriptors() {
3449     return number_of_descriptors_storage() - number_of_descriptors();
3450   }
3451
3452   inline void SetNumberOfDescriptors(int number_of_descriptors);
3453   inline int number_of_entries() { return number_of_descriptors(); }
3454
3455   bool HasEnumCache() {
3456     return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
3457   }
3458
3459   void CopyEnumCacheFrom(DescriptorArray* array) {
3460     set(kEnumCacheIndex, array->get(kEnumCacheIndex));
3461   }
3462
3463   FixedArray* GetEnumCache() {
3464     ASSERT(HasEnumCache());
3465     FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3466     return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
3467   }
3468
3469   bool HasEnumIndicesCache() {
3470     if (IsEmpty()) return false;
3471     Object* object = get(kEnumCacheIndex);
3472     if (object->IsSmi()) return false;
3473     FixedArray* bridge = FixedArray::cast(object);
3474     return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
3475   }
3476
3477   FixedArray* GetEnumIndicesCache() {
3478     ASSERT(HasEnumIndicesCache());
3479     FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
3480     return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
3481   }
3482
3483   Object** GetEnumCacheSlot() {
3484     ASSERT(HasEnumCache());
3485     return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
3486                                 kEnumCacheOffset);
3487   }
3488
3489   void ClearEnumCache();
3490
3491   // Initialize or change the enum cache,
3492   // using the supplied storage for the small "bridge".
3493   void SetEnumCache(FixedArray* bridge_storage,
3494                     FixedArray* new_cache,
3495                     Object* new_index_cache);
3496
3497   // Accessors for fetching instance descriptor at descriptor number.
3498   inline Name* GetKey(int descriptor_number);
3499   inline Object** GetKeySlot(int descriptor_number);
3500   inline Object* GetValue(int descriptor_number);
3501   inline Object** GetValueSlot(int descriptor_number);
3502   inline Object** GetDescriptorStartSlot(int descriptor_number);
3503   inline Object** GetDescriptorEndSlot(int descriptor_number);
3504   inline PropertyDetails GetDetails(int descriptor_number);
3505   inline PropertyType GetType(int descriptor_number);
3506   inline int GetFieldIndex(int descriptor_number);
3507   inline Object* GetConstant(int descriptor_number);
3508   inline Object* GetCallbacksObject(int descriptor_number);
3509   inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3510
3511   inline Name* GetSortedKey(int descriptor_number);
3512   inline int GetSortedKeyIndex(int descriptor_number);
3513   inline void SetSortedKey(int pointer, int descriptor_number);
3514   inline void InitializeRepresentations(Representation representation);
3515   inline void SetRepresentation(int descriptor_number,
3516                                 Representation representation);
3517
3518   // Accessor for complete descriptor.
3519   inline void Get(int descriptor_number, Descriptor* desc);
3520   inline void Set(int descriptor_number,
3521                   Descriptor* desc,
3522                   const WhitenessWitness&);
3523   inline void Set(int descriptor_number, Descriptor* desc);
3524
3525   // Append automatically sets the enumeration index. This should only be used
3526   // to add descriptors in bulk at the end, followed by sorting the descriptor
3527   // array.
3528   inline void Append(Descriptor* desc, const WhitenessWitness&);
3529   inline void Append(Descriptor* desc);
3530
3531   // Transfer a complete descriptor from the src descriptor array to this
3532   // descriptor array.
3533   void CopyFrom(int dst_index,
3534                 DescriptorArray* src,
3535                 int src_index,
3536                 const WhitenessWitness&);
3537   static Handle<DescriptorArray> Merge(Handle<DescriptorArray> desc,
3538                                        int verbatim,
3539                                        int valid,
3540                                        int new_size,
3541                                        int modify_index,
3542                                        StoreMode store_mode,
3543                                        Handle<DescriptorArray> other);
3544   MUST_USE_RESULT MaybeObject* Merge(int verbatim,
3545                                      int valid,
3546                                      int new_size,
3547                                      int modify_index,
3548                                      StoreMode store_mode,
3549                                      DescriptorArray* other);
3550
3551   bool IsMoreGeneralThan(int verbatim,
3552                          int valid,
3553                          int new_size,
3554                          DescriptorArray* other);
3555
3556   MUST_USE_RESULT MaybeObject* CopyUpTo(int enumeration_index) {
3557     return CopyUpToAddAttributes(enumeration_index, NONE);
3558   }
3559
3560   static Handle<DescriptorArray> CopyUpToAddAttributes(
3561       Handle<DescriptorArray> desc,
3562       int enumeration_index,
3563       PropertyAttributes attributes);
3564   MUST_USE_RESULT MaybeObject* CopyUpToAddAttributes(
3565       int enumeration_index,
3566       PropertyAttributes attributes);
3567
3568   // Sort the instance descriptors by the hash codes of their keys.
3569   void Sort();
3570
3571   // Search the instance descriptors for given name.
3572   INLINE(int Search(Name* name, int number_of_own_descriptors));
3573
3574   // As the above, but uses DescriptorLookupCache and updates it when
3575   // necessary.
3576   INLINE(int SearchWithCache(Name* name, Map* map));
3577
3578   // Allocates a DescriptorArray, but returns the singleton
3579   // empty descriptor array object if number_of_descriptors is 0.
3580   MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
3581                                                int number_of_descriptors,
3582                                                int slack = 0);
3583
3584   // Casting.
3585   static inline DescriptorArray* cast(Object* obj);
3586
3587   // Constant for denoting key was not found.
3588   static const int kNotFound = -1;
3589
3590   static const int kDescriptorLengthIndex = 0;
3591   static const int kEnumCacheIndex = 1;
3592   static const int kFirstIndex = 2;
3593
3594   // The length of the "bridge" to the enum cache.
3595   static const int kEnumCacheBridgeLength = 2;
3596   static const int kEnumCacheBridgeCacheIndex = 0;
3597   static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3598
3599   // Layout description.
3600   static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3601   static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3602   static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3603
3604   // Layout description for the bridge array.
3605   static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3606
3607   // Layout of descriptor.
3608   static const int kDescriptorKey = 0;
3609   static const int kDescriptorDetails = 1;
3610   static const int kDescriptorValue = 2;
3611   static const int kDescriptorSize = 3;
3612
3613 #ifdef OBJECT_PRINT
3614   // Print all the descriptors.
3615   void PrintDescriptors(FILE* out = stdout);
3616 #endif
3617
3618 #ifdef DEBUG
3619   // Is the descriptor array sorted and without duplicates?
3620   bool IsSortedNoDuplicates(int valid_descriptors = -1);
3621
3622   // Is the descriptor array consistent with the back pointers in targets?
3623   bool IsConsistentWithBackPointers(Map* current_map);
3624
3625   // Are two DescriptorArrays equal?
3626   bool IsEqualTo(DescriptorArray* other);
3627 #endif
3628
3629   // Returns the fixed array length required to hold number_of_descriptors
3630   // descriptors.
3631   static int LengthFor(int number_of_descriptors) {
3632     return ToKeyIndex(number_of_descriptors);
3633   }
3634
3635  private:
3636   // An entry in a DescriptorArray, represented as an (array, index) pair.
3637   class Entry {
3638    public:
3639     inline explicit Entry(DescriptorArray* descs, int index) :
3640         descs_(descs), index_(index) { }
3641
3642     inline PropertyType type() { return descs_->GetType(index_); }
3643     inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3644
3645    private:
3646     DescriptorArray* descs_;
3647     int index_;
3648   };
3649
3650   // Conversion from descriptor number to array indices.
3651   static int ToKeyIndex(int descriptor_number) {
3652     return kFirstIndex +
3653            (descriptor_number * kDescriptorSize) +
3654            kDescriptorKey;
3655   }
3656
3657   static int ToDetailsIndex(int descriptor_number) {
3658     return kFirstIndex +
3659            (descriptor_number * kDescriptorSize) +
3660            kDescriptorDetails;
3661   }
3662
3663   static int ToValueIndex(int descriptor_number) {
3664     return kFirstIndex +
3665            (descriptor_number * kDescriptorSize) +
3666            kDescriptorValue;
3667   }
3668
3669   // Swap first and second descriptor.
3670   inline void SwapSortedKeys(int first, int second);
3671
3672   DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3673 };
3674
3675
3676 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3677
3678 template<SearchMode search_mode, typename T>
3679 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3680
3681
3682 template<SearchMode search_mode, typename T>
3683 inline int Search(T* array, Name* name, int valid_entries = 0);
3684
3685
3686 // HashTable is a subclass of FixedArray that implements a hash table
3687 // that uses open addressing and quadratic probing.
3688 //
3689 // In order for the quadratic probing to work, elements that have not
3690 // yet been used and elements that have been deleted are
3691 // distinguished.  Probing continues when deleted elements are
3692 // encountered and stops when unused elements are encountered.
3693 //
3694 // - Elements with key == undefined have not been used yet.
3695 // - Elements with key == the_hole have been deleted.
3696 //
3697 // The hash table class is parameterized with a Shape and a Key.
3698 // Shape must be a class with the following interface:
3699 //   class ExampleShape {
3700 //    public:
3701 //      // Tells whether key matches other.
3702 //     static bool IsMatch(Key key, Object* other);
3703 //     // Returns the hash value for key.
3704 //     static uint32_t Hash(Key key);
3705 //     // Returns the hash value for object.
3706 //     static uint32_t HashForObject(Key key, Object* object);
3707 //     // Convert key to an object.
3708 //     static inline Object* AsObject(Heap* heap, Key key);
3709 //     // The prefix size indicates number of elements in the beginning
3710 //     // of the backing storage.
3711 //     static const int kPrefixSize = ..;
3712 //     // The Element size indicates number of elements per entry.
3713 //     static const int kEntrySize = ..;
3714 //   };
3715 // The prefix size indicates an amount of memory in the
3716 // beginning of the backing storage that can be used for non-element
3717 // information by subclasses.
3718
3719 template<typename Key>
3720 class BaseShape {
3721  public:
3722   static const bool UsesSeed = false;
3723   static uint32_t Hash(Key key) { return 0; }
3724   static uint32_t SeededHash(Key key, uint32_t seed) {
3725     ASSERT(UsesSeed);
3726     return Hash(key);
3727   }
3728   static uint32_t HashForObject(Key key, Object* object) { return 0; }
3729   static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3730     ASSERT(UsesSeed);
3731     return HashForObject(key, object);
3732   }
3733 };
3734
3735 template<typename Shape, typename Key>
3736 class HashTable: public FixedArray {
3737  public:
3738   // Wrapper methods
3739   inline uint32_t Hash(Key key) {
3740     if (Shape::UsesSeed) {
3741       return Shape::SeededHash(key,
3742           GetHeap()->HashSeed());
3743     } else {
3744       return Shape::Hash(key);
3745     }
3746   }
3747
3748   inline uint32_t HashForObject(Key key, Object* object) {
3749     if (Shape::UsesSeed) {
3750       return Shape::SeededHashForObject(key,
3751           GetHeap()->HashSeed(), object);
3752     } else {
3753       return Shape::HashForObject(key, object);
3754     }
3755   }
3756
3757   // Returns the number of elements in the hash table.
3758   int NumberOfElements() {
3759     return Smi::cast(get(kNumberOfElementsIndex))->value();
3760   }
3761
3762   // Returns the number of deleted elements in the hash table.
3763   int NumberOfDeletedElements() {
3764     return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3765   }
3766
3767   // Returns the capacity of the hash table.
3768   int Capacity() {
3769     return Smi::cast(get(kCapacityIndex))->value();
3770   }
3771
3772   // ElementAdded should be called whenever an element is added to a
3773   // hash table.
3774   void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3775
3776   // ElementRemoved should be called whenever an element is removed from
3777   // a hash table.
3778   void ElementRemoved() {
3779     SetNumberOfElements(NumberOfElements() - 1);
3780     SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3781   }
3782   void ElementsRemoved(int n) {
3783     SetNumberOfElements(NumberOfElements() - n);
3784     SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3785   }
3786
3787   // Returns a new HashTable object. Might return Failure.
3788   MUST_USE_RESULT static MaybeObject* Allocate(
3789       Heap* heap,
3790       int at_least_space_for,
3791       MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3792       PretenureFlag pretenure = NOT_TENURED);
3793
3794   // Computes the required capacity for a table holding the given
3795   // number of elements. May be more than HashTable::kMaxCapacity.
3796   static int ComputeCapacity(int at_least_space_for);
3797
3798   // Returns the key at entry.
3799   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3800
3801   // Tells whether k is a real key.  The hole and undefined are not allowed
3802   // as keys and can be used to indicate missing or deleted elements.
3803   bool IsKey(Object* k) {
3804     return !k->IsTheHole() && !k->IsUndefined();
3805   }
3806
3807   // Garbage collection support.
3808   void IteratePrefix(ObjectVisitor* visitor);
3809   void IterateElements(ObjectVisitor* visitor);
3810
3811   // Casting.
3812   static inline HashTable* cast(Object* obj);
3813
3814   // Compute the probe offset (quadratic probing).
3815   INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3816     return (n + n * n) >> 1;
3817   }
3818
3819   static const int kNumberOfElementsIndex = 0;
3820   static const int kNumberOfDeletedElementsIndex = 1;
3821   static const int kCapacityIndex = 2;
3822   static const int kPrefixStartIndex = 3;
3823   static const int kElementsStartIndex =
3824       kPrefixStartIndex + Shape::kPrefixSize;
3825   static const int kEntrySize = Shape::kEntrySize;
3826   static const int kElementsStartOffset =
3827       kHeaderSize + kElementsStartIndex * kPointerSize;
3828   static const int kCapacityOffset =
3829       kHeaderSize + kCapacityIndex * kPointerSize;
3830
3831   // Constant used for denoting a absent entry.
3832   static const int kNotFound = -1;
3833
3834   // Maximal capacity of HashTable. Based on maximal length of underlying
3835   // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3836   // cannot overflow.
3837   static const int kMaxCapacity =
3838       (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3839
3840   // Find entry for key otherwise return kNotFound.
3841   inline int FindEntry(Key key);
3842   int FindEntry(Isolate* isolate, Key key);
3843
3844   // Rehashes the table in-place.
3845   void Rehash(Key key);
3846
3847  protected:
3848   friend class ObjectHashSet;
3849   friend class ObjectHashTable;
3850
3851   // Find the entry at which to insert element with the given key that
3852   // has the given hash value.
3853   uint32_t FindInsertionEntry(uint32_t hash);
3854
3855   // Returns the index for an entry (of the key)
3856   static inline int EntryToIndex(int entry) {
3857     return (entry * kEntrySize) + kElementsStartIndex;
3858   }
3859
3860   // Update the number of elements in the hash table.
3861   void SetNumberOfElements(int nof) {
3862     set(kNumberOfElementsIndex, Smi::FromInt(nof));
3863   }
3864
3865   // Update the number of deleted elements in the hash table.
3866   void SetNumberOfDeletedElements(int nod) {
3867     set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3868   }
3869
3870   // Sets the capacity of the hash table.
3871   void SetCapacity(int capacity) {
3872     // To scale a computed hash code to fit within the hash table, we
3873     // use bit-wise AND with a mask, so the capacity must be positive
3874     // and non-zero.
3875     ASSERT(capacity > 0);
3876     ASSERT(capacity <= kMaxCapacity);
3877     set(kCapacityIndex, Smi::FromInt(capacity));
3878   }
3879
3880
3881   // Returns probe entry.
3882   static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3883     ASSERT(IsPowerOf2(size));
3884     return (hash + GetProbeOffset(number)) & (size - 1);
3885   }
3886
3887   inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3888     return hash & (size - 1);
3889   }
3890
3891   inline static uint32_t NextProbe(
3892       uint32_t last, uint32_t number, uint32_t size) {
3893     return (last + number) & (size - 1);
3894   }
3895
3896   // Returns _expected_ if one of entries given by the first _probe_ probes is
3897   // equal to  _expected_. Otherwise, returns the entry given by the probe
3898   // number _probe_.
3899   uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3900
3901   void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3902
3903   // Rehashes this hash-table into the new table.
3904   MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
3905
3906   // Attempt to shrink hash table after removal of key.
3907   MUST_USE_RESULT MaybeObject* Shrink(Key key);
3908
3909   // Ensure enough space for n additional elements.
3910   MUST_USE_RESULT MaybeObject* EnsureCapacity(
3911       int n,
3912       Key key,
3913       PretenureFlag pretenure = NOT_TENURED);
3914 };
3915
3916
3917 // HashTableKey is an abstract superclass for virtual key behavior.
3918 class HashTableKey {
3919  public:
3920   // Returns whether the other object matches this key.
3921   virtual bool IsMatch(Object* other) = 0;
3922   // Returns the hash value for this key.
3923   virtual uint32_t Hash() = 0;
3924   // Returns the hash value for object.
3925   virtual uint32_t HashForObject(Object* key) = 0;
3926   // Returns the key object for storing into the hash table.
3927   // If allocations fails a failure object is returned.
3928   MUST_USE_RESULT virtual MaybeObject* AsObject(Heap* heap) = 0;
3929   // Required.
3930   virtual ~HashTableKey() {}
3931 };
3932
3933
3934 class StringTableShape : public BaseShape<HashTableKey*> {
3935  public:
3936   static inline bool IsMatch(HashTableKey* key, Object* value) {
3937     return key->IsMatch(value);
3938   }
3939   static inline uint32_t Hash(HashTableKey* key) {
3940     return key->Hash();
3941   }
3942   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3943     return key->HashForObject(object);
3944   }
3945   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3946                                                       HashTableKey* key) {
3947     return key->AsObject(heap);
3948   }
3949
3950   static const int kPrefixSize = 0;
3951   static const int kEntrySize = 1;
3952 };
3953
3954 class SeqOneByteString;
3955
3956 // StringTable.
3957 //
3958 // No special elements in the prefix and the element size is 1
3959 // because only the string itself (the key) needs to be stored.
3960 class StringTable: public HashTable<StringTableShape, HashTableKey*> {
3961  public:
3962   // Find string in the string table.  If it is not there yet, it is
3963   // added.  The return value is the string table which might have
3964   // been enlarged.  If the return value is not a failure, the string
3965   // pointer *s is set to the string found.
3966   MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
3967   MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
3968
3969   // Looks up a string that is equal to the given string and returns
3970   // true if it is found, assigning the string to the given output
3971   // parameter.
3972   bool LookupStringIfExists(String* str, String** result);
3973   bool LookupTwoCharsStringIfExists(uint16_t c1, uint16_t c2, String** result);
3974
3975   // Casting.
3976   static inline StringTable* cast(Object* obj);
3977
3978  private:
3979   template <bool seq_ascii> friend class JsonParser;
3980
3981   DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3982 };
3983
3984
3985 class MapCacheShape : public BaseShape<HashTableKey*> {
3986  public:
3987   static inline bool IsMatch(HashTableKey* key, Object* value) {
3988     return key->IsMatch(value);
3989   }
3990   static inline uint32_t Hash(HashTableKey* key) {
3991     return key->Hash();
3992   }
3993
3994   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3995     return key->HashForObject(object);
3996   }
3997
3998   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
3999                                                       HashTableKey* key) {
4000     return key->AsObject(heap);
4001   }
4002
4003   static const int kPrefixSize = 0;
4004   static const int kEntrySize = 2;
4005 };
4006
4007
4008 // MapCache.
4009 //
4010 // Maps keys that are a fixed array of unique names to a map.
4011 // Used for canonicalize maps for object literals.
4012 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
4013  public:
4014   // Find cached value for a name key, otherwise return null.
4015   Object* Lookup(FixedArray* key);
4016   MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
4017   static inline MapCache* cast(Object* obj);
4018
4019  private:
4020   DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
4021 };
4022
4023
4024 template <typename Shape, typename Key>
4025 class Dictionary: public HashTable<Shape, Key> {
4026  public:
4027   static inline Dictionary<Shape, Key>* cast(Object* obj) {
4028     return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
4029   }
4030
4031   // Returns the value at entry.
4032   Object* ValueAt(int entry) {
4033     return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
4034   }
4035
4036   // Set the value for entry.
4037   void ValueAtPut(int entry, Object* value) {
4038     this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
4039   }
4040
4041   // Returns the property details for the property at entry.
4042   PropertyDetails DetailsAt(int entry) {
4043     ASSERT(entry >= 0);  // Not found is -1, which is not caught by get().
4044     return PropertyDetails(
4045         Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
4046   }
4047
4048   // Set the details for entry.
4049   void DetailsAtPut(int entry, PropertyDetails value) {
4050     this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
4051   }
4052
4053   // Sorting support
4054   void CopyValuesTo(FixedArray* elements);
4055
4056   // Delete a property from the dictionary.
4057   Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
4058
4059   // Attempt to shrink the dictionary after deletion of key.
4060   MUST_USE_RESULT MaybeObject* Shrink(Key key);
4061
4062   // Returns the number of elements in the dictionary filtering out properties
4063   // with the specified attributes.
4064   int NumberOfElementsFilterAttributes(PropertyAttributes filter);
4065
4066   // Returns the number of enumerable elements in the dictionary.
4067   int NumberOfEnumElements();
4068
4069   enum SortMode { UNSORTED, SORTED };
4070   // Copies keys to preallocated fixed array.
4071   void CopyKeysTo(FixedArray* storage,
4072                   PropertyAttributes filter,
4073                   SortMode sort_mode);
4074   // Fill in details for properties into storage.
4075   void CopyKeysTo(FixedArray* storage,
4076                   int index,
4077                   PropertyAttributes filter,
4078                   SortMode sort_mode);
4079
4080   // Accessors for next enumeration index.
4081   void SetNextEnumerationIndex(int index) {
4082     ASSERT(index != 0);
4083     this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
4084   }
4085
4086   int NextEnumerationIndex() {
4087     return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
4088   }
4089
4090   // Returns a new array for dictionary usage. Might return Failure.
4091   MUST_USE_RESULT static MaybeObject* Allocate(
4092       Heap* heap,
4093       int at_least_space_for,
4094       PretenureFlag pretenure = NOT_TENURED);
4095
4096   // Ensure enough space for n additional elements.
4097   MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
4098
4099 #ifdef OBJECT_PRINT
4100   void Print(FILE* out = stdout);
4101 #endif
4102   // Returns the key (slow).
4103   Object* SlowReverseLookup(Object* value);
4104
4105   // Sets the entry to (key, value) pair.
4106   inline void SetEntry(int entry,
4107                        Object* key,
4108                        Object* value);
4109   inline void SetEntry(int entry,
4110                        Object* key,
4111                        Object* value,
4112                        PropertyDetails details);
4113
4114   MUST_USE_RESULT MaybeObject* Add(Key key,
4115                                    Object* value,
4116                                    PropertyDetails details);
4117
4118  protected:
4119   // Generic at put operation.
4120   MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
4121
4122   // Add entry to dictionary.
4123   MUST_USE_RESULT MaybeObject* AddEntry(Key key,
4124                                         Object* value,
4125                                         PropertyDetails details,
4126                                         uint32_t hash);
4127
4128   // Generate new enumeration indices to avoid enumeration index overflow.
4129   MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
4130   static const int kMaxNumberKeyIndex =
4131       HashTable<Shape, Key>::kPrefixStartIndex;
4132   static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
4133 };
4134
4135
4136 class NameDictionaryShape : public BaseShape<Name*> {
4137  public:
4138   static inline bool IsMatch(Name* key, Object* other);
4139   static inline uint32_t Hash(Name* key);
4140   static inline uint32_t HashForObject(Name* key, Object* object);
4141   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4142                                                       Name* key);
4143   static const int kPrefixSize = 2;
4144   static const int kEntrySize = 3;
4145   static const bool kIsEnumerable = true;
4146 };
4147
4148
4149 class NameDictionary: public Dictionary<NameDictionaryShape, Name*> {
4150  public:
4151   static inline NameDictionary* cast(Object* obj) {
4152     ASSERT(obj->IsDictionary());
4153     return reinterpret_cast<NameDictionary*>(obj);
4154   }
4155
4156   // Copies enumerable keys to preallocated fixed array.
4157   void CopyEnumKeysTo(FixedArray* storage);
4158   static void DoGenerateNewEnumerationIndices(
4159       Handle<NameDictionary> dictionary);
4160
4161   // For transforming properties of a JSObject.
4162   MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
4163       JSObject* obj,
4164       int unused_property_fields);
4165
4166   // Find entry for key, otherwise return kNotFound. Optimized version of
4167   // HashTable::FindEntry.
4168   int FindEntry(Name* key);
4169 };
4170
4171
4172 class NumberDictionaryShape : public BaseShape<uint32_t> {
4173  public:
4174   static inline bool IsMatch(uint32_t key, Object* other);
4175   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4176                                                       uint32_t key);
4177   static const int kEntrySize = 3;
4178   static const bool kIsEnumerable = false;
4179 };
4180
4181
4182 class SeededNumberDictionaryShape : public NumberDictionaryShape {
4183  public:
4184   static const bool UsesSeed = true;
4185   static const int kPrefixSize = 2;
4186
4187   static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
4188   static inline uint32_t SeededHashForObject(uint32_t key,
4189                                              uint32_t seed,
4190                                              Object* object);
4191 };
4192
4193
4194 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
4195  public:
4196   static const int kPrefixSize = 0;
4197
4198   static inline uint32_t Hash(uint32_t key);
4199   static inline uint32_t HashForObject(uint32_t key, Object* object);
4200 };
4201
4202
4203 class SeededNumberDictionary
4204     : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
4205  public:
4206   static SeededNumberDictionary* cast(Object* obj) {
4207     ASSERT(obj->IsDictionary());
4208     return reinterpret_cast<SeededNumberDictionary*>(obj);
4209   }
4210
4211   // Type specific at put (default NONE attributes is used when adding).
4212   MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4213   MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
4214       Handle<SeededNumberDictionary> dictionary,
4215       uint32_t key,
4216       Handle<Object> value,
4217       PropertyDetails details);
4218   MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
4219                                               Object* value,
4220                                               PropertyDetails details);
4221
4222   // Set an existing entry or add a new one if needed.
4223   // Return the updated dictionary.
4224   MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
4225       Handle<SeededNumberDictionary> dictionary,
4226       uint32_t index,
4227       Handle<Object> value,
4228       PropertyDetails details);
4229
4230   MUST_USE_RESULT MaybeObject* Set(uint32_t key,
4231                                    Object* value,
4232                                    PropertyDetails details);
4233
4234   void UpdateMaxNumberKey(uint32_t key);
4235
4236   // If slow elements are required we will never go back to fast-case
4237   // for the elements kept in this dictionary.  We require slow
4238   // elements if an element has been added at an index larger than
4239   // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
4240   // when defining a getter or setter with a number key.
4241   inline bool requires_slow_elements();
4242   inline void set_requires_slow_elements();
4243
4244   // Get the value of the max number key that has been added to this
4245   // dictionary.  max_number_key can only be called if
4246   // requires_slow_elements returns false.
4247   inline uint32_t max_number_key();
4248
4249   // Bit masks.
4250   static const int kRequiresSlowElementsMask = 1;
4251   static const int kRequiresSlowElementsTagSize = 1;
4252   static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
4253 };
4254
4255
4256 class UnseededNumberDictionary
4257     : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
4258  public:
4259   static UnseededNumberDictionary* cast(Object* obj) {
4260     ASSERT(obj->IsDictionary());
4261     return reinterpret_cast<UnseededNumberDictionary*>(obj);
4262   }
4263
4264   // Type specific at put (default NONE attributes is used when adding).
4265   MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
4266   MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
4267
4268   // Set an existing entry or add a new one if needed.
4269   // Return the updated dictionary.
4270   MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
4271       Handle<UnseededNumberDictionary> dictionary,
4272       uint32_t index,
4273       Handle<Object> value);
4274
4275   MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
4276 };
4277
4278
4279 template <int entrysize>
4280 class ObjectHashTableShape : public BaseShape<Object*> {
4281  public:
4282   static inline bool IsMatch(Object* key, Object* other);
4283   static inline uint32_t Hash(Object* key);
4284   static inline uint32_t HashForObject(Object* key, Object* object);
4285   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4286                                                       Object* key);
4287   static const int kPrefixSize = 0;
4288   static const int kEntrySize = entrysize;
4289 };
4290
4291
4292 // ObjectHashSet holds keys that are arbitrary objects by using the identity
4293 // hash of the key for hashing purposes.
4294 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
4295  public:
4296   static inline ObjectHashSet* cast(Object* obj) {
4297     ASSERT(obj->IsHashTable());
4298     return reinterpret_cast<ObjectHashSet*>(obj);
4299   }
4300
4301   // Looks up whether the given key is part of this hash set.
4302   bool Contains(Object* key);
4303
4304   static Handle<ObjectHashSet> EnsureCapacity(
4305       Handle<ObjectHashSet> table,
4306       int n,
4307       Handle<Object> key,
4308       PretenureFlag pretenure = NOT_TENURED);
4309
4310   // Attempt to shrink hash table after removal of key.
4311   static Handle<ObjectHashSet> Shrink(Handle<ObjectHashSet> table,
4312                                       Handle<Object> key);
4313
4314   // Adds the given key to this hash set.
4315   static Handle<ObjectHashSet> Add(Handle<ObjectHashSet> table,
4316                                    Handle<Object> key);
4317
4318   // Removes the given key from this hash set.
4319   static Handle<ObjectHashSet> Remove(Handle<ObjectHashSet> table,
4320                                       Handle<Object> key);
4321 };
4322
4323
4324 // ObjectHashTable maps keys that are arbitrary objects to object values by
4325 // using the identity hash of the key for hashing purposes.
4326 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
4327  public:
4328   static inline ObjectHashTable* cast(Object* obj) {
4329     ASSERT(obj->IsHashTable());
4330     return reinterpret_cast<ObjectHashTable*>(obj);
4331   }
4332
4333   static Handle<ObjectHashTable> EnsureCapacity(
4334       Handle<ObjectHashTable> table,
4335       int n,
4336       Handle<Object> key,
4337       PretenureFlag pretenure = NOT_TENURED);
4338
4339   // Attempt to shrink hash table after removal of key.
4340   static Handle<ObjectHashTable> Shrink(Handle<ObjectHashTable> table,
4341                                         Handle<Object> key);
4342
4343   // Looks up the value associated with the given key. The hole value is
4344   // returned in case the key is not present.
4345   Object* Lookup(Object* key);
4346
4347   // Adds (or overwrites) the value associated with the given key. Mapping a
4348   // key to the hole value causes removal of the whole entry.
4349   static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
4350                                      Handle<Object> key,
4351                                      Handle<Object> value);
4352
4353  private:
4354   friend class MarkCompactCollector;
4355
4356   void AddEntry(int entry, Object* key, Object* value);
4357   void RemoveEntry(int entry);
4358
4359   // Returns the index to the value of an entry.
4360   static inline int EntryToValueIndex(int entry) {
4361     return EntryToIndex(entry) + 1;
4362   }
4363 };
4364
4365
4366 template <int entrysize>
4367 class WeakHashTableShape : public BaseShape<Object*> {
4368  public:
4369   static inline bool IsMatch(Object* key, Object* other);
4370   static inline uint32_t Hash(Object* key);
4371   static inline uint32_t HashForObject(Object* key, Object* object);
4372   MUST_USE_RESULT static inline MaybeObject* AsObject(Heap* heap,
4373                                                       Object* key);
4374   static const int kPrefixSize = 0;
4375   static const int kEntrySize = entrysize;
4376 };
4377
4378
4379 // WeakHashTable maps keys that are arbitrary objects to object values.
4380 // It is used for the global weak hash table that maps objects
4381 // embedded in optimized code to dependent code lists.
4382 class WeakHashTable: public HashTable<WeakHashTableShape<2>, Object*> {
4383  public:
4384   static inline WeakHashTable* cast(Object* obj) {
4385     ASSERT(obj->IsHashTable());
4386     return reinterpret_cast<WeakHashTable*>(obj);
4387   }
4388
4389   // Looks up the value associated with the given key. The hole value is
4390   // returned in case the key is not present.
4391   Object* Lookup(Object* key);
4392
4393   // Adds (or overwrites) the value associated with the given key. Mapping a
4394   // key to the hole value causes removal of the whole entry.
4395   MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
4396
4397   // This function is called when heap verification is turned on.
4398   void Zap(Object* value) {
4399     int capacity = Capacity();
4400     for (int i = 0; i < capacity; i++) {
4401       set(EntryToIndex(i), value);
4402       set(EntryToValueIndex(i), value);
4403     }
4404   }
4405
4406  private:
4407   friend class MarkCompactCollector;
4408
4409   void AddEntry(int entry, Object* key, Object* value);
4410
4411   // Returns the index to the value of an entry.
4412   static inline int EntryToValueIndex(int entry) {
4413     return EntryToIndex(entry) + 1;
4414   }
4415 };
4416
4417
4418 // JSFunctionResultCache caches results of some JSFunction invocation.
4419 // It is a fixed array with fixed structure:
4420 //   [0]: factory function
4421 //   [1]: finger index
4422 //   [2]: current cache size
4423 //   [3]: dummy field.
4424 // The rest of array are key/value pairs.
4425 class JSFunctionResultCache: public FixedArray {
4426  public:
4427   static const int kFactoryIndex = 0;
4428   static const int kFingerIndex = kFactoryIndex + 1;
4429   static const int kCacheSizeIndex = kFingerIndex + 1;
4430   static const int kDummyIndex = kCacheSizeIndex + 1;
4431   static const int kEntriesIndex = kDummyIndex + 1;
4432
4433   static const int kEntrySize = 2;  // key + value
4434
4435   static const int kFactoryOffset = kHeaderSize;
4436   static const int kFingerOffset = kFactoryOffset + kPointerSize;
4437   static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4438
4439   inline void MakeZeroSize();
4440   inline void Clear();
4441
4442   inline int size();
4443   inline void set_size(int size);
4444   inline int finger_index();
4445   inline void set_finger_index(int finger_index);
4446
4447   // Casting
4448   static inline JSFunctionResultCache* cast(Object* obj);
4449
4450   DECLARE_VERIFIER(JSFunctionResultCache)
4451 };
4452
4453
4454 // ScopeInfo represents information about different scopes of a source
4455 // program  and the allocation of the scope's variables. Scope information
4456 // is stored in a compressed form in ScopeInfo objects and is used
4457 // at runtime (stack dumps, deoptimization, etc.).
4458
4459 // This object provides quick access to scope info details for runtime
4460 // routines.
4461 class ScopeInfo : public FixedArray {
4462  public:
4463   static inline ScopeInfo* cast(Object* object);
4464
4465   // Return the type of this scope.
4466   ScopeType scope_type();
4467
4468   // Does this scope call eval?
4469   bool CallsEval();
4470
4471   // Return the strict mode of this scope.
4472   StrictMode strict_mode();
4473
4474   // Does this scope make a sloppy eval call?
4475   bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4476
4477   // Return the total number of locals allocated on the stack and in the
4478   // context. This includes the parameters that are allocated in the context.
4479   int LocalCount();
4480
4481   // Return the number of stack slots for code. This number consists of two
4482   // parts:
4483   //  1. One stack slot per stack allocated local.
4484   //  2. One stack slot for the function name if it is stack allocated.
4485   int StackSlotCount();
4486
4487   // Return the number of context slots for code if a context is allocated. This
4488   // number consists of three parts:
4489   //  1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4490   //  2. One context slot per context allocated local.
4491   //  3. One context slot for the function name if it is context allocated.
4492   // Parameters allocated in the context count as context allocated locals. If
4493   // no contexts are allocated for this scope ContextLength returns 0.
4494   int ContextLength();
4495
4496   // Is this scope the scope of a named function expression?
4497   bool HasFunctionName();
4498
4499   // Return if this has context allocated locals.
4500   bool HasHeapAllocatedLocals();
4501
4502   // Return if contexts are allocated for this scope.
4503   bool HasContext();
4504
4505   // Return the function_name if present.
4506   String* FunctionName();
4507
4508   // Return the name of the given parameter.
4509   String* ParameterName(int var);
4510
4511   // Return the name of the given local.
4512   String* LocalName(int var);
4513
4514   // Return the name of the given stack local.
4515   String* StackLocalName(int var);
4516
4517   // Return the name of the given context local.
4518   String* ContextLocalName(int var);
4519
4520   // Return the mode of the given context local.
4521   VariableMode ContextLocalMode(int var);
4522
4523   // Return the initialization flag of the given context local.
4524   InitializationFlag ContextLocalInitFlag(int var);
4525
4526   // Lookup support for serialized scope info. Returns the
4527   // the stack slot index for a given slot name if the slot is
4528   // present; otherwise returns a value < 0. The name must be an internalized
4529   // string.
4530   int StackSlotIndex(String* name);
4531
4532   // Lookup support for serialized scope info. Returns the
4533   // context slot index for a given slot name if the slot is present; otherwise
4534   // returns a value < 0. The name must be an internalized string.
4535   // If the slot is present and mode != NULL, sets *mode to the corresponding
4536   // mode for that variable.
4537   int ContextSlotIndex(String* name,
4538                        VariableMode* mode,
4539                        InitializationFlag* init_flag);
4540
4541   // Lookup support for serialized scope info. Returns the
4542   // parameter index for a given parameter name if the parameter is present;
4543   // otherwise returns a value < 0. The name must be an internalized string.
4544   int ParameterIndex(String* name);
4545
4546   // Lookup support for serialized scope info. Returns the function context
4547   // slot index if the function name is present and context-allocated (named
4548   // function expressions, only), otherwise returns a value < 0. The name
4549   // must be an internalized string.
4550   int FunctionContextSlotIndex(String* name, VariableMode* mode);
4551
4552
4553   // Copies all the context locals into an object used to materialize a scope.
4554   static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4555                                              Handle<Context> context,
4556                                              Handle<JSObject> scope_object);
4557
4558
4559   static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4560
4561   // Serializes empty scope info.
4562   static ScopeInfo* Empty(Isolate* isolate);
4563
4564 #ifdef DEBUG
4565   void Print();
4566 #endif
4567
4568   // The layout of the static part of a ScopeInfo is as follows. Each entry is
4569   // numeric and occupies one array slot.
4570   // 1. A set of properties of the scope
4571   // 2. The number of parameters. This only applies to function scopes. For
4572   //    non-function scopes this is 0.
4573   // 3. The number of non-parameter variables allocated on the stack.
4574   // 4. The number of non-parameter and parameter variables allocated in the
4575   //    context.
4576 #define FOR_EACH_NUMERIC_FIELD(V)          \
4577   V(Flags)                                 \
4578   V(ParameterCount)                        \
4579   V(StackLocalCount)                       \
4580   V(ContextLocalCount)
4581
4582 #define FIELD_ACCESSORS(name)                            \
4583   void Set##name(int value) {                            \
4584     set(k##name, Smi::FromInt(value));                   \
4585   }                                                      \
4586   int name() {                                           \
4587     if (length() > 0) {                                  \
4588       return Smi::cast(get(k##name))->value();           \
4589     } else {                                             \
4590       return 0;                                          \
4591     }                                                    \
4592   }
4593   FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4594 #undef FIELD_ACCESSORS
4595
4596  private:
4597   enum {
4598 #define DECL_INDEX(name) k##name,
4599   FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4600 #undef DECL_INDEX
4601 #undef FOR_EACH_NUMERIC_FIELD
4602     kVariablePartIndex
4603   };
4604
4605   // The layout of the variable part of a ScopeInfo is as follows:
4606   // 1. ParameterEntries:
4607   //    This part stores the names of the parameters for function scopes. One
4608   //    slot is used per parameter, so in total this part occupies
4609   //    ParameterCount() slots in the array. For other scopes than function
4610   //    scopes ParameterCount() is 0.
4611   // 2. StackLocalEntries:
4612   //    Contains the names of local variables that are allocated on the stack,
4613   //    in increasing order of the stack slot index. One slot is used per stack
4614   //    local, so in total this part occupies StackLocalCount() slots in the
4615   //    array.
4616   // 3. ContextLocalNameEntries:
4617   //    Contains the names of local variables and parameters that are allocated
4618   //    in the context. They are stored in increasing order of the context slot
4619   //    index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4620   //    context local, so in total this part occupies ContextLocalCount() slots
4621   //    in the array.
4622   // 4. ContextLocalInfoEntries:
4623   //    Contains the variable modes and initialization flags corresponding to
4624   //    the context locals in ContextLocalNameEntries. One slot is used per
4625   //    context local, so in total this part occupies ContextLocalCount()
4626   //    slots in the array.
4627   // 5. FunctionNameEntryIndex:
4628   //    If the scope belongs to a named function expression this part contains
4629   //    information about the function variable. It always occupies two array
4630   //    slots:  a. The name of the function variable.
4631   //            b. The context or stack slot index for the variable.
4632   int ParameterEntriesIndex();
4633   int StackLocalEntriesIndex();
4634   int ContextLocalNameEntriesIndex();
4635   int ContextLocalInfoEntriesIndex();
4636   int FunctionNameEntryIndex();
4637
4638   // Location of the function variable for named function expressions.
4639   enum FunctionVariableInfo {
4640     NONE,     // No function name present.
4641     STACK,    // Function
4642     CONTEXT,
4643     UNUSED
4644   };
4645
4646   // Properties of scopes.
4647   class ScopeTypeField:        public BitField<ScopeType,            0, 3> {};
4648   class CallsEvalField:        public BitField<bool,                 3, 1> {};
4649   class StrictModeField:       public BitField<StrictMode,           4, 1> {};
4650   class FunctionVariableField: public BitField<FunctionVariableInfo, 5, 2> {};
4651   class FunctionVariableMode:  public BitField<VariableMode,         7, 3> {};
4652
4653   // BitFields representing the encoded information for context locals in the
4654   // ContextLocalInfoEntries part.
4655   class ContextLocalMode:      public BitField<VariableMode,         0, 3> {};
4656   class ContextLocalInitFlag:  public BitField<InitializationFlag,   3, 1> {};
4657 };
4658
4659
4660 // The cache for maps used by normalized (dictionary mode) objects.
4661 // Such maps do not have property descriptors, so a typical program
4662 // needs very limited number of distinct normalized maps.
4663 class NormalizedMapCache: public FixedArray {
4664  public:
4665   static const int kEntries = 64;
4666
4667   static Handle<Map> Get(Handle<NormalizedMapCache> cache,
4668                          Handle<JSObject> object,
4669                          PropertyNormalizationMode mode);
4670
4671   void Clear();
4672
4673   // Casting
4674   static inline NormalizedMapCache* cast(Object* obj);
4675
4676   DECLARE_VERIFIER(NormalizedMapCache)
4677 };
4678
4679
4680 // ByteArray represents fixed sized byte arrays.  Used for the relocation info
4681 // that is attached to code objects.
4682 class ByteArray: public FixedArrayBase {
4683  public:
4684   inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4685
4686   // Setter and getter.
4687   inline byte get(int index);
4688   inline void set(int index, byte value);
4689
4690   // Treat contents as an int array.
4691   inline int get_int(int index);
4692
4693   static int SizeFor(int length) {
4694     return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4695   }
4696   // We use byte arrays for free blocks in the heap.  Given a desired size in
4697   // bytes that is a multiple of the word size and big enough to hold a byte
4698   // array, this function returns the number of elements a byte array should
4699   // have.
4700   static int LengthFor(int size_in_bytes) {
4701     ASSERT(IsAligned(size_in_bytes, kPointerSize));
4702     ASSERT(size_in_bytes >= kHeaderSize);
4703     return size_in_bytes - kHeaderSize;
4704   }
4705
4706   // Returns data start address.
4707   inline Address GetDataStartAddress();
4708
4709   // Returns a pointer to the ByteArray object for a given data start address.
4710   static inline ByteArray* FromDataStartAddress(Address address);
4711
4712   // Casting.
4713   static inline ByteArray* cast(Object* obj);
4714
4715   // Dispatched behavior.
4716   inline int ByteArraySize() {
4717     return SizeFor(this->length());
4718   }
4719   DECLARE_PRINTER(ByteArray)
4720   DECLARE_VERIFIER(ByteArray)
4721
4722   // Layout description.
4723   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4724
4725   // Maximal memory consumption for a single ByteArray.
4726   static const int kMaxSize = 512 * MB;
4727   // Maximal length of a single ByteArray.
4728   static const int kMaxLength = kMaxSize - kHeaderSize;
4729
4730  private:
4731   DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4732 };
4733
4734
4735 // FreeSpace represents fixed sized areas of the heap that are not currently in
4736 // use.  Used by the heap and GC.
4737 class FreeSpace: public HeapObject {
4738  public:
4739   // [size]: size of the free space including the header.
4740   inline int size();
4741   inline void set_size(int value);
4742
4743   inline int Size() { return size(); }
4744
4745   // Casting.
4746   static inline FreeSpace* cast(Object* obj);
4747
4748   // Dispatched behavior.
4749   DECLARE_PRINTER(FreeSpace)
4750   DECLARE_VERIFIER(FreeSpace)
4751
4752   // Layout description.
4753   // Size is smi tagged when it is stored.
4754   static const int kSizeOffset = HeapObject::kHeaderSize;
4755   static const int kHeaderSize = kSizeOffset + kPointerSize;
4756
4757   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4758
4759  private:
4760   DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4761 };
4762
4763
4764 // V has parameters (Type, type, TYPE, C type, element_size)
4765 #define BUILTIN_TYPED_ARRAY(V) \
4766   V(Uint8, uint8, UINT8, uint8_t, 1)                                           \
4767   V(Int8, int8, INT8, int8_t, 1)                                               \
4768   V(Uint16, uint16, UINT16, uint16_t, 2)                                       \
4769   V(Int16, int16, INT16, int16_t, 2)                                           \
4770   V(Uint32, uint32, UINT32, uint32_t, 4)                                       \
4771   V(Int32, int32, INT32, int32_t, 4)                                           \
4772   V(Float32, float32, FLOAT32, float, 4)                                       \
4773   V(Float64, float64, FLOAT64, double, 8)                                      \
4774   V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4775
4776
4777 #define SIMD128_TYPED_ARRAY(V) \
4778   V(Float32x4, float32x4, FLOAT32x4, v8::internal::float32x4_value_t, 16)      \
4779   V(Int32x4, int32x4, INT32x4, v8::internal::int32x4_value_t, 16)
4780
4781
4782 #define TYPED_ARRAYS(V) \
4783   BUILTIN_TYPED_ARRAY(V) \
4784   SIMD128_TYPED_ARRAY(V)
4785
4786
4787 // An ExternalArray represents a fixed-size array of primitive values
4788 // which live outside the JavaScript heap. Its subclasses are used to
4789 // implement the CanvasArray types being defined in the WebGL
4790 // specification. As of this writing the first public draft is not yet
4791 // available, but Khronos members can access the draft at:
4792 //   https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4793 //
4794 // The semantics of these arrays differ from CanvasPixelArray.
4795 // Out-of-range values passed to the setter are converted via a C
4796 // cast, not clamping. Out-of-range indices cause exceptions to be
4797 // raised rather than being silently ignored.
4798 class ExternalArray: public FixedArrayBase {
4799  public:
4800   inline bool is_the_hole(int index) { return false; }
4801
4802   // [external_pointer]: The pointer to the external memory area backing this
4803   // external array.
4804   DECL_ACCESSORS(external_pointer, void)  // Pointer to the data store.
4805
4806   // Casting.
4807   static inline ExternalArray* cast(Object* obj);
4808
4809   // Maximal acceptable length for an external array.
4810   static const int kMaxLength = 0x3fffffff;
4811
4812   // ExternalArray headers are not quadword aligned.
4813   static const int kExternalPointerOffset =
4814       POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4815   static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4816   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4817
4818  private:
4819   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4820 };
4821
4822
4823 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4824 // semantics used for implementing the CanvasPixelArray object. Please see the
4825 // specification at:
4826
4827 // http://www.whatwg.org/specs/web-apps/current-work/
4828 //                      multipage/the-canvas-element.html#canvaspixelarray
4829 // In particular, write access clamps the value written to 0 or 255 if the
4830 // value written is outside this range.
4831 class ExternalUint8ClampedArray: public ExternalArray {
4832  public:
4833   inline uint8_t* external_uint8_clamped_pointer();
4834
4835   // Setter and getter.
4836   inline uint8_t get_scalar(int index);
4837   MUST_USE_RESULT inline MaybeObject* get(int index);
4838   inline void set(int index, uint8_t value);
4839
4840   // This accessor applies the correct conversion from Smi, HeapNumber and
4841   // undefined and clamps the converted value between 0 and 255.
4842   Object* SetValue(uint32_t index, Object* value);
4843
4844   static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4845                                  uint32_t index,
4846                                  Handle<Object> value);
4847
4848   // Casting.
4849   static inline ExternalUint8ClampedArray* cast(Object* obj);
4850
4851   // Dispatched behavior.
4852   DECLARE_PRINTER(ExternalUint8ClampedArray)
4853   DECLARE_VERIFIER(ExternalUint8ClampedArray)
4854
4855  private:
4856   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4857 };
4858
4859
4860 class ExternalInt8Array: public ExternalArray {
4861  public:
4862   // Setter and getter.
4863   inline int8_t get_scalar(int index);
4864   MUST_USE_RESULT inline MaybeObject* get(int index);
4865   inline void set(int index, int8_t value);
4866
4867   static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4868                                  uint32_t index,
4869                                  Handle<Object> value);
4870
4871   // This accessor applies the correct conversion from Smi, HeapNumber
4872   // and undefined.
4873   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4874
4875   // Casting.
4876   static inline ExternalInt8Array* cast(Object* obj);
4877
4878   // Dispatched behavior.
4879   DECLARE_PRINTER(ExternalInt8Array)
4880   DECLARE_VERIFIER(ExternalInt8Array)
4881
4882  private:
4883   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4884 };
4885
4886
4887 class ExternalUint8Array: public ExternalArray {
4888  public:
4889   // Setter and getter.
4890   inline uint8_t get_scalar(int index);
4891   MUST_USE_RESULT inline MaybeObject* get(int index);
4892   inline void set(int index, uint8_t value);
4893
4894   static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4895                                  uint32_t index,
4896                                  Handle<Object> value);
4897
4898   // This accessor applies the correct conversion from Smi, HeapNumber
4899   // and undefined.
4900   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4901
4902   // Casting.
4903   static inline ExternalUint8Array* cast(Object* obj);
4904
4905   // Dispatched behavior.
4906   DECLARE_PRINTER(ExternalUint8Array)
4907   DECLARE_VERIFIER(ExternalUint8Array)
4908
4909  private:
4910   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4911 };
4912
4913
4914 class ExternalInt16Array: public ExternalArray {
4915  public:
4916   // Setter and getter.
4917   inline int16_t get_scalar(int index);
4918   MUST_USE_RESULT inline MaybeObject* get(int index);
4919   inline void set(int index, int16_t value);
4920
4921   static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4922                                  uint32_t index,
4923                                  Handle<Object> value);
4924
4925   // This accessor applies the correct conversion from Smi, HeapNumber
4926   // and undefined.
4927   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4928
4929   // Casting.
4930   static inline ExternalInt16Array* cast(Object* obj);
4931
4932   // Dispatched behavior.
4933   DECLARE_PRINTER(ExternalInt16Array)
4934   DECLARE_VERIFIER(ExternalInt16Array)
4935
4936  private:
4937   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4938 };
4939
4940
4941 class ExternalUint16Array: public ExternalArray {
4942  public:
4943   // Setter and getter.
4944   inline uint16_t get_scalar(int index);
4945   MUST_USE_RESULT inline MaybeObject* get(int index);
4946   inline void set(int index, uint16_t value);
4947
4948   static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4949                                  uint32_t index,
4950                                  Handle<Object> value);
4951
4952   // This accessor applies the correct conversion from Smi, HeapNumber
4953   // and undefined.
4954   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4955
4956   // Casting.
4957   static inline ExternalUint16Array* cast(Object* obj);
4958
4959   // Dispatched behavior.
4960   DECLARE_PRINTER(ExternalUint16Array)
4961   DECLARE_VERIFIER(ExternalUint16Array)
4962
4963  private:
4964   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4965 };
4966
4967
4968 class ExternalInt32Array: public ExternalArray {
4969  public:
4970   // Setter and getter.
4971   inline int32_t get_scalar(int index);
4972   MUST_USE_RESULT inline MaybeObject* get(int index);
4973   inline void set(int index, int32_t value);
4974
4975   static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4976                                  uint32_t index,
4977                                  Handle<Object> value);
4978
4979   // This accessor applies the correct conversion from Smi, HeapNumber
4980   // and undefined.
4981   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
4982
4983   // Casting.
4984   static inline ExternalInt32Array* cast(Object* obj);
4985
4986   // Dispatched behavior.
4987   DECLARE_PRINTER(ExternalInt32Array)
4988   DECLARE_VERIFIER(ExternalInt32Array)
4989
4990  private:
4991   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4992 };
4993
4994
4995 class ExternalUint32Array: public ExternalArray {
4996  public:
4997   // Setter and getter.
4998   inline uint32_t get_scalar(int index);
4999   MUST_USE_RESULT inline MaybeObject* get(int index);
5000   inline void set(int index, uint32_t value);
5001
5002   static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
5003                                  uint32_t index,
5004                                  Handle<Object> value);
5005
5006   // This accessor applies the correct conversion from Smi, HeapNumber
5007   // and undefined.
5008   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5009
5010   // Casting.
5011   static inline ExternalUint32Array* cast(Object* obj);
5012
5013   // Dispatched behavior.
5014   DECLARE_PRINTER(ExternalUint32Array)
5015   DECLARE_VERIFIER(ExternalUint32Array)
5016
5017  private:
5018   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
5019 };
5020
5021
5022 class ExternalFloat32Array: public ExternalArray {
5023  public:
5024   // Setter and getter.
5025   inline float get_scalar(int index);
5026   MUST_USE_RESULT inline MaybeObject* get(int index);
5027   inline void set(int index, float value);
5028
5029   static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
5030                                  uint32_t index,
5031                                  Handle<Object> value);
5032
5033   // This accessor applies the correct conversion from Smi, HeapNumber
5034   // and undefined.
5035   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5036
5037   // Casting.
5038   static inline ExternalFloat32Array* cast(Object* obj);
5039
5040   // Dispatched behavior.
5041   DECLARE_PRINTER(ExternalFloat32Array)
5042   DECLARE_VERIFIER(ExternalFloat32Array)
5043
5044  private:
5045   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
5046 };
5047
5048
5049 class ExternalFloat32x4Array: public ExternalArray {
5050  public:
5051   // Setter and getter.
5052   inline float32x4_value_t get_scalar(int index);
5053   MUST_USE_RESULT inline MaybeObject* get(int index);
5054   inline void set(int index, const float32x4_value_t& value);
5055
5056   static Handle<Object> SetValue(Handle<ExternalFloat32x4Array> array,
5057                                  uint32_t index,
5058                                  Handle<Object> value);
5059
5060   // This accessor applies the correct conversion from Smi, HeapNumber
5061   // and undefined.
5062   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5063
5064   // Casting.
5065   static inline ExternalFloat32x4Array* cast(Object* obj);
5066
5067   // Dispatched behavior.
5068   DECLARE_PRINTER(ExternalFloat32x4Array)
5069   DECLARE_VERIFIER(ExternalFloat32x4Array)
5070
5071  private:
5072   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32x4Array);
5073 };
5074
5075
5076 class ExternalInt32x4Array: public ExternalArray {
5077  public:
5078   // Setter and getter.
5079   inline int32x4_value_t get_scalar(int index);
5080   MUST_USE_RESULT inline MaybeObject* get(int index);
5081   inline void set(int index, const int32x4_value_t& value);
5082
5083   static Handle<Object> SetValue(Handle<ExternalInt32x4Array> array,
5084                                  uint32_t index,
5085                                  Handle<Object> value);
5086   // This accessor applies the correct conversion from Smi, HeapNumber
5087   // and undefined.
5088   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5089
5090   // Casting.
5091   static inline ExternalInt32x4Array* cast(Object* obj);
5092
5093   // Dispatched behavior.
5094   DECLARE_PRINTER(ExternalInt32x4Array)
5095   DECLARE_VERIFIER(ExternalInt32x4Array)
5096
5097  private:
5098   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32x4Array);
5099 };
5100
5101
5102 class ExternalFloat64Array: public ExternalArray {
5103  public:
5104   // Setter and getter.
5105   inline double get_scalar(int index);
5106   MUST_USE_RESULT inline MaybeObject* get(int index);
5107   inline void set(int index, double value);
5108
5109   static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
5110                                  uint32_t index,
5111                                  Handle<Object> value);
5112
5113   // This accessor applies the correct conversion from Smi, HeapNumber
5114   // and undefined.
5115   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5116
5117   // Casting.
5118   static inline ExternalFloat64Array* cast(Object* obj);
5119
5120   // Dispatched behavior.
5121   DECLARE_PRINTER(ExternalFloat64Array)
5122   DECLARE_VERIFIER(ExternalFloat64Array)
5123
5124  private:
5125   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
5126 };
5127
5128
5129 class FixedTypedArrayBase: public FixedArrayBase {
5130  public:
5131   // Casting:
5132   static inline FixedTypedArrayBase* cast(Object* obj);
5133
5134   static const int kDataOffset = kHeaderSize;
5135
5136   inline int size();
5137
5138   // Use with care: returns raw pointer into heap.
5139   inline void* DataPtr();
5140
5141   inline int DataSize();
5142
5143  private:
5144   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
5145 };
5146
5147
5148 template <class Traits>
5149 class FixedTypedArray: public FixedTypedArrayBase {
5150  public:
5151   typedef typename Traits::ElementType ElementType;
5152   static const InstanceType kInstanceType = Traits::kInstanceType;
5153
5154   // Casting:
5155   static inline FixedTypedArray<Traits>* cast(Object* obj);
5156
5157   static inline int ElementOffset(int index) {
5158     return kDataOffset + index * sizeof(ElementType);
5159   }
5160
5161   static inline int SizeFor(int length) {
5162     return ElementOffset(length);
5163   }
5164
5165   inline ElementType get_scalar(int index);
5166   MUST_USE_RESULT inline MaybeObject* get(int index);
5167   inline void set(int index, ElementType value);
5168
5169   static inline ElementType from_int(int value);
5170   static inline ElementType from_double(double value);
5171
5172   // This accessor applies the correct conversion from Smi, HeapNumber
5173   // and undefined.
5174   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
5175
5176   static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
5177                                  uint32_t index,
5178                                  Handle<Object> value);
5179
5180   DECLARE_PRINTER(FixedTypedArray)
5181   DECLARE_VERIFIER(FixedTypedArray)
5182
5183  private:
5184   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
5185 };
5186
5187 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size)         \
5188   class Type##ArrayTraits {                                                   \
5189     public:                                                                   \
5190       typedef elementType ElementType;                                        \
5191       static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE;    \
5192       static const char* Designator() { return #type " array"; }              \
5193       static inline MaybeObject* ToObject(Heap* heap, elementType scalar);    \
5194       static inline elementType defaultValue();                               \
5195   };                                                                          \
5196                                                                               \
5197   typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
5198
5199 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
5200
5201 #undef FIXED_TYPED_ARRAY_TRAITS
5202
5203 // DeoptimizationInputData is a fixed array used to hold the deoptimization
5204 // data for code generated by the Hydrogen/Lithium compiler.  It also
5205 // contains information about functions that were inlined.  If N different
5206 // functions were inlined then first N elements of the literal array will
5207 // contain these functions.
5208 //
5209 // It can be empty.
5210 class DeoptimizationInputData: public FixedArray {
5211  public:
5212   // Layout description.  Indices in the array.
5213   static const int kTranslationByteArrayIndex = 0;
5214   static const int kInlinedFunctionCountIndex = 1;
5215   static const int kLiteralArrayIndex = 2;
5216   static const int kOsrAstIdIndex = 3;
5217   static const int kOsrPcOffsetIndex = 4;
5218   static const int kOptimizationIdIndex = 5;
5219   static const int kSharedFunctionInfoIndex = 6;
5220   static const int kFirstDeoptEntryIndex = 7;
5221
5222   // Offsets of deopt entry elements relative to the start of the entry.
5223   static const int kAstIdRawOffset = 0;
5224   static const int kTranslationIndexOffset = 1;
5225   static const int kArgumentsStackHeightOffset = 2;
5226   static const int kPcOffset = 3;
5227   static const int kDeoptEntrySize = 4;
5228
5229   // Simple element accessors.
5230 #define DEFINE_ELEMENT_ACCESSORS(name, type)      \
5231   type* name() {                                  \
5232     return type::cast(get(k##name##Index));       \
5233   }                                               \
5234   void Set##name(type* value) {                   \
5235     set(k##name##Index, value);                   \
5236   }
5237
5238   DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
5239   DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
5240   DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
5241   DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
5242   DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
5243   DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
5244   DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
5245
5246 #undef DEFINE_ELEMENT_ACCESSORS
5247
5248   // Accessors for elements of the ith deoptimization entry.
5249 #define DEFINE_ENTRY_ACCESSORS(name, type)                       \
5250   type* name(int i) {                                            \
5251     return type::cast(get(IndexForEntry(i) + k##name##Offset));  \
5252   }                                                              \
5253   void Set##name(int i, type* value) {                           \
5254     set(IndexForEntry(i) + k##name##Offset, value);              \
5255   }
5256
5257   DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
5258   DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
5259   DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
5260   DEFINE_ENTRY_ACCESSORS(Pc, Smi)
5261
5262 #undef DEFINE_ENTRY_ACCESSORS
5263
5264   BailoutId AstId(int i) {
5265     return BailoutId(AstIdRaw(i)->value());
5266   }
5267
5268   void SetAstId(int i, BailoutId value) {
5269     SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
5270   }
5271
5272   int DeoptCount() {
5273     return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
5274   }
5275
5276   // Allocates a DeoptimizationInputData.
5277   MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5278                                                int deopt_entry_count,
5279                                                PretenureFlag pretenure);
5280
5281   // Casting.
5282   static inline DeoptimizationInputData* cast(Object* obj);
5283
5284 #ifdef ENABLE_DISASSEMBLER
5285   void DeoptimizationInputDataPrint(FILE* out);
5286 #endif
5287
5288  private:
5289   static int IndexForEntry(int i) {
5290     return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
5291   }
5292
5293   static int LengthFor(int entry_count) {
5294     return IndexForEntry(entry_count);
5295   }
5296 };
5297
5298
5299 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
5300 // data for code generated by the full compiler.
5301 // The format of the these objects is
5302 //   [i * 2]: Ast ID for ith deoptimization.
5303 //   [i * 2 + 1]: PC and state of ith deoptimization
5304 class DeoptimizationOutputData: public FixedArray {
5305  public:
5306   int DeoptPoints() { return length() / 2; }
5307
5308   BailoutId AstId(int index) {
5309     return BailoutId(Smi::cast(get(index * 2))->value());
5310   }
5311
5312   void SetAstId(int index, BailoutId id) {
5313     set(index * 2, Smi::FromInt(id.ToInt()));
5314   }
5315
5316   Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
5317   void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
5318
5319   static int LengthOfFixedArray(int deopt_points) {
5320     return deopt_points * 2;
5321   }
5322
5323   // Allocates a DeoptimizationOutputData.
5324   MUST_USE_RESULT static MaybeObject* Allocate(Isolate* isolate,
5325                                                int number_of_deopt_points,
5326                                                PretenureFlag pretenure);
5327
5328   // Casting.
5329   static inline DeoptimizationOutputData* cast(Object* obj);
5330
5331 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
5332   void DeoptimizationOutputDataPrint(FILE* out);
5333 #endif
5334 };
5335
5336
5337 // Forward declaration.
5338 class Cell;
5339 class PropertyCell;
5340 class SafepointEntry;
5341 class TypeFeedbackInfo;
5342
5343 // Code describes objects with on-the-fly generated machine code.
5344 class Code: public HeapObject {
5345  public:
5346   // Opaque data type for encapsulating code flags like kind, inline
5347   // cache state, and arguments count.
5348   typedef uint32_t Flags;
5349
5350 #define NON_IC_KIND_LIST(V) \
5351   V(FUNCTION)               \
5352   V(OPTIMIZED_FUNCTION)     \
5353   V(STUB)                   \
5354   V(HANDLER)                \
5355   V(BUILTIN)                \
5356   V(REGEXP)
5357
5358 #define IC_KIND_LIST(V) \
5359   V(LOAD_IC)            \
5360   V(KEYED_LOAD_IC)      \
5361   V(STORE_IC)           \
5362   V(KEYED_STORE_IC)     \
5363   V(BINARY_OP_IC)       \
5364   V(COMPARE_IC)         \
5365   V(COMPARE_NIL_IC)     \
5366   V(TO_BOOLEAN_IC)
5367
5368 #define CODE_KIND_LIST(V) \
5369   NON_IC_KIND_LIST(V)     \
5370   IC_KIND_LIST(V)
5371
5372   enum Kind {
5373 #define DEFINE_CODE_KIND_ENUM(name) name,
5374     CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5375 #undef DEFINE_CODE_KIND_ENUM
5376     NUMBER_OF_KINDS
5377   };
5378
5379   // No more than 16 kinds. The value is currently encoded in four bits in
5380   // Flags.
5381   STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5382
5383   static const char* Kind2String(Kind kind);
5384
5385   // Types of stubs.
5386   enum StubType {
5387     NORMAL,
5388     FAST
5389   };
5390
5391   static const int kPrologueOffsetNotSet = -1;
5392
5393 #ifdef ENABLE_DISASSEMBLER
5394   // Printing
5395   static const char* ICState2String(InlineCacheState state);
5396   static const char* StubType2String(StubType type);
5397   static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
5398   void Disassemble(const char* name, FILE* out = stdout);
5399 #endif  // ENABLE_DISASSEMBLER
5400
5401   // [instruction_size]: Size of the native instructions
5402   inline int instruction_size();
5403   inline void set_instruction_size(int value);
5404
5405   // [relocation_info]: Code relocation information
5406   DECL_ACCESSORS(relocation_info, ByteArray)
5407   void InvalidateRelocation();
5408   void InvalidateEmbeddedObjects();
5409
5410   // [handler_table]: Fixed array containing offsets of exception handlers.
5411   DECL_ACCESSORS(handler_table, FixedArray)
5412
5413   // [deoptimization_data]: Array containing data for deopt.
5414   DECL_ACCESSORS(deoptimization_data, FixedArray)
5415
5416   // [raw_type_feedback_info]: This field stores various things, depending on
5417   // the kind of the code object.
5418   //   FUNCTION           => type feedback information.
5419   //   STUB               => various things, e.g. a SMI
5420   DECL_ACCESSORS(raw_type_feedback_info, Object)
5421   inline Object* type_feedback_info();
5422   inline void set_type_feedback_info(
5423       Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5424   inline int stub_info();
5425   inline void set_stub_info(int info);
5426
5427   // [next_code_link]: Link for lists of optimized or deoptimized code.
5428   // Note that storage for this field is overlapped with typefeedback_info.
5429   DECL_ACCESSORS(next_code_link, Object)
5430
5431   // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5432   // field does not have to be traced during garbage collection since
5433   // it is only used by the garbage collector itself.
5434   DECL_ACCESSORS(gc_metadata, Object)
5435
5436   // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5437   // at the moment when this object was created.
5438   inline void set_ic_age(int count);
5439   inline int ic_age();
5440
5441   // [prologue_offset]: Offset of the function prologue, used for aging
5442   // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5443   inline int prologue_offset();
5444   inline void set_prologue_offset(int offset);
5445
5446   // Unchecked accessors to be used during GC.
5447   inline ByteArray* unchecked_relocation_info();
5448
5449   inline int relocation_size();
5450
5451   // [flags]: Various code flags.
5452   inline Flags flags();
5453   inline void set_flags(Flags flags);
5454
5455   // [flags]: Access to specific code flags.
5456   inline Kind kind();
5457   inline InlineCacheState ic_state();  // Only valid for IC stubs.
5458   inline ExtraICState extra_ic_state();  // Only valid for IC stubs.
5459
5460   inline StubType type();  // Only valid for monomorphic IC stubs.
5461
5462   // Testers for IC stub kinds.
5463   inline bool is_inline_cache_stub();
5464   inline bool is_debug_stub();
5465   inline bool is_handler() { return kind() == HANDLER; }
5466   inline bool is_load_stub() { return kind() == LOAD_IC; }
5467   inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5468   inline bool is_store_stub() { return kind() == STORE_IC; }
5469   inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5470   inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5471   inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5472   inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5473   inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5474   inline bool is_keyed_stub();
5475   inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5476
5477   inline void set_raw_kind_specific_flags1(int value);
5478   inline void set_raw_kind_specific_flags2(int value);
5479
5480   // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
5481   inline int major_key();
5482   inline void set_major_key(int value);
5483   inline bool has_major_key();
5484
5485   // For kind STUB or ICs, tells whether or not a code object was generated by
5486   // the optimizing compiler (but it may not be an optimized function).
5487   bool is_crankshafted();
5488   inline void set_is_crankshafted(bool value);
5489
5490   // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5491   inline bool optimizable();
5492   inline void set_optimizable(bool value);
5493
5494   // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5495   // deoptimization support.
5496   inline bool has_deoptimization_support();
5497   inline void set_has_deoptimization_support(bool value);
5498
5499   // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5500   // been compiled with debug break slots.
5501   inline bool has_debug_break_slots();
5502   inline void set_has_debug_break_slots(bool value);
5503
5504   // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5505   // been compiled with IsOptimizing set to true.
5506   inline bool is_compiled_optimizable();
5507   inline void set_compiled_optimizable(bool value);
5508
5509   // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5510   // how long the function has been marked for OSR and therefore which
5511   // level of loop nesting we are willing to do on-stack replacement
5512   // for.
5513   inline void set_allow_osr_at_loop_nesting_level(int level);
5514   inline int allow_osr_at_loop_nesting_level();
5515
5516   // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5517   // the code object was seen on the stack with no IC patching going on.
5518   inline int profiler_ticks();
5519   inline void set_profiler_ticks(int ticks);
5520
5521   // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5522   // reserved in the code prologue.
5523   inline unsigned stack_slots();
5524   inline void set_stack_slots(unsigned slots);
5525
5526   // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
5527   // the instruction stream where the safepoint table starts.
5528   inline unsigned safepoint_table_offset();
5529   inline void set_safepoint_table_offset(unsigned offset);
5530
5531   // [back_edge_table_start]: For kind FUNCTION, the offset in the
5532   // instruction stream where the back edge table starts.
5533   inline unsigned back_edge_table_offset();
5534   inline void set_back_edge_table_offset(unsigned offset);
5535
5536   inline bool back_edges_patched_for_osr();
5537   inline void set_back_edges_patched_for_osr(bool value);
5538
5539   // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5540   inline byte to_boolean_state();
5541
5542   // [has_function_cache]: For kind STUB tells whether there is a function
5543   // cache is passed to the stub.
5544   inline bool has_function_cache();
5545   inline void set_has_function_cache(bool flag);
5546
5547
5548   // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5549   // the code is going to be deoptimized because of dead embedded maps.
5550   inline bool marked_for_deoptimization();
5551   inline void set_marked_for_deoptimization(bool flag);
5552
5553   // [constant_pool]: The constant pool for this function.
5554   inline ConstantPoolArray* constant_pool();
5555   inline void set_constant_pool(Object* constant_pool);
5556
5557   // Get the safepoint entry for the given pc.
5558   SafepointEntry GetSafepointEntry(Address pc);
5559
5560   // Find an object in a stub with a specified map
5561   Object* FindNthObject(int n, Map* match_map);
5562
5563   // Find the first allocation site in an IC stub.
5564   AllocationSite* FindFirstAllocationSite();
5565
5566   // Find the first map in an IC stub.
5567   Map* FindFirstMap();
5568   void FindAllMaps(MapHandleList* maps);
5569   void FindAllTypes(TypeHandleList* types);
5570
5571   // Find the first handler in an IC stub.
5572   Code* FindFirstHandler();
5573
5574   // Find |length| handlers and put them into |code_list|. Returns false if not
5575   // enough handlers can be found.
5576   bool FindHandlers(CodeHandleList* code_list, int length = -1);
5577
5578   // Find the first name in an IC stub.
5579   Name* FindFirstName();
5580
5581   class FindAndReplacePattern;
5582   // For each (map-to-find, object-to-replace) pair in the pattern, this
5583   // function replaces the corresponding placeholder in the code with the
5584   // object-to-replace. The function assumes that pairs in the pattern come in
5585   // the same order as the placeholders in the code.
5586   void FindAndReplace(const FindAndReplacePattern& pattern);
5587
5588   // The entire code object including its header is copied verbatim to the
5589   // snapshot so that it can be written in one, fast, memcpy during
5590   // deserialization. The deserializer will overwrite some pointers, rather
5591   // like a runtime linker, but the random allocation addresses used in the
5592   // mksnapshot process would still be present in the unlinked snapshot data,
5593   // which would make snapshot production non-reproducible. This method wipes
5594   // out the to-be-overwritten header data for reproducible snapshots.
5595   inline void WipeOutHeader();
5596
5597   // Flags operations.
5598   static inline Flags ComputeFlags(
5599       Kind kind,
5600       InlineCacheState ic_state = UNINITIALIZED,
5601       ExtraICState extra_ic_state = kNoExtraICState,
5602       StubType type = NORMAL,
5603       InlineCacheHolderFlag holder = OWN_MAP);
5604
5605   static inline Flags ComputeMonomorphicFlags(
5606       Kind kind,
5607       ExtraICState extra_ic_state = kNoExtraICState,
5608       InlineCacheHolderFlag holder = OWN_MAP,
5609       StubType type = NORMAL);
5610
5611   static inline Flags ComputeHandlerFlags(
5612       Kind handler_kind,
5613       StubType type = NORMAL,
5614       InlineCacheHolderFlag holder = OWN_MAP);
5615
5616   static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5617   static inline StubType ExtractTypeFromFlags(Flags flags);
5618   static inline Kind ExtractKindFromFlags(Flags flags);
5619   static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5620   static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5621
5622   static inline Flags RemoveTypeFromFlags(Flags flags);
5623
5624   // Convert a target address into a code object.
5625   static inline Code* GetCodeFromTargetAddress(Address address);
5626
5627   // Convert an entry address into an object.
5628   static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5629
5630   // Returns the address of the first instruction.
5631   inline byte* instruction_start();
5632
5633   // Returns the address right after the last instruction.
5634   inline byte* instruction_end();
5635
5636   // Returns the size of the instructions, padding, and relocation information.
5637   inline int body_size();
5638
5639   // Returns the address of the first relocation info (read backwards!).
5640   inline byte* relocation_start();
5641
5642   // Code entry point.
5643   inline byte* entry();
5644
5645   // Returns true if pc is inside this object's instructions.
5646   inline bool contains(byte* pc);
5647
5648   // Relocate the code by delta bytes. Called to signal that this code
5649   // object has been moved by delta bytes.
5650   void Relocate(intptr_t delta);
5651
5652   // Migrate code described by desc.
5653   void CopyFrom(const CodeDesc& desc);
5654
5655   // Returns the object size for a given body (used for allocation).
5656   static int SizeFor(int body_size) {
5657     ASSERT_SIZE_TAG_ALIGNED(body_size);
5658     return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5659   }
5660
5661   // Calculate the size of the code object to report for log events. This takes
5662   // the layout of the code object into account.
5663   int ExecutableSize() {
5664     // Check that the assumptions about the layout of the code object holds.
5665     ASSERT_EQ(static_cast<int>(instruction_start() - address()),
5666               Code::kHeaderSize);
5667     return instruction_size() + Code::kHeaderSize;
5668   }
5669
5670   // Locating source position.
5671   int SourcePosition(Address pc);
5672   int SourceStatementPosition(Address pc);
5673
5674   // Casting.
5675   static inline Code* cast(Object* obj);
5676
5677   // Dispatched behavior.
5678   int CodeSize() { return SizeFor(body_size()); }
5679   inline void CodeIterateBody(ObjectVisitor* v);
5680
5681   template<typename StaticVisitor>
5682   inline void CodeIterateBody(Heap* heap);
5683
5684   DECLARE_PRINTER(Code)
5685   DECLARE_VERIFIER(Code)
5686
5687   void ClearInlineCaches();
5688   void ClearInlineCaches(Kind kind);
5689
5690   void ClearTypeFeedbackInfo(Heap* heap);
5691
5692   BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5693   uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5694
5695 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5696   enum Age {
5697     kNotExecutedCodeAge = -2,
5698     kExecutedOnceCodeAge = -1,
5699     kNoAgeCodeAge = 0,
5700     CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5701     kAfterLastCodeAge,
5702     kFirstCodeAge = kNotExecutedCodeAge,
5703     kLastCodeAge = kAfterLastCodeAge - 1,
5704     kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5705     kIsOldCodeAge = kSexagenarianCodeAge,
5706     kPreAgedCodeAge = kIsOldCodeAge - 1
5707   };
5708 #undef DECLARE_CODE_AGE_ENUM
5709
5710   // Code aging.  Indicates how many full GCs this code has survived without
5711   // being entered through the prologue.  Used to determine when it is
5712   // relatively safe to flush this code object and replace it with the lazy
5713   // compilation stub.
5714   static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5715   static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5716   void MakeOlder(MarkingParity);
5717   static bool IsYoungSequence(byte* sequence);
5718   bool IsOld();
5719   Age GetAge();
5720   // Gets the raw code age, including psuedo code-age values such as
5721   // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5722   Age GetRawAge();
5723   static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5724     return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5725   }
5726
5727   void PrintDeoptLocation(FILE* out, int bailout_id);
5728   bool CanDeoptAt(Address pc);
5729
5730 #ifdef VERIFY_HEAP
5731   void VerifyEmbeddedObjectsDependency();
5732 #endif
5733
5734   inline bool IsWeakObject(Object* object) {
5735     return is_optimized_code() && IsWeakObjectInOptimizedCode(object);
5736   }
5737
5738   inline bool IsWeakObjectInOptimizedCode(Object* object);
5739
5740   // Max loop nesting marker used to postpose OSR. We don't take loop
5741   // nesting that is deeper than 5 levels into account.
5742   static const int kMaxLoopNestingMarker = 6;
5743
5744   // Layout description.
5745   static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5746   static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5747   static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5748   static const int kDeoptimizationDataOffset =
5749       kHandlerTableOffset + kPointerSize;
5750   static const int kTypeFeedbackInfoOffset =
5751       kDeoptimizationDataOffset + kPointerSize;
5752   static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5753   static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5754   static const int kICAgeOffset =
5755       kGCMetadataOffset + kPointerSize;
5756   static const int kFlagsOffset = kICAgeOffset + kIntSize;
5757   static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5758   static const int kKindSpecificFlags2Offset =
5759       kKindSpecificFlags1Offset + kIntSize;
5760   // Note: We might be able to squeeze this into the flags above.
5761   static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5762   static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5763
5764   static const int kHeaderPaddingStart = kConstantPoolOffset + kIntSize;
5765
5766   // Add padding to align the instruction start following right after
5767   // the Code object header.
5768   static const int kHeaderSize =
5769       (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5770
5771   // Byte offsets within kKindSpecificFlags1Offset.
5772   static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5773
5774   static const int kFullCodeFlags = kOptimizableOffset + 1;
5775   class FullCodeFlagsHasDeoptimizationSupportField:
5776       public BitField<bool, 0, 1> {};  // NOLINT
5777   class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5778   class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5779
5780   static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
5781   static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
5782
5783   // Flags layout.  BitField<type, shift, size>.
5784   class ICStateField: public BitField<InlineCacheState, 0, 3> {};
5785   class TypeField: public BitField<StubType, 3, 1> {};
5786   class CacheHolderField: public BitField<InlineCacheHolderFlag, 5, 1> {};
5787   class KindField: public BitField<Kind, 6, 4> {};
5788   // TODO(bmeurer): Bit 10 is available for free use. :-)
5789   class ExtraICStateField: public BitField<ExtraICState, 11,
5790       PlatformSmiTagging::kSmiValueSize - 11 + 1> {};  // NOLINT
5791
5792   // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5793   static const int kStackSlotsFirstBit = 0;
5794   static const int kStackSlotsBitCount = 24;
5795   static const int kHasFunctionCacheFirstBit =
5796       kStackSlotsFirstBit + kStackSlotsBitCount;
5797   static const int kHasFunctionCacheBitCount = 1;
5798   static const int kMarkedForDeoptimizationFirstBit =
5799       kStackSlotsFirstBit + kStackSlotsBitCount + 1;
5800   static const int kMarkedForDeoptimizationBitCount = 1;
5801
5802   STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5803   STATIC_ASSERT(kHasFunctionCacheFirstBit + kHasFunctionCacheBitCount <= 32);
5804   STATIC_ASSERT(kMarkedForDeoptimizationFirstBit +
5805                 kMarkedForDeoptimizationBitCount <= 32);
5806
5807   class StackSlotsField: public BitField<int,
5808       kStackSlotsFirstBit, kStackSlotsBitCount> {};  // NOLINT
5809   class HasFunctionCacheField: public BitField<bool,
5810       kHasFunctionCacheFirstBit, kHasFunctionCacheBitCount> {};  // NOLINT
5811   class MarkedForDeoptimizationField: public BitField<bool,
5812       kMarkedForDeoptimizationFirstBit,
5813       kMarkedForDeoptimizationBitCount> {};  // NOLINT
5814
5815   // KindSpecificFlags2 layout (ALL)
5816   static const int kIsCrankshaftedBit = 0;
5817   class IsCrankshaftedField: public BitField<bool,
5818       kIsCrankshaftedBit, 1> {};  // NOLINT
5819
5820   // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5821   static const int kStubMajorKeyFirstBit = kIsCrankshaftedBit + 1;
5822   static const int kSafepointTableOffsetFirstBit =
5823       kStubMajorKeyFirstBit + kStubMajorKeyBits;
5824   static const int kSafepointTableOffsetBitCount = 24;
5825
5826   STATIC_ASSERT(kStubMajorKeyFirstBit + kStubMajorKeyBits <= 32);
5827   STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5828                 kSafepointTableOffsetBitCount <= 32);
5829   STATIC_ASSERT(1 + kStubMajorKeyBits +
5830                 kSafepointTableOffsetBitCount <= 32);
5831
5832   class SafepointTableOffsetField: public BitField<int,
5833       kSafepointTableOffsetFirstBit,
5834       kSafepointTableOffsetBitCount> {};  // NOLINT
5835   class StubMajorKeyField: public BitField<int,
5836       kStubMajorKeyFirstBit, kStubMajorKeyBits> {};  // NOLINT
5837
5838   // KindSpecificFlags2 layout (FUNCTION)
5839   class BackEdgeTableOffsetField: public BitField<int,
5840       kIsCrankshaftedBit + 1, 29> {};  // NOLINT
5841   class BackEdgesPatchedForOSRField: public BitField<bool,
5842       kIsCrankshaftedBit + 1 + 29, 1> {};  // NOLINT
5843
5844   static const int kArgumentsBits = 16;
5845   static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5846
5847   // This constant should be encodable in an ARM instruction.
5848   static const int kFlagsNotUsedInLookup =
5849       TypeField::kMask | CacheHolderField::kMask;
5850
5851  private:
5852   friend class RelocIterator;
5853   friend class Deoptimizer;  // For FindCodeAgeSequence.
5854
5855   void ClearInlineCaches(Kind* kind);
5856
5857   // Code aging
5858   byte* FindCodeAgeSequence();
5859   static void GetCodeAgeAndParity(Code* code, Age* age,
5860                                   MarkingParity* parity);
5861   static void GetCodeAgeAndParity(byte* sequence, Age* age,
5862                                   MarkingParity* parity);
5863   static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5864
5865   // Code aging -- platform-specific
5866   static void PatchPlatformCodeAge(Isolate* isolate,
5867                                    byte* sequence, Age age,
5868                                    MarkingParity parity);
5869
5870   DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5871 };
5872
5873
5874 class CompilationInfo;
5875
5876 // This class describes the layout of dependent codes array of a map. The
5877 // array is partitioned into several groups of dependent codes. Each group
5878 // contains codes with the same dependency on the map. The array has the
5879 // following layout for n dependency groups:
5880 //
5881 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5882 // | C1 | C2 | ... | Cn | group 1 |  group 2 | ... | group n | undefined |
5883 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5884 //
5885 // The first n elements are Smis, each of them specifies the number of codes
5886 // in the corresponding group. The subsequent elements contain grouped code
5887 // objects. The suffix of the array can be filled with the undefined value if
5888 // the number of codes is less than the length of the array. The order of the
5889 // code objects within a group is not preserved.
5890 //
5891 // All code indexes used in the class are counted starting from the first
5892 // code object of the first group. In other words, code index 0 corresponds
5893 // to array index n = kCodesStartIndex.
5894
5895 class DependentCode: public FixedArray {
5896  public:
5897   enum DependencyGroup {
5898     // Group of code that weakly embed this map and depend on being
5899     // deoptimized when the map is garbage collected.
5900     kWeaklyEmbeddedGroup,
5901     // Group of code that embed a transition to this map, and depend on being
5902     // deoptimized when the transition is replaced by a new version.
5903     kTransitionGroup,
5904     // Group of code that omit run-time prototype checks for prototypes
5905     // described by this map. The group is deoptimized whenever an object
5906     // described by this map changes shape (and transitions to a new map),
5907     // possibly invalidating the assumptions embedded in the code.
5908     kPrototypeCheckGroup,
5909     // Group of code that depends on elements not being added to objects with
5910     // this map.
5911     kElementsCantBeAddedGroup,
5912     // Group of code that depends on global property values in property cells
5913     // not being changed.
5914     kPropertyCellChangedGroup,
5915     // Group of code that depends on tenuring information in AllocationSites
5916     // not being changed.
5917     kAllocationSiteTenuringChangedGroup,
5918     // Group of code that depends on element transition information in
5919     // AllocationSites not being changed.
5920     kAllocationSiteTransitionChangedGroup,
5921     kGroupCount = kAllocationSiteTransitionChangedGroup + 1
5922   };
5923
5924   // Array for holding the index of the first code object of each group.
5925   // The last element stores the total number of code objects.
5926   class GroupStartIndexes {
5927    public:
5928     explicit GroupStartIndexes(DependentCode* entries);
5929     void Recompute(DependentCode* entries);
5930     int at(int i) { return start_indexes_[i]; }
5931     int number_of_entries() { return start_indexes_[kGroupCount]; }
5932    private:
5933     int start_indexes_[kGroupCount + 1];
5934   };
5935
5936   bool Contains(DependencyGroup group, Code* code);
5937   static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5938                                       DependencyGroup group,
5939                                       Handle<Object> object);
5940   void UpdateToFinishedCode(DependencyGroup group,
5941                             CompilationInfo* info,
5942                             Code* code);
5943   void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5944                              CompilationInfo* info);
5945
5946   void DeoptimizeDependentCodeGroup(Isolate* isolate,
5947                                     DependentCode::DependencyGroup group);
5948
5949   bool MarkCodeForDeoptimization(Isolate* isolate,
5950                                  DependentCode::DependencyGroup group);
5951
5952   // The following low-level accessors should only be used by this class
5953   // and the mark compact collector.
5954   inline int number_of_entries(DependencyGroup group);
5955   inline void set_number_of_entries(DependencyGroup group, int value);
5956   inline bool is_code_at(int i);
5957   inline Code* code_at(int i);
5958   inline CompilationInfo* compilation_info_at(int i);
5959   inline void set_object_at(int i, Object* object);
5960   inline Object** slot_at(int i);
5961   inline Object* object_at(int i);
5962   inline void clear_at(int i);
5963   inline void copy(int from, int to);
5964   static inline DependentCode* cast(Object* object);
5965
5966   static DependentCode* ForObject(Handle<HeapObject> object,
5967                                   DependencyGroup group);
5968
5969  private:
5970   // Make a room at the end of the given group by moving out the first
5971   // code objects of the subsequent groups.
5972   inline void ExtendGroup(DependencyGroup group);
5973   static const int kCodesStartIndex = kGroupCount;
5974 };
5975
5976
5977 // All heap objects have a Map that describes their structure.
5978 //  A Map contains information about:
5979 //  - Size information about the object
5980 //  - How to iterate over an object (for garbage collection)
5981 class Map: public HeapObject {
5982  public:
5983   // Instance size.
5984   // Size in bytes or kVariableSizeSentinel if instances do not have
5985   // a fixed size.
5986   inline int instance_size();
5987   inline void set_instance_size(int value);
5988
5989   // Count of properties allocated in the object.
5990   inline int inobject_properties();
5991   inline void set_inobject_properties(int value);
5992
5993   // Count of property fields pre-allocated in the object when first allocated.
5994   inline int pre_allocated_property_fields();
5995   inline void set_pre_allocated_property_fields(int value);
5996
5997   // Instance type.
5998   inline InstanceType instance_type();
5999   inline void set_instance_type(InstanceType value);
6000
6001   // Tells how many unused property fields are available in the
6002   // instance (only used for JSObject in fast mode).
6003   inline int unused_property_fields();
6004   inline void set_unused_property_fields(int value);
6005
6006   // Bit field.
6007   inline byte bit_field();
6008   inline void set_bit_field(byte value);
6009
6010   // Bit field 2.
6011   inline byte bit_field2();
6012   inline void set_bit_field2(byte value);
6013
6014   // Bit field 3.
6015   inline uint32_t bit_field3();
6016   inline void set_bit_field3(uint32_t bits);
6017
6018   class EnumLengthBits:             public BitField<int,
6019       0, kDescriptorIndexBitCount> {};  // NOLINT
6020   class NumberOfOwnDescriptorsBits: public BitField<int,
6021       kDescriptorIndexBitCount, kDescriptorIndexBitCount> {};  // NOLINT
6022   STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
6023   class IsShared:                   public BitField<bool, 20,  1> {};
6024   class FunctionWithPrototype:      public BitField<bool, 21,  1> {};
6025   class DictionaryMap:              public BitField<bool, 22,  1> {};
6026   class OwnsDescriptors:            public BitField<bool, 23,  1> {};
6027   class HasInstanceCallHandler:     public BitField<bool, 24,  1> {};
6028   class Deprecated:                 public BitField<bool, 25,  1> {};
6029   class IsFrozen:                   public BitField<bool, 26,  1> {};
6030   class IsUnstable:                 public BitField<bool, 27,  1> {};
6031   class IsMigrationTarget:          public BitField<bool, 28,  1> {};
6032
6033   // Tells whether the object in the prototype property will be used
6034   // for instances created from this function.  If the prototype
6035   // property is set to a value that is not a JSObject, the prototype
6036   // property will not be used to create instances of the function.
6037   // See ECMA-262, 13.2.2.
6038   inline void set_non_instance_prototype(bool value);
6039   inline bool has_non_instance_prototype();
6040
6041   // Tells whether function has special prototype property. If not, prototype
6042   // property will not be created when accessed (will return undefined),
6043   // and construction from this function will not be allowed.
6044   inline void set_function_with_prototype(bool value);
6045   inline bool function_with_prototype();
6046
6047   // Tells whether the instance with this map should be ignored by the
6048   // Object.getPrototypeOf() function and the __proto__ accessor.
6049   inline void set_is_hidden_prototype() {
6050     set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
6051   }
6052
6053   inline bool is_hidden_prototype() {
6054     return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
6055   }
6056
6057   // Records and queries whether the instance has a named interceptor.
6058   inline void set_has_named_interceptor() {
6059     set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
6060   }
6061
6062   inline bool has_named_interceptor() {
6063     return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
6064   }
6065
6066   // Records and queries whether the instance has an indexed interceptor.
6067   inline void set_has_indexed_interceptor() {
6068     set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
6069   }
6070
6071   inline bool has_indexed_interceptor() {
6072     return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
6073   }
6074
6075   // Tells whether the instance is undetectable.
6076   // An undetectable object is a special class of JSObject: 'typeof' operator
6077   // returns undefined, ToBoolean returns false. Otherwise it behaves like
6078   // a normal JS object.  It is useful for implementing undetectable
6079   // document.all in Firefox & Safari.
6080   // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
6081   inline void set_is_undetectable() {
6082     set_bit_field(bit_field() | (1 << kIsUndetectable));
6083   }
6084
6085   inline bool is_undetectable() {
6086     return ((1 << kIsUndetectable) & bit_field()) != 0;
6087   }
6088
6089   // Tells whether the instance has a call-as-function handler.
6090   inline void set_is_observed() {
6091     set_bit_field(bit_field() | (1 << kIsObserved));
6092   }
6093
6094   inline bool is_observed() {
6095     return ((1 << kIsObserved) & bit_field()) != 0;
6096   }
6097
6098   inline void set_is_extensible(bool value);
6099   inline bool is_extensible();
6100
6101   inline void set_elements_kind(ElementsKind elements_kind) {
6102     ASSERT(elements_kind < kElementsKindCount);
6103     ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
6104     set_bit_field2((bit_field2() & ~kElementsKindMask) |
6105         (elements_kind << kElementsKindShift));
6106     ASSERT(this->elements_kind() == elements_kind);
6107   }
6108
6109   inline ElementsKind elements_kind() {
6110     return static_cast<ElementsKind>(
6111         (bit_field2() & kElementsKindMask) >> kElementsKindShift);
6112   }
6113
6114   // Tells whether the instance has fast elements that are only Smis.
6115   inline bool has_fast_smi_elements() {
6116     return IsFastSmiElementsKind(elements_kind());
6117   }
6118
6119   // Tells whether the instance has fast elements.
6120   inline bool has_fast_object_elements() {
6121     return IsFastObjectElementsKind(elements_kind());
6122   }
6123
6124   inline bool has_fast_smi_or_object_elements() {
6125     return IsFastSmiOrObjectElementsKind(elements_kind());
6126   }
6127
6128   inline bool has_fast_double_elements() {
6129     return IsFastDoubleElementsKind(elements_kind());
6130   }
6131
6132   inline bool has_fast_elements() {
6133     return IsFastElementsKind(elements_kind());
6134   }
6135
6136   inline bool has_sloppy_arguments_elements() {
6137     return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6138   }
6139
6140   inline bool has_external_array_elements() {
6141     return IsExternalArrayElementsKind(elements_kind());
6142   }
6143
6144   inline bool has_fixed_typed_array_elements() {
6145     return IsFixedTypedArrayElementsKind(elements_kind());
6146   }
6147
6148   inline bool has_dictionary_elements() {
6149     return IsDictionaryElementsKind(elements_kind());
6150   }
6151
6152   inline bool has_slow_elements_kind() {
6153     return elements_kind() == DICTIONARY_ELEMENTS
6154         || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
6155   }
6156
6157   static bool IsValidElementsTransition(ElementsKind from_kind,
6158                                         ElementsKind to_kind);
6159
6160   // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
6161   // map with DICTIONARY_ELEMENTS was found in the prototype chain.
6162   bool DictionaryElementsInPrototypeChainOnly();
6163
6164   inline bool HasTransitionArray();
6165   inline bool HasElementsTransition();
6166   inline Map* elements_transition_map();
6167   MUST_USE_RESULT inline MaybeObject* set_elements_transition_map(
6168       Map* transitioned_map);
6169   inline void SetTransition(int transition_index, Map* target);
6170   inline Map* GetTransition(int transition_index);
6171
6172   static Handle<TransitionArray> AddTransition(Handle<Map> map,
6173                                                Handle<Name> key,
6174                                                Handle<Map> target,
6175                                                SimpleTransitionFlag flag);
6176
6177   MUST_USE_RESULT inline MaybeObject* AddTransition(Name* key,
6178                                                     Map* target,
6179                                                     SimpleTransitionFlag flag);
6180   DECL_ACCESSORS(transitions, TransitionArray)
6181   inline void ClearTransitions(Heap* heap,
6182                                WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6183
6184   void DeprecateTransitionTree();
6185   void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6186
6187   Map* FindRootMap();
6188   Map* FindUpdatedMap(int verbatim, int length, DescriptorArray* descriptors);
6189   Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6190
6191   inline int GetInObjectPropertyOffset(int index);
6192
6193   int NumberOfFields();
6194
6195   bool InstancesNeedRewriting(Map* target,
6196                               int target_number_of_fields,
6197                               int target_inobject,
6198                               int target_unused);
6199   static Handle<Map> GeneralizeAllFieldRepresentations(
6200       Handle<Map> map,
6201       Representation new_representation);
6202   static Handle<Map> GeneralizeRepresentation(
6203       Handle<Map> map,
6204       int modify_index,
6205       Representation new_representation,
6206       StoreMode store_mode);
6207   static Handle<Map> CopyGeneralizeAllRepresentations(
6208       Handle<Map> map,
6209       int modify_index,
6210       StoreMode store_mode,
6211       PropertyAttributes attributes,
6212       const char* reason);
6213
6214   void PrintGeneralization(FILE* file,
6215                            const char* reason,
6216                            int modify_index,
6217                            int split,
6218                            int descriptors,
6219                            bool constant_to_field,
6220                            Representation old_representation,
6221                            Representation new_representation);
6222
6223   // Returns the constructor name (the name (possibly, inferred name) of the
6224   // function that was used to instantiate the object).
6225   String* constructor_name();
6226
6227   // Tells whether the map is attached to SharedFunctionInfo
6228   // (for inobject slack tracking).
6229   inline void set_attached_to_shared_function_info(bool value);
6230
6231   inline bool attached_to_shared_function_info();
6232
6233   // Tells whether the map is shared between objects that may have different
6234   // behavior. If true, the map should never be modified, instead a clone
6235   // should be created and modified.
6236   inline void set_is_shared(bool value);
6237   inline bool is_shared();
6238
6239   // Tells whether the map is used for JSObjects in dictionary mode (ie
6240   // normalized objects, ie objects for which HasFastProperties returns false).
6241   // A map can never be used for both dictionary mode and fast mode JSObjects.
6242   // False by default and for HeapObjects that are not JSObjects.
6243   inline void set_dictionary_map(bool value);
6244   inline bool is_dictionary_map();
6245
6246   // Tells whether the instance needs security checks when accessing its
6247   // properties.
6248   inline void set_is_access_check_needed(bool access_check_needed);
6249   inline bool is_access_check_needed();
6250
6251   // Returns true if map has a non-empty stub code cache.
6252   inline bool has_code_cache();
6253
6254   // [prototype]: implicit prototype object.
6255   DECL_ACCESSORS(prototype, Object)
6256
6257   // [constructor]: points back to the function responsible for this map.
6258   DECL_ACCESSORS(constructor, Object)
6259
6260   // [instance descriptors]: describes the object.
6261   DECL_ACCESSORS(instance_descriptors, DescriptorArray)
6262   inline void InitializeDescriptors(DescriptorArray* descriptors);
6263
6264   // [stub cache]: contains stubs compiled for this map.
6265   DECL_ACCESSORS(code_cache, Object)
6266
6267   // [dependent code]: list of optimized codes that have this map embedded.
6268   DECL_ACCESSORS(dependent_code, DependentCode)
6269
6270   // [back pointer]: points back to the parent map from which a transition
6271   // leads to this map. The field overlaps with prototype transitions and the
6272   // back pointer will be moved into the prototype transitions array if
6273   // required.
6274   inline Object* GetBackPointer();
6275   inline void SetBackPointer(Object* value,
6276                              WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6277   inline void init_back_pointer(Object* undefined);
6278
6279   // [prototype transitions]: cache of prototype transitions.
6280   // Prototype transition is a transition that happens
6281   // when we change object's prototype to a new one.
6282   // Cache format:
6283   //    0: finger - index of the first free cell in the cache
6284   //    1: back pointer that overlaps with prototype transitions field.
6285   //    2 + 2 * i: prototype
6286   //    3 + 2 * i: target map
6287   inline FixedArray* GetPrototypeTransitions();
6288   MUST_USE_RESULT inline MaybeObject* SetPrototypeTransitions(
6289       FixedArray* prototype_transitions);
6290   inline bool HasPrototypeTransitions();
6291
6292   inline HeapObject* UncheckedPrototypeTransitions();
6293   inline TransitionArray* unchecked_transition_array();
6294
6295   static const int kProtoTransitionHeaderSize = 1;
6296   static const int kProtoTransitionNumberOfEntriesOffset = 0;
6297   static const int kProtoTransitionElementsPerEntry = 2;
6298   static const int kProtoTransitionPrototypeOffset = 0;
6299   static const int kProtoTransitionMapOffset = 1;
6300
6301   inline int NumberOfProtoTransitions() {
6302     FixedArray* cache = GetPrototypeTransitions();
6303     if (cache->length() == 0) return 0;
6304     return
6305         Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6306   }
6307
6308   inline void SetNumberOfProtoTransitions(int value) {
6309     FixedArray* cache = GetPrototypeTransitions();
6310     ASSERT(cache->length() != 0);
6311     cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6312   }
6313
6314   // Lookup in the map's instance descriptors and fill out the result
6315   // with the given holder if the name is found. The holder may be
6316   // NULL when this function is used from the compiler.
6317   inline void LookupDescriptor(JSObject* holder,
6318                                Name* name,
6319                                LookupResult* result);
6320
6321   inline void LookupTransition(JSObject* holder,
6322                                Name* name,
6323                                LookupResult* result);
6324
6325   inline PropertyDetails GetLastDescriptorDetails();
6326
6327   // The size of transition arrays are limited so they do not end up in large
6328   // object space. Otherwise ClearNonLiveTransitions would leak memory while
6329   // applying in-place right trimming.
6330   inline bool CanHaveMoreTransitions();
6331
6332   int LastAdded() {
6333     int number_of_own_descriptors = NumberOfOwnDescriptors();
6334     ASSERT(number_of_own_descriptors > 0);
6335     return number_of_own_descriptors - 1;
6336   }
6337
6338   int NumberOfOwnDescriptors() {
6339     return NumberOfOwnDescriptorsBits::decode(bit_field3());
6340   }
6341
6342   void SetNumberOfOwnDescriptors(int number) {
6343     ASSERT(number <= instance_descriptors()->number_of_descriptors());
6344     set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6345   }
6346
6347   inline Cell* RetrieveDescriptorsPointer();
6348
6349   int EnumLength() {
6350     return EnumLengthBits::decode(bit_field3());
6351   }
6352
6353   void SetEnumLength(int length) {
6354     if (length != kInvalidEnumCacheSentinel) {
6355       ASSERT(length >= 0);
6356       ASSERT(length == 0 || instance_descriptors()->HasEnumCache());
6357       ASSERT(length <= NumberOfOwnDescriptors());
6358     }
6359     set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6360   }
6361
6362   inline bool owns_descriptors();
6363   inline void set_owns_descriptors(bool is_shared);
6364   inline bool has_instance_call_handler();
6365   inline void set_has_instance_call_handler();
6366   inline void freeze();
6367   inline bool is_frozen();
6368   inline void mark_unstable();
6369   inline bool is_stable();
6370   inline void set_migration_target(bool value);
6371   inline bool is_migration_target();
6372   inline void deprecate();
6373   inline bool is_deprecated();
6374   inline bool CanBeDeprecated();
6375   // Returns a non-deprecated version of the input. If the input was not
6376   // deprecated, it is directly returned. Otherwise, the non-deprecated version
6377   // is found by re-transitioning from the root of the transition tree using the
6378   // descriptor array of the map. Returns NULL if no updated map is found.
6379   // This method also applies any pending migrations along the prototype chain.
6380   static Handle<Map> CurrentMapForDeprecated(Handle<Map> map);
6381   // Same as above, but does not touch the prototype chain.
6382   static Handle<Map> CurrentMapForDeprecatedInternal(Handle<Map> map);
6383
6384   static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6385   MUST_USE_RESULT MaybeObject* RawCopy(int instance_size);
6386   MUST_USE_RESULT MaybeObject* CopyWithPreallocatedFieldDescriptors();
6387   static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6388   MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
6389   static Handle<Map> CopyReplaceDescriptors(Handle<Map> map,
6390                                             Handle<DescriptorArray> descriptors,
6391                                             TransitionFlag flag,
6392                                             Handle<Name> name);
6393   MUST_USE_RESULT MaybeObject* CopyReplaceDescriptors(
6394       DescriptorArray* descriptors,
6395       TransitionFlag flag,
6396       Name* name = NULL,
6397       SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6398   static Handle<Map> CopyInstallDescriptors(
6399       Handle<Map> map,
6400       int new_descriptor,
6401       Handle<DescriptorArray> descriptors);
6402   MUST_USE_RESULT MaybeObject* ShareDescriptor(DescriptorArray* descriptors,
6403                                                Descriptor* descriptor);
6404   MUST_USE_RESULT MaybeObject* CopyAddDescriptor(Descriptor* descriptor,
6405                                                  TransitionFlag flag);
6406   MUST_USE_RESULT MaybeObject* CopyInsertDescriptor(Descriptor* descriptor,
6407                                                     TransitionFlag flag);
6408   MUST_USE_RESULT MaybeObject* CopyReplaceDescriptor(
6409       DescriptorArray* descriptors,
6410       Descriptor* descriptor,
6411       int index,
6412       TransitionFlag flag);
6413
6414   MUST_USE_RESULT MaybeObject* AsElementsKind(ElementsKind kind);
6415
6416   static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6417
6418   MUST_USE_RESULT MaybeObject* CopyAsElementsKind(ElementsKind kind,
6419                                                   TransitionFlag flag);
6420
6421   static Handle<Map> CopyForObserved(Handle<Map> map);
6422
6423   static Handle<Map> CopyNormalized(Handle<Map> map,
6424                                     PropertyNormalizationMode mode,
6425                                     NormalizedMapSharingMode sharing);
6426
6427   inline void AppendDescriptor(Descriptor* desc,
6428                                const DescriptorArray::WhitenessWitness&);
6429
6430   // Returns a copy of the map, with all transitions dropped from the
6431   // instance descriptors.
6432   static Handle<Map> Copy(Handle<Map> map);
6433   MUST_USE_RESULT MaybeObject* Copy();
6434
6435   // Returns the next free property index (only valid for FAST MODE).
6436   int NextFreePropertyIndex();
6437
6438   // Returns the number of properties described in instance_descriptors
6439   // filtering out properties with the specified attributes.
6440   int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6441                                   PropertyAttributes filter = NONE);
6442
6443   // Returns the number of slots allocated for the initial properties
6444   // backing storage for instances of this map.
6445   int InitialPropertiesLength() {
6446     return pre_allocated_property_fields() + unused_property_fields() -
6447         inobject_properties();
6448   }
6449
6450   // Casting.
6451   static inline Map* cast(Object* obj);
6452
6453   // Locate an accessor in the instance descriptor.
6454   AccessorDescriptor* FindAccessor(Name* name);
6455
6456   // Code cache operations.
6457
6458   // Clears the code cache.
6459   inline void ClearCodeCache(Heap* heap);
6460
6461   // Update code cache.
6462   static void UpdateCodeCache(Handle<Map> map,
6463                               Handle<Name> name,
6464                               Handle<Code> code);
6465   MUST_USE_RESULT MaybeObject* UpdateCodeCache(Name* name, Code* code);
6466
6467   // Extend the descriptor array of the map with the list of descriptors.
6468   // In case of duplicates, the latest descriptor is used.
6469   static void AppendCallbackDescriptors(Handle<Map> map,
6470                                         Handle<Object> descriptors);
6471
6472   static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6473
6474   // Returns the found code or undefined if absent.
6475   Object* FindInCodeCache(Name* name, Code::Flags flags);
6476
6477   // Returns the non-negative index of the code object if it is in the
6478   // cache and -1 otherwise.
6479   int IndexInCodeCache(Object* name, Code* code);
6480
6481   // Removes a code object from the code cache at the given index.
6482   void RemoveFromCodeCache(Name* name, Code* code, int index);
6483
6484   // Set all map transitions from this map to dead maps to null.  Also clear
6485   // back pointers in transition targets so that we do not process this map
6486   // again while following back pointers.
6487   void ClearNonLiveTransitions(Heap* heap);
6488
6489   // Computes a hash value for this map, to be used in HashTables and such.
6490   int Hash();
6491
6492   bool EquivalentToForTransition(Map* other);
6493
6494   // Compares this map to another to see if they describe equivalent objects.
6495   // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6496   // it had exactly zero inobject properties.
6497   // The "shared" flags of both this map and |other| are ignored.
6498   bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6499
6500   // Returns the map that this map transitions to if its elements_kind
6501   // is changed to |elements_kind|, or NULL if no such map is cached yet.
6502   // |safe_to_add_transitions| is set to false if adding transitions is not
6503   // allowed.
6504   Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6505
6506   // Returns the transitioned map for this map with the most generic
6507   // elements_kind that's found in |candidates|, or null handle if no match is
6508   // found at all.
6509   Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6510   Map* FindTransitionedMap(MapList* candidates);
6511
6512   // Zaps the contents of backing data structures. Note that the
6513   // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6514   // holding weak references when incremental marking is used, because it also
6515   // iterates over objects that are otherwise unreachable.
6516   // In general we only want to call these functions in release mode when
6517   // heap verification is turned on.
6518   void ZapPrototypeTransitions();
6519   void ZapTransitions();
6520
6521   bool CanTransition() {
6522     // Only JSObject and subtypes have map transitions and back pointers.
6523     STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6524     return instance_type() >= FIRST_JS_OBJECT_TYPE;
6525   }
6526
6527   bool IsJSObjectMap() {
6528     return instance_type() >= FIRST_JS_OBJECT_TYPE;
6529   }
6530   bool IsJSGlobalProxyMap() {
6531     return instance_type() == JS_GLOBAL_PROXY_TYPE;
6532   }
6533   bool IsJSGlobalObjectMap() {
6534     return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6535   }
6536   bool IsGlobalObjectMap() {
6537     const InstanceType type = instance_type();
6538     return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6539   }
6540
6541   // Fires when the layout of an object with a leaf map changes.
6542   // This includes adding transitions to the leaf map or changing
6543   // the descriptor array.
6544   inline void NotifyLeafMapLayoutChange();
6545
6546   inline bool CanOmitMapChecks();
6547
6548   void AddDependentCompilationInfo(DependentCode::DependencyGroup group,
6549                                    CompilationInfo* info);
6550
6551   void AddDependentCode(DependentCode::DependencyGroup group,
6552                         Handle<Code> code);
6553
6554   bool IsMapInArrayPrototypeChain();
6555
6556   // Dispatched behavior.
6557   DECLARE_PRINTER(Map)
6558   DECLARE_VERIFIER(Map)
6559
6560 #ifdef VERIFY_HEAP
6561   void SharedMapVerify();
6562   void VerifyOmittedMapChecks();
6563 #endif
6564
6565   inline int visitor_id();
6566   inline void set_visitor_id(int visitor_id);
6567
6568   typedef void (*TraverseCallback)(Map* map, void* data);
6569
6570   void TraverseTransitionTree(TraverseCallback callback, void* data);
6571
6572   // When you set the prototype of an object using the __proto__ accessor you
6573   // need a new map for the object (the prototype is stored in the map).  In
6574   // order not to multiply maps unnecessarily we store these as transitions in
6575   // the original map.  That way we can transition to the same map if the same
6576   // prototype is set, rather than creating a new map every time.  The
6577   // transitions are in the form of a map where the keys are prototype objects
6578   // and the values are the maps the are transitioned to.
6579   static const int kMaxCachedPrototypeTransitions = 256;
6580   static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6581                                             Handle<Object> prototype);
6582   static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6583                                             Handle<Object> prototype,
6584                                             Handle<Map> target_map);
6585
6586   static const int kMaxPreAllocatedPropertyFields = 255;
6587
6588   // Layout description.
6589   static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6590   static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6591   static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
6592   static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6593   // Storage for the transition array is overloaded to directly contain a back
6594   // pointer if unused. When the map has transitions, the back pointer is
6595   // transferred to the transition array and accessed through an extra
6596   // indirection.
6597   static const int kTransitionsOrBackPointerOffset =
6598       kConstructorOffset + kPointerSize;
6599   static const int kDescriptorsOffset =
6600       kTransitionsOrBackPointerOffset + kPointerSize;
6601   static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6602   static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6603   static const int kBitField3Offset = kDependentCodeOffset + kPointerSize;
6604   static const int kSize = kBitField3Offset + kPointerSize;
6605
6606   // Layout of pointer fields. Heap iteration code relies on them
6607   // being continuously allocated.
6608   static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6609   static const int kPointerFieldsEndOffset = kBitField3Offset + kPointerSize;
6610
6611   // Byte offsets within kInstanceSizesOffset.
6612   static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6613   static const int kInObjectPropertiesByte = 1;
6614   static const int kInObjectPropertiesOffset =
6615       kInstanceSizesOffset + kInObjectPropertiesByte;
6616   static const int kPreAllocatedPropertyFieldsByte = 2;
6617   static const int kPreAllocatedPropertyFieldsOffset =
6618       kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6619   static const int kVisitorIdByte = 3;
6620   static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6621
6622   // Byte offsets within kInstanceAttributesOffset attributes.
6623   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6624   static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
6625   static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
6626   static const int kBitField2Offset = kInstanceAttributesOffset + 3;
6627
6628   STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
6629
6630   // Bit positions for bit field.
6631   static const int kUnused = 0;  // To be used for marking recently used maps.
6632   static const int kHasNonInstancePrototype = 1;
6633   static const int kIsHiddenPrototype = 2;
6634   static const int kHasNamedInterceptor = 3;
6635   static const int kHasIndexedInterceptor = 4;
6636   static const int kIsUndetectable = 5;
6637   static const int kIsObserved = 6;
6638   static const int kIsAccessCheckNeeded = 7;
6639
6640   // Bit positions for bit field 2
6641   static const int kIsExtensible = 0;
6642   static const int kStringWrapperSafeForDefaultValueOf = 1;
6643   static const int kAttachedToSharedFunctionInfo = 2;
6644   // No bits can be used after kElementsKindFirstBit, they are all reserved for
6645   // storing ElementKind.
6646   static const int kElementsKindShift = 3;
6647   static const int kElementsKindBitCount = 5;
6648
6649   // Derived values from bit field 2
6650   static const int kElementsKindMask = (-1 << kElementsKindShift) &
6651       ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
6652   static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6653       (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
6654   static const int8_t kMaximumBitField2FastSmiElementValue =
6655       static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6656                           Map::kElementsKindShift) - 1;
6657   static const int8_t kMaximumBitField2FastHoleyElementValue =
6658       static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6659                           Map::kElementsKindShift) - 1;
6660   static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6661       static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6662                           Map::kElementsKindShift) - 1;
6663
6664   typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6665                               kPointerFieldsEndOffset,
6666                               kSize> BodyDescriptor;
6667
6668  private:
6669   DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6670 };
6671
6672
6673 // An abstract superclass, a marker class really, for simple structure classes.
6674 // It doesn't carry much functionality but allows struct classes to be
6675 // identified in the type system.
6676 class Struct: public HeapObject {
6677  public:
6678   inline void InitializeBody(int object_size);
6679   static inline Struct* cast(Object* that);
6680 };
6681
6682
6683 // A simple one-element struct, useful where smis need to be boxed.
6684 class Box : public Struct {
6685  public:
6686   // [value]: the boxed contents.
6687   DECL_ACCESSORS(value, Object)
6688
6689   static inline Box* cast(Object* obj);
6690
6691   // Dispatched behavior.
6692   DECLARE_PRINTER(Box)
6693   DECLARE_VERIFIER(Box)
6694
6695   static const int kValueOffset = HeapObject::kHeaderSize;
6696   static const int kSize = kValueOffset + kPointerSize;
6697
6698  private:
6699   DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6700 };
6701
6702
6703 // Script describes a script which has been added to the VM.
6704 class Script: public Struct {
6705  public:
6706   // Script types.
6707   enum Type {
6708     TYPE_NATIVE = 0,
6709     TYPE_EXTENSION = 1,
6710     TYPE_NORMAL = 2
6711   };
6712
6713   // Script compilation types.
6714   enum CompilationType {
6715     COMPILATION_TYPE_HOST = 0,
6716     COMPILATION_TYPE_EVAL = 1
6717   };
6718
6719   // Script compilation state.
6720   enum CompilationState {
6721     COMPILATION_STATE_INITIAL = 0,
6722     COMPILATION_STATE_COMPILED = 1
6723   };
6724
6725   // [source]: the script source.
6726   DECL_ACCESSORS(source, Object)
6727
6728   // [name]: the script name.
6729   DECL_ACCESSORS(name, Object)
6730
6731   // [id]: the script id.
6732   DECL_ACCESSORS(id, Smi)
6733
6734   // [line_offset]: script line offset in resource from where it was extracted.
6735   DECL_ACCESSORS(line_offset, Smi)
6736
6737   // [column_offset]: script column offset in resource from where it was
6738   // extracted.
6739   DECL_ACCESSORS(column_offset, Smi)
6740
6741   // [context_data]: context data for the context this script was compiled in.
6742   DECL_ACCESSORS(context_data, Object)
6743
6744   // [wrapper]: the wrapper cache.
6745   DECL_ACCESSORS(wrapper, Foreign)
6746
6747   // [type]: the script type.
6748   DECL_ACCESSORS(type, Smi)
6749
6750   // [line_ends]: FixedArray of line ends positions.
6751   DECL_ACCESSORS(line_ends, Object)
6752
6753   // [eval_from_shared]: for eval scripts the shared funcion info for the
6754   // function from which eval was called.
6755   DECL_ACCESSORS(eval_from_shared, Object)
6756
6757   // [eval_from_instructions_offset]: the instruction offset in the code for the
6758   // function from which eval was called where eval was called.
6759   DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6760
6761   // [flags]: Holds an exciting bitfield.
6762   DECL_ACCESSORS(flags, Smi)
6763
6764   // [compilation_type]: how the the script was compiled. Encoded in the
6765   // 'flags' field.
6766   inline CompilationType compilation_type();
6767   inline void set_compilation_type(CompilationType type);
6768
6769   // [compilation_state]: determines whether the script has already been
6770   // compiled. Encoded in the 'flags' field.
6771   inline CompilationState compilation_state();
6772   inline void set_compilation_state(CompilationState state);
6773
6774   // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6775   // ScriptOrigin, and used by the embedder to make decisions about the
6776   // script's level of privilege. V8 just passes this through. Encoded in
6777   // the 'flags' field.
6778   DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6779
6780   static inline Script* cast(Object* obj);
6781
6782   // If script source is an external string, check that the underlying
6783   // resource is accessible. Otherwise, always return true.
6784   inline bool HasValidSource();
6785
6786   // Dispatched behavior.
6787   DECLARE_PRINTER(Script)
6788   DECLARE_VERIFIER(Script)
6789
6790   static const int kSourceOffset = HeapObject::kHeaderSize;
6791   static const int kNameOffset = kSourceOffset + kPointerSize;
6792   static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6793   static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6794   static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6795   static const int kWrapperOffset = kContextOffset + kPointerSize;
6796   static const int kTypeOffset = kWrapperOffset + kPointerSize;
6797   static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6798   static const int kIdOffset = kLineEndsOffset + kPointerSize;
6799   static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6800   static const int kEvalFrominstructionsOffsetOffset =
6801       kEvalFromSharedOffset + kPointerSize;
6802   static const int kFlagsOffset =
6803       kEvalFrominstructionsOffsetOffset + kPointerSize;
6804   static const int kSize = kFlagsOffset + kPointerSize;
6805
6806  private:
6807   // Bit positions in the flags field.
6808   static const int kCompilationTypeBit = 0;
6809   static const int kCompilationStateBit = 1;
6810   static const int kIsSharedCrossOriginBit = 2;
6811
6812   DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6813 };
6814
6815
6816 // List of builtin functions we want to identify to improve code
6817 // generation.
6818 //
6819 // Each entry has a name of a global object property holding an object
6820 // optionally followed by ".prototype", a name of a builtin function
6821 // on the object (the one the id is set for), and a label.
6822 //
6823 // Installation of ids for the selected builtin functions is handled
6824 // by the bootstrapper.
6825 #define FUNCTIONS_WITH_ID_LIST(V)                   \
6826   V(Array.prototype, push, ArrayPush)               \
6827   V(Array.prototype, pop, ArrayPop)                 \
6828   V(Function.prototype, apply, FunctionApply)       \
6829   V(String.prototype, charCodeAt, StringCharCodeAt) \
6830   V(String.prototype, charAt, StringCharAt)         \
6831   V(String, fromCharCode, StringFromCharCode)       \
6832   V(Math, floor, MathFloor)                         \
6833   V(Math, round, MathRound)                         \
6834   V(Math, ceil, MathCeil)                           \
6835   V(Math, abs, MathAbs)                             \
6836   V(Math, log, MathLog)                             \
6837   V(Math, exp, MathExp)                             \
6838   V(Math, sqrt, MathSqrt)                           \
6839   V(Math, pow, MathPow)                             \
6840   V(Math, max, MathMax)                             \
6841   V(Math, min, MathMin)                             \
6842   V(Math, imul, MathImul)
6843
6844 #define SIMD_NULLARY_OPERATIONS(V)                                             \
6845   V(SIMD.float32x4, zero, Float32x4Zero, Float32x4)                            \
6846   V(SIMD.int32x4, zero, Int32x4Zero, Int32x4)
6847
6848 #define SIMD_UNARY_OPERATIONS(V)                                               \
6849   V(SIMD.float32x4, abs, Float32x4Abs, Float32x4, Float32x4)                   \
6850   V(SIMD.float32x4, bitsToInt32x4, Float32x4BitsToInt32x4, Int32x4, Float32x4) \
6851   V(SIMD.float32x4, neg, Float32x4Neg, Float32x4, Float32x4)                   \
6852   V(SIMD.float32x4, reciprocal, Float32x4Reciprocal, Float32x4, Float32x4)     \
6853   V(SIMD.float32x4, reciprocalSqrt, Float32x4ReciprocalSqrt,                   \
6854     Float32x4, Float32x4)                                                      \
6855   V(SIMD.float32x4, splat, Float32x4Splat, Float32x4, Double)                  \
6856   V(SIMD.float32x4, sqrt, Float32x4Sqrt, Float32x4, Float32x4)                 \
6857   V(SIMD.float32x4, toInt32x4, Float32x4ToInt32x4, Int32x4, Float32x4)         \
6858   V(SIMD.int32x4, bitsToFloat32x4, Int32x4BitsToFloat32x4, Float32x4, Int32x4) \
6859   V(SIMD.int32x4, neg, Int32x4Neg, Int32x4, Int32x4)                           \
6860   V(SIMD.int32x4, not, Int32x4Not, Int32x4, Int32x4)                           \
6861   V(SIMD.int32x4, splat, Int32x4Splat, Int32x4, Integer32)                     \
6862   V(SIMD.int32x4, toFloat32x4, Int32x4ToFloat32x4, Float32x4, Int32x4)
6863
6864 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6865 #define SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(V)                           \
6866   V(SIMD.float32x4.prototype, signMask, Float32x4GetSignMask, Integer32,       \
6867     Float32x4)                                                                 \
6868   V(SIMD.float32x4.prototype, x, Float32x4GetX, Double, Float32x4)             \
6869   V(SIMD.float32x4.prototype, y, Float32x4GetY, Double, Float32x4)             \
6870   V(SIMD.float32x4.prototype, z, Float32x4GetZ, Double, Float32x4)             \
6871   V(SIMD.float32x4.prototype, w, Float32x4GetW, Double, Float32x4)             \
6872   V(SIMD.int32x4.prototype, signMask, Int32x4GetSignMask, Integer32, Int32x4)  \
6873   V(SIMD.int32x4.prototype, x, Int32x4GetX, Integer32, Int32x4)                \
6874   V(SIMD.int32x4.prototype, y, Int32x4GetY, Integer32, Int32x4)                \
6875   V(SIMD.int32x4.prototype, z, Int32x4GetZ, Integer32, Int32x4)                \
6876   V(SIMD.int32x4.prototype, w, Int32x4GetW, Integer32, Int32x4)                \
6877   V(SIMD.int32x4.prototype, flagX, Int32x4GetFlagX, Tagged, Int32x4)           \
6878   V(SIMD.int32x4.prototype, flagY, Int32x4GetFlagY, Tagged, Int32x4)           \
6879   V(SIMD.int32x4.prototype, flagZ, Int32x4GetFlagZ, Tagged, Int32x4)           \
6880   V(SIMD.int32x4.prototype, flagW, Int32x4GetFlagW, Tagged, Int32x4)
6881
6882 #define SIMD_BINARY_OPERATIONS(V)                                              \
6883   V(SIMD.float32x4, add, Float32x4Add, Float32x4, Float32x4, Float32x4)        \
6884   V(SIMD.float32x4, div, Float32x4Div, Float32x4, Float32x4, Float32x4)        \
6885   V(SIMD.float32x4, max, Float32x4Max, Float32x4, Float32x4, Float32x4)        \
6886   V(SIMD.float32x4, min, Float32x4Min, Float32x4, Float32x4, Float32x4)        \
6887   V(SIMD.float32x4, mul, Float32x4Mul, Float32x4, Float32x4, Float32x4)        \
6888   V(SIMD.float32x4, sub, Float32x4Sub, Float32x4, Float32x4, Float32x4)        \
6889   V(SIMD.float32x4, equal, Float32x4Equal, Int32x4, Float32x4, Float32x4)      \
6890   V(SIMD.float32x4, notEqual, Float32x4NotEqual, Int32x4, Float32x4,           \
6891     Float32x4)                                                                 \
6892   V(SIMD.float32x4, greaterThan, Float32x4GreaterThan, Int32x4, Float32x4,     \
6893     Float32x4)                                                                 \
6894   V(SIMD.float32x4, greaterThanOrEqual, Float32x4GreaterThanOrEqual, Int32x4,  \
6895     Float32x4, Float32x4)                                                      \
6896   V(SIMD.float32x4, lessThan, Float32x4LessThan, Int32x4, Float32x4,           \
6897     Float32x4)                                                                 \
6898   V(SIMD.float32x4, lessThanOrEqual, Float32x4LessThanOrEqual, Int32x4,        \
6899     Float32x4, Float32x4)                                                      \
6900   V(SIMD.float32x4, shuffle, Float32x4Shuffle, Float32x4, Float32x4,           \
6901     Integer32)                                                                 \
6902   V(SIMD.float32x4, scale, Float32x4Scale, Float32x4, Float32x4, Double)       \
6903   V(SIMD.float32x4, withX, Float32x4WithX, Float32x4, Float32x4, Double)       \
6904   V(SIMD.float32x4, withY, Float32x4WithY, Float32x4, Float32x4, Double)       \
6905   V(SIMD.float32x4, withZ, Float32x4WithZ, Float32x4, Float32x4, Double)       \
6906   V(SIMD.float32x4, withW, Float32x4WithW, Float32x4, Float32x4, Double)       \
6907   V(SIMD.int32x4, add, Int32x4Add, Int32x4, Int32x4, Int32x4)                  \
6908   V(SIMD.int32x4, and, Int32x4And, Int32x4, Int32x4, Int32x4)                  \
6909   V(SIMD.int32x4, mul, Int32x4Mul, Int32x4, Int32x4, Int32x4)                  \
6910   V(SIMD.int32x4, or, Int32x4Or, Int32x4, Int32x4, Int32x4)                    \
6911   V(SIMD.int32x4, sub, Int32x4Sub, Int32x4, Int32x4, Int32x4)                  \
6912   V(SIMD.int32x4, xor, Int32x4Xor, Int32x4, Int32x4, Int32x4)                  \
6913   V(SIMD.int32x4, shuffle, Int32x4Shuffle, Int32x4, Int32x4, Integer32)        \
6914   V(SIMD.int32x4, withX, Int32x4WithX, Int32x4, Int32x4, Integer32)            \
6915   V(SIMD.int32x4, withY, Int32x4WithY, Int32x4, Int32x4, Integer32)            \
6916   V(SIMD.int32x4, withZ, Int32x4WithZ, Int32x4, Int32x4, Integer32)            \
6917   V(SIMD.int32x4, withW, Int32x4WithW, Int32x4, Int32x4, Integer32)            \
6918   V(SIMD.int32x4, withFlagX, Int32x4WithFlagX, Int32x4, Int32x4, Tagged)       \
6919   V(SIMD.int32x4, withFlagY, Int32x4WithFlagY, Int32x4, Int32x4, Tagged)       \
6920   V(SIMD.int32x4, withFlagZ, Int32x4WithFlagZ, Int32x4, Int32x4, Tagged)       \
6921   V(SIMD.int32x4, withFlagW, Int32x4WithFlagW, Int32x4, Int32x4, Tagged)       \
6922   V(SIMD.int32x4, greaterThan, Int32x4GreaterThan, Int32x4, Int32x4, Int32x4)  \
6923   V(SIMD.int32x4, equal, Int32x4Equal, Int32x4, Int32x4, Int32x4)              \
6924   V(SIMD.int32x4, lessThan, Int32x4LessThan, Int32x4, Int32x4, Int32x4)        \
6925   V(SIMD.int32x4, shiftLeft, Int32x4ShiftLeft, Int32x4, Int32x4, Integer32)    \
6926   V(SIMD.int32x4, shiftRight, Int32x4ShiftRight, Int32x4, Int32x4, Integer32)  \
6927   V(SIMD.int32x4, shiftRightArithmetic, Int32x4ShiftRightArithmetic, Int32x4,  \
6928     Int32x4, Integer32)
6929
6930 #define SIMD_TERNARY_OPERATIONS(V)                                             \
6931   V(SIMD.float32x4, clamp, Float32x4Clamp, Float32x4, Float32x4, Float32x4,    \
6932     Float32x4)                                                                 \
6933   V(SIMD.float32x4, shuffleMix, Float32x4ShuffleMix, Float32x4, Float32x4,     \
6934     Float32x4, Integer32)                                                      \
6935   V(SIMD.int32x4, select, Int32x4Select, Float32x4, Int32x4, Float32x4,        \
6936     Float32x4)
6937
6938 #define SIMD_QUARTERNARY_OPERATIONS(V)                                         \
6939   V(SIMD, float32x4, Float32x4Constructor, Float32x4, Double, Double, Double,  \
6940     Double)                                                                    \
6941   V(SIMD, int32x4, Int32x4Constructor, Int32x4, Integer32, Integer32,          \
6942     Integer32, Integer32)                                                      \
6943   V(SIMD.int32x4, bool, Int32x4Bool, Int32x4, Tagged, Tagged, Tagged, Tagged)
6944
6945 #define SIMD_ARRAY_OPERATIONS(V)                                               \
6946   V(Float32x4Array.prototype, getAt, Float32x4ArrayGetAt)                      \
6947   V(Float32x4Array.prototype, setAt, Float32x4ArraySetAt)                      \
6948   V(Int32x4Array.prototype, getAt, Int32x4ArrayGetAt)                          \
6949   V(Int32x4Array.prototype, setAt, Int32x4ArraySetAt)
6950
6951 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6952 #define SIMD_FAKE_ID_LISTS(V)                                                  \
6953   V(SIMD, unreachable, SIMD128Unreachable)                                     \
6954   V(SIMD, change, SIMD128Change)
6955
6956 enum BuiltinFunctionId {
6957   kArrayCode,
6958 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name)    \
6959   k##name,
6960   FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6961   // Fake id for a special case of Math.pow. Note, it continues the
6962   // list of math functions.
6963   kMathPowHalf,
6964   // Installed only on --harmony-maths.
6965   kMathClz32,
6966   SIMD_FAKE_ID_LISTS(DECLARE_FUNCTION_ID)
6967   SIMD_ARRAY_OPERATIONS(DECLARE_FUNCTION_ID)
6968 #undef DECLARE_FUNCTION_ID
6969 #define DECLARE_SIMD_NULLARY_FUNCTION_ID(i1, i2, name, i3)                     \
6970   k##name,
6971   SIMD_NULLARY_OPERATIONS(DECLARE_SIMD_NULLARY_FUNCTION_ID)
6972 #undef DECLARE_SIMD_NULLARY_FUNCTION_ID
6973 #define DECLARE_SIMD_UNARY_FUNCTION_ID(i1, i2, name, i3, i4)                   \
6974   k##name,
6975   SIMD_UNARY_OPERATIONS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6976   SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6977 #undef DECLARE_SIMD_UNARY_FUNCTION_ID
6978 #define DECLARE_SIMD_BINARY_FUNCTION_ID(i1, i2, name, i3, i4, i5)              \
6979   k##name,
6980   SIMD_BINARY_OPERATIONS(DECLARE_SIMD_BINARY_FUNCTION_ID)
6981 #undef DECLARE_SIMD_BINARY_FUNCTION_ID
6982 #define DECLARE_SIMD_TERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6)         \
6983   k##name,
6984   SIMD_TERNARY_OPERATIONS(DECLARE_SIMD_TERNARY_FUNCTION_ID)
6985 #undef DECLARE_SIMD_TERNARY_FUNCTION_ID
6986 #define DECLARE_SIMD_QUARTERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6, i7) \
6987   k##name,
6988   SIMD_QUARTERNARY_OPERATIONS(DECLARE_SIMD_QUARTERNARY_FUNCTION_ID)
6989 #undef DECLARE_SIMD_QUARTERNARY_FUNCTION_ID
6990   kNumberOfBuiltinFunction
6991 };
6992
6993
6994 // SharedFunctionInfo describes the JSFunction information that can be
6995 // shared by multiple instances of the function.
6996 class SharedFunctionInfo: public HeapObject {
6997  public:
6998   // [name]: Function name.
6999   DECL_ACCESSORS(name, Object)
7000
7001   // [code]: Function code.
7002   DECL_ACCESSORS(code, Code)
7003   inline void ReplaceCode(Code* code);
7004
7005   // [optimized_code_map]: Map from native context to optimized code
7006   // and a shared literals array or Smi(0) if none.
7007   DECL_ACCESSORS(optimized_code_map, Object)
7008
7009   // Returns index i of the entry with the specified context and OSR entry.
7010   // At position i - 1 is the context, position i the code, and i + 1 the
7011   // literals array.  Returns -1 when no matching entry is found.
7012   int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
7013
7014   // Installs optimized code from the code map on the given closure. The
7015   // index has to be consistent with a search result as defined above.
7016   FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
7017
7018   Code* GetCodeFromOptimizedCodeMap(int index);
7019
7020   // Clear optimized code map.
7021   void ClearOptimizedCodeMap();
7022
7023   // Removed a specific optimized code object from the optimized code map.
7024   void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
7025
7026   // Trims the optimized code map after entries have been removed.
7027   void TrimOptimizedCodeMap(int shrink_by);
7028
7029   // Add a new entry to the optimized code map.
7030   MUST_USE_RESULT MaybeObject* AddToOptimizedCodeMap(Context* native_context,
7031                                                      Code* code,
7032                                                      FixedArray* literals,
7033                                                      BailoutId osr_ast_id);
7034   static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
7035                                     Handle<Context> native_context,
7036                                     Handle<Code> code,
7037                                     Handle<FixedArray> literals,
7038                                     BailoutId osr_ast_id);
7039
7040   // Layout description of the optimized code map.
7041   static const int kNextMapIndex = 0;
7042   static const int kEntriesStart = 1;
7043   static const int kContextOffset = 0;
7044   static const int kCachedCodeOffset = 1;
7045   static const int kLiteralsOffset = 2;
7046   static const int kOsrAstIdOffset = 3;
7047   static const int kEntryLength = 4;
7048   static const int kInitialLength = kEntriesStart + kEntryLength;
7049
7050   // [scope_info]: Scope info.
7051   DECL_ACCESSORS(scope_info, ScopeInfo)
7052
7053   // [construct stub]: Code stub for constructing instances of this function.
7054   DECL_ACCESSORS(construct_stub, Code)
7055
7056   // Returns if this function has been compiled to native code yet.
7057   inline bool is_compiled();
7058
7059   // [length]: The function length - usually the number of declared parameters.
7060   // Use up to 2^30 parameters.
7061   inline int length();
7062   inline void set_length(int value);
7063
7064   // [formal parameter count]: The declared number of parameters.
7065   inline int formal_parameter_count();
7066   inline void set_formal_parameter_count(int value);
7067
7068   // Set the formal parameter count so the function code will be
7069   // called without using argument adaptor frames.
7070   inline void DontAdaptArguments();
7071
7072   // [expected_nof_properties]: Expected number of properties for the function.
7073   inline int expected_nof_properties();
7074   inline void set_expected_nof_properties(int value);
7075
7076   // Inobject slack tracking is the way to reclaim unused inobject space.
7077   //
7078   // The instance size is initially determined by adding some slack to
7079   // expected_nof_properties (to allow for a few extra properties added
7080   // after the constructor). There is no guarantee that the extra space
7081   // will not be wasted.
7082   //
7083   // Here is the algorithm to reclaim the unused inobject space:
7084   // - Detect the first constructor call for this SharedFunctionInfo.
7085   //   When it happens enter the "in progress" state: remember the
7086   //   constructor's initial_map and install a special construct stub that
7087   //   counts constructor calls.
7088   // - While the tracking is in progress create objects filled with
7089   //   one_pointer_filler_map instead of undefined_value. This way they can be
7090   //   resized quickly and safely.
7091   // - Once enough (kGenerousAllocationCount) objects have been created
7092   //   compute the 'slack' (traverse the map transition tree starting from the
7093   //   initial_map and find the lowest value of unused_property_fields).
7094   // - Traverse the transition tree again and decrease the instance size
7095   //   of every map. Existing objects will resize automatically (they are
7096   //   filled with one_pointer_filler_map). All further allocations will
7097   //   use the adjusted instance size.
7098   // - Decrease expected_nof_properties so that an allocations made from
7099   //   another context will use the adjusted instance size too.
7100   // - Exit "in progress" state by clearing the reference to the initial_map
7101   //   and setting the regular construct stub (generic or inline).
7102   //
7103   //  The above is the main event sequence. Some special cases are possible
7104   //  while the tracking is in progress:
7105   //
7106   // - GC occurs.
7107   //   Check if the initial_map is referenced by any live objects (except this
7108   //   SharedFunctionInfo). If it is, continue tracking as usual.
7109   //   If it is not, clear the reference and reset the tracking state. The
7110   //   tracking will be initiated again on the next constructor call.
7111   //
7112   // - The constructor is called from another context.
7113   //   Immediately complete the tracking, perform all the necessary changes
7114   //   to maps. This is  necessary because there is no efficient way to track
7115   //   multiple initial_maps.
7116   //   Proceed to create an object in the current context (with the adjusted
7117   //   size).
7118   //
7119   // - A different constructor function sharing the same SharedFunctionInfo is
7120   //   called in the same context. This could be another closure in the same
7121   //   context, or the first function could have been disposed.
7122   //   This is handled the same way as the previous case.
7123   //
7124   //  Important: inobject slack tracking is not attempted during the snapshot
7125   //  creation.
7126
7127   static const int kGenerousAllocationCount = 8;
7128
7129   // [construction_count]: Counter for constructor calls made during
7130   // the tracking phase.
7131   inline int construction_count();
7132   inline void set_construction_count(int value);
7133
7134   // [initial_map]: initial map of the first function called as a constructor.
7135   // Saved for the duration of the tracking phase.
7136   // This is a weak link (GC resets it to undefined_value if no other live
7137   // object reference this map).
7138   DECL_ACCESSORS(initial_map, Object)
7139
7140   // True if the initial_map is not undefined and the countdown stub is
7141   // installed.
7142   inline bool IsInobjectSlackTrackingInProgress();
7143
7144   // Starts the tracking.
7145   // Stores the initial map and installs the countdown stub.
7146   // IsInobjectSlackTrackingInProgress is normally true after this call,
7147   // except when tracking have not been started (e.g. the map has no unused
7148   // properties or the snapshot is being built).
7149   void StartInobjectSlackTracking(Map* map);
7150
7151   // Completes the tracking.
7152   // IsInobjectSlackTrackingInProgress is false after this call.
7153   void CompleteInobjectSlackTracking();
7154
7155   // Invoked before pointers in SharedFunctionInfo are being marked.
7156   // Also clears the optimized code map.
7157   inline void BeforeVisitingPointers();
7158
7159   // Clears the initial_map before the GC marking phase to ensure the reference
7160   // is weak. IsInobjectSlackTrackingInProgress is false after this call.
7161   void DetachInitialMap();
7162
7163   // Restores the link to the initial map after the GC marking phase.
7164   // IsInobjectSlackTrackingInProgress is true after this call.
7165   void AttachInitialMap(Map* map);
7166
7167   // False if there are definitely no live objects created from this function.
7168   // True if live objects _may_ exist (existence not guaranteed).
7169   // May go back from true to false after GC.
7170   DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
7171
7172   // [instance class name]: class name for instances.
7173   DECL_ACCESSORS(instance_class_name, Object)
7174
7175   // [function data]: This field holds some additional data for function.
7176   // Currently it either has FunctionTemplateInfo to make benefit the API
7177   // or Smi identifying a builtin function.
7178   // In the long run we don't want all functions to have this field but
7179   // we can fix that when we have a better model for storing hidden data
7180   // on objects.
7181   DECL_ACCESSORS(function_data, Object)
7182
7183   inline bool IsApiFunction();
7184   inline FunctionTemplateInfo* get_api_func_data();
7185   inline bool HasBuiltinFunctionId();
7186   inline BuiltinFunctionId builtin_function_id();
7187
7188   // [script info]: Script from which the function originates.
7189   DECL_ACCESSORS(script, Object)
7190
7191   // [num_literals]: Number of literals used by this function.
7192   inline int num_literals();
7193   inline void set_num_literals(int value);
7194
7195   // [start_position_and_type]: Field used to store both the source code
7196   // position, whether or not the function is a function expression,
7197   // and whether or not the function is a toplevel function. The two
7198   // least significants bit indicates whether the function is an
7199   // expression and the rest contains the source code position.
7200   inline int start_position_and_type();
7201   inline void set_start_position_and_type(int value);
7202
7203   // [debug info]: Debug information.
7204   DECL_ACCESSORS(debug_info, Object)
7205
7206   // [inferred name]: Name inferred from variable or property
7207   // assignment of this function. Used to facilitate debugging and
7208   // profiling of JavaScript code written in OO style, where almost
7209   // all functions are anonymous but are assigned to object
7210   // properties.
7211   DECL_ACCESSORS(inferred_name, String)
7212
7213   // The function's name if it is non-empty, otherwise the inferred name.
7214   String* DebugName();
7215
7216   // Position of the 'function' token in the script source.
7217   inline int function_token_position();
7218   inline void set_function_token_position(int function_token_position);
7219
7220   // Position of this function in the script source.
7221   inline int start_position();
7222   inline void set_start_position(int start_position);
7223
7224   // End position of this function in the script source.
7225   inline int end_position();
7226   inline void set_end_position(int end_position);
7227
7228   // Is this function a function expression in the source code.
7229   DECL_BOOLEAN_ACCESSORS(is_expression)
7230
7231   // Is this function a top-level function (scripts, evals).
7232   DECL_BOOLEAN_ACCESSORS(is_toplevel)
7233
7234   // Bit field containing various information collected by the compiler to
7235   // drive optimization.
7236   inline int compiler_hints();
7237   inline void set_compiler_hints(int value);
7238
7239   inline int ast_node_count();
7240   inline void set_ast_node_count(int count);
7241
7242   inline int profiler_ticks();
7243
7244   // Inline cache age is used to infer whether the function survived a context
7245   // disposal or not. In the former case we reset the opt_count.
7246   inline int ic_age();
7247   inline void set_ic_age(int age);
7248
7249   // Indicates if this function can be lazy compiled.
7250   // This is used to determine if we can safely flush code from a function
7251   // when doing GC if we expect that the function will no longer be used.
7252   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7253
7254   // Indicates if this function can be lazy compiled without a context.
7255   // This is used to determine if we can force compilation without reaching
7256   // the function through program execution but through other means (e.g. heap
7257   // iteration by the debugger).
7258   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7259
7260   // Indicates whether optimizations have been disabled for this
7261   // shared function info. If a function is repeatedly optimized or if
7262   // we cannot optimize the function we disable optimization to avoid
7263   // spending time attempting to optimize it again.
7264   DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7265
7266   // Indicates the language mode.
7267   inline StrictMode strict_mode();
7268   inline void set_strict_mode(StrictMode strict_mode);
7269
7270   // False if the function definitely does not allocate an arguments object.
7271   DECL_BOOLEAN_ACCESSORS(uses_arguments)
7272
7273   // True if the function has any duplicated parameter names.
7274   DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7275
7276   // Indicates whether the function is a native function.
7277   // These needs special treatment in .call and .apply since
7278   // null passed as the receiver should not be translated to the
7279   // global object.
7280   DECL_BOOLEAN_ACCESSORS(native)
7281
7282   // Indicate that this builtin needs to be inlined in crankshaft.
7283   DECL_BOOLEAN_ACCESSORS(inline_builtin)
7284
7285   // Indicates that the function was created by the Function function.
7286   // Though it's anonymous, toString should treat it as if it had the name
7287   // "anonymous".  We don't set the name itself so that the system does not
7288   // see a binding for it.
7289   DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7290
7291   // Indicates whether the function is a bound function created using
7292   // the bind function.
7293   DECL_BOOLEAN_ACCESSORS(bound)
7294
7295   // Indicates that the function is anonymous (the name field can be set
7296   // through the API, which does not change this flag).
7297   DECL_BOOLEAN_ACCESSORS(is_anonymous)
7298
7299   // Is this a function or top-level/eval code.
7300   DECL_BOOLEAN_ACCESSORS(is_function)
7301
7302   // Indicates that the function cannot be optimized.
7303   DECL_BOOLEAN_ACCESSORS(dont_optimize)
7304
7305   // Indicates that the function cannot be inlined.
7306   DECL_BOOLEAN_ACCESSORS(dont_inline)
7307
7308   // Indicates that code for this function cannot be cached.
7309   DECL_BOOLEAN_ACCESSORS(dont_cache)
7310
7311   // Indicates that code for this function cannot be flushed.
7312   DECL_BOOLEAN_ACCESSORS(dont_flush)
7313
7314   // Indicates that this function is a generator.
7315   DECL_BOOLEAN_ACCESSORS(is_generator)
7316
7317   // Indicates whether or not the code in the shared function support
7318   // deoptimization.
7319   inline bool has_deoptimization_support();
7320
7321   // Enable deoptimization support through recompiled code.
7322   void EnableDeoptimizationSupport(Code* recompiled);
7323
7324   // Disable (further) attempted optimization of all functions sharing this
7325   // shared function info.
7326   void DisableOptimization(BailoutReason reason);
7327
7328   inline BailoutReason DisableOptimizationReason();
7329
7330   // Lookup the bailout ID and ASSERT that it exists in the non-optimized
7331   // code, returns whether it asserted (i.e., always true if assertions are
7332   // disabled).
7333   bool VerifyBailoutId(BailoutId id);
7334
7335   // [source code]: Source code for the function.
7336   bool HasSourceCode();
7337   Handle<Object> GetSourceCode();
7338
7339   // Number of times the function was optimized.
7340   inline int opt_count();
7341   inline void set_opt_count(int opt_count);
7342
7343   // Number of times the function was deoptimized.
7344   inline void set_deopt_count(int value);
7345   inline int deopt_count();
7346   inline void increment_deopt_count();
7347
7348   // Number of time we tried to re-enable optimization after it
7349   // was disabled due to high number of deoptimizations.
7350   inline void set_opt_reenable_tries(int value);
7351   inline int opt_reenable_tries();
7352
7353   inline void TryReenableOptimization();
7354
7355   // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7356   inline void set_counters(int value);
7357   inline int counters();
7358
7359   // Stores opt_count and bailout_reason as bit-fields.
7360   inline void set_opt_count_and_bailout_reason(int value);
7361   inline int opt_count_and_bailout_reason();
7362
7363   void set_bailout_reason(BailoutReason reason) {
7364     set_opt_count_and_bailout_reason(
7365         DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7366                                                reason));
7367   }
7368
7369   void set_dont_optimize_reason(BailoutReason reason) {
7370     set_bailout_reason(reason);
7371     set_dont_optimize(reason != kNoReason);
7372   }
7373
7374   // Check whether or not this function is inlineable.
7375   bool IsInlineable();
7376
7377   // Source size of this function.
7378   int SourceSize();
7379
7380   // Calculate the instance size.
7381   int CalculateInstanceSize();
7382
7383   // Calculate the number of in-object properties.
7384   int CalculateInObjectProperties();
7385
7386   // Dispatched behavior.
7387   // Set max_length to -1 for unlimited length.
7388   void SourceCodePrint(StringStream* accumulator, int max_length);
7389   DECLARE_PRINTER(SharedFunctionInfo)
7390   DECLARE_VERIFIER(SharedFunctionInfo)
7391
7392   void ResetForNewContext(int new_ic_age);
7393
7394   // Casting.
7395   static inline SharedFunctionInfo* cast(Object* obj);
7396
7397   // Constants.
7398   static const int kDontAdaptArgumentsSentinel = -1;
7399
7400   // Layout description.
7401   // Pointer fields.
7402   static const int kNameOffset = HeapObject::kHeaderSize;
7403   static const int kCodeOffset = kNameOffset + kPointerSize;
7404   static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7405   static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7406   static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7407   static const int kInstanceClassNameOffset =
7408       kConstructStubOffset + kPointerSize;
7409   static const int kFunctionDataOffset =
7410       kInstanceClassNameOffset + kPointerSize;
7411   static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7412   static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7413   static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7414   static const int kInitialMapOffset =
7415       kInferredNameOffset + kPointerSize;
7416   // ast_node_count is a Smi field. It could be grouped with another Smi field
7417   // into a PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
7418   static const int kAstNodeCountOffset =
7419       kInitialMapOffset + kPointerSize;
7420 #if V8_HOST_ARCH_32_BIT
7421   // Smi fields.
7422   static const int kLengthOffset =
7423       kAstNodeCountOffset + kPointerSize;
7424   static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7425   static const int kExpectedNofPropertiesOffset =
7426       kFormalParameterCountOffset + kPointerSize;
7427   static const int kNumLiteralsOffset =
7428       kExpectedNofPropertiesOffset + kPointerSize;
7429   static const int kStartPositionAndTypeOffset =
7430       kNumLiteralsOffset + kPointerSize;
7431   static const int kEndPositionOffset =
7432       kStartPositionAndTypeOffset + kPointerSize;
7433   static const int kFunctionTokenPositionOffset =
7434       kEndPositionOffset + kPointerSize;
7435   static const int kCompilerHintsOffset =
7436       kFunctionTokenPositionOffset + kPointerSize;
7437   static const int kOptCountAndBailoutReasonOffset =
7438       kCompilerHintsOffset + kPointerSize;
7439   static const int kCountersOffset =
7440       kOptCountAndBailoutReasonOffset + kPointerSize;
7441
7442   // Total size.
7443   static const int kSize = kCountersOffset + kPointerSize;
7444 #else
7445   // The only reason to use smi fields instead of int fields
7446   // is to allow iteration without maps decoding during
7447   // garbage collections.
7448   // To avoid wasting space on 64-bit architectures we use
7449   // the following trick: we group integer fields into pairs
7450   // First integer in each pair is shifted left by 1.
7451   // By doing this we guarantee that LSB of each kPointerSize aligned
7452   // word is not set and thus this word cannot be treated as pointer
7453   // to HeapObject during old space traversal.
7454   static const int kLengthOffset =
7455       kAstNodeCountOffset + kPointerSize;
7456   static const int kFormalParameterCountOffset =
7457       kLengthOffset + kIntSize;
7458
7459   static const int kExpectedNofPropertiesOffset =
7460       kFormalParameterCountOffset + kIntSize;
7461   static const int kNumLiteralsOffset =
7462       kExpectedNofPropertiesOffset + kIntSize;
7463
7464   static const int kEndPositionOffset =
7465       kNumLiteralsOffset + kIntSize;
7466   static const int kStartPositionAndTypeOffset =
7467       kEndPositionOffset + kIntSize;
7468
7469   static const int kFunctionTokenPositionOffset =
7470       kStartPositionAndTypeOffset + kIntSize;
7471   static const int kCompilerHintsOffset =
7472       kFunctionTokenPositionOffset + kIntSize;
7473
7474   static const int kOptCountAndBailoutReasonOffset =
7475       kCompilerHintsOffset + kIntSize;
7476
7477   static const int kCountersOffset =
7478       kOptCountAndBailoutReasonOffset + kIntSize;
7479
7480   // Total size.
7481   static const int kSize = kCountersOffset + kIntSize;
7482
7483 #endif
7484
7485   // The construction counter for inobject slack tracking is stored in the
7486   // most significant byte of compiler_hints which is otherwise unused.
7487   // Its offset depends on the endian-ness of the architecture.
7488 #if __BYTE_ORDER == __LITTLE_ENDIAN
7489   static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
7490 #elif __BYTE_ORDER == __BIG_ENDIAN
7491   static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
7492 #else
7493 #error Unknown byte ordering
7494 #endif
7495
7496   static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7497
7498   typedef FixedBodyDescriptor<kNameOffset,
7499                               kInitialMapOffset + kPointerSize,
7500                               kSize> BodyDescriptor;
7501
7502   // Bit positions in start_position_and_type.
7503   // The source code start position is in the 30 most significant bits of
7504   // the start_position_and_type field.
7505   static const int kIsExpressionBit    = 0;
7506   static const int kIsTopLevelBit      = 1;
7507   static const int kStartPositionShift = 2;
7508   static const int kStartPositionMask  = ~((1 << kStartPositionShift) - 1);
7509
7510   // Bit positions in compiler_hints.
7511   enum CompilerHints {
7512     kAllowLazyCompilation,
7513     kAllowLazyCompilationWithoutContext,
7514     kLiveObjectsMayExist,
7515     kOptimizationDisabled,
7516     kStrictModeFunction,
7517     kUsesArguments,
7518     kHasDuplicateParameters,
7519     kNative,
7520     kInlineBuiltin,
7521     kBoundFunction,
7522     kIsAnonymous,
7523     kNameShouldPrintAsAnonymous,
7524     kIsFunction,
7525     kDontOptimize,
7526     kDontInline,
7527     kDontCache,
7528     kDontFlush,
7529     kIsGenerator,
7530     kCompilerHintsCount  // Pseudo entry
7531   };
7532
7533   class DeoptCountBits: public BitField<int, 0, 4> {};
7534   class OptReenableTriesBits: public BitField<int, 4, 18> {};
7535   class ICAgeBits: public BitField<int, 22, 8> {};
7536
7537   class OptCountBits: public BitField<int, 0, 22> {};
7538   class DisabledOptimizationReasonBits: public BitField<int, 22, 8> {};
7539
7540  private:
7541 #if V8_HOST_ARCH_32_BIT
7542   // On 32 bit platforms, compiler hints is a smi.
7543   static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7544   static const int kCompilerHintsSize = kPointerSize;
7545 #else
7546   // On 64 bit platforms, compiler hints is not a smi, see comment above.
7547   static const int kCompilerHintsSmiTagSize = 0;
7548   static const int kCompilerHintsSize = kIntSize;
7549 #endif
7550
7551   STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7552                 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7553
7554  public:
7555   // Constants for optimizing codegen for strict mode function and
7556   // native tests.
7557   // Allows to use byte-width instructions.
7558   static const int kStrictModeBitWithinByte =
7559       (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7560
7561   static const int kNativeBitWithinByte =
7562       (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7563
7564 #if __BYTE_ORDER == __LITTLE_ENDIAN
7565   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7566       (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7567   static const int kNativeByteOffset = kCompilerHintsOffset +
7568       (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7569 #elif __BYTE_ORDER == __BIG_ENDIAN
7570   static const int kStrictModeByteOffset = kCompilerHintsOffset +
7571       (kCompilerHintsSize - 1) -
7572       ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7573   static const int kNativeByteOffset = kCompilerHintsOffset +
7574       (kCompilerHintsSize - 1) -
7575       ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7576 #else
7577 #error Unknown byte ordering
7578 #endif
7579
7580  private:
7581   DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7582 };
7583
7584
7585 class JSGeneratorObject: public JSObject {
7586  public:
7587   // [function]: The function corresponding to this generator object.
7588   DECL_ACCESSORS(function, JSFunction)
7589
7590   // [context]: The context of the suspended computation.
7591   DECL_ACCESSORS(context, Context)
7592
7593   // [receiver]: The receiver of the suspended computation.
7594   DECL_ACCESSORS(receiver, Object)
7595
7596   // [continuation]: Offset into code of continuation.
7597   //
7598   // A positive offset indicates a suspended generator.  The special
7599   // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7600   // cannot be resumed.
7601   inline int continuation();
7602   inline void set_continuation(int continuation);
7603
7604   // [operand_stack]: Saved operand stack.
7605   DECL_ACCESSORS(operand_stack, FixedArray)
7606
7607   // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7608   // if the captured activation had no stack handler.
7609   inline int stack_handler_index();
7610   inline void set_stack_handler_index(int stack_handler_index);
7611
7612   // Casting.
7613   static inline JSGeneratorObject* cast(Object* obj);
7614
7615   // Dispatched behavior.
7616   DECLARE_PRINTER(JSGeneratorObject)
7617   DECLARE_VERIFIER(JSGeneratorObject)
7618
7619   // Magic sentinel values for the continuation.
7620   static const int kGeneratorExecuting = -1;
7621   static const int kGeneratorClosed = 0;
7622
7623   // Layout description.
7624   static const int kFunctionOffset = JSObject::kHeaderSize;
7625   static const int kContextOffset = kFunctionOffset + kPointerSize;
7626   static const int kReceiverOffset = kContextOffset + kPointerSize;
7627   static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7628   static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7629   static const int kStackHandlerIndexOffset =
7630       kOperandStackOffset + kPointerSize;
7631   static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7632
7633   // Resume mode, for use by runtime functions.
7634   enum ResumeMode { NEXT, THROW };
7635
7636   // Yielding from a generator returns an object with the following inobject
7637   // properties.  See Context::generator_result_map() for the map.
7638   static const int kResultValuePropertyIndex = 0;
7639   static const int kResultDonePropertyIndex = 1;
7640   static const int kResultPropertyCount = 2;
7641
7642   static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7643   static const int kResultDonePropertyOffset =
7644       kResultValuePropertyOffset + kPointerSize;
7645   static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7646
7647  private:
7648   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7649 };
7650
7651
7652 // Representation for module instance objects.
7653 class JSModule: public JSObject {
7654  public:
7655   // [context]: the context holding the module's locals, or undefined if none.
7656   DECL_ACCESSORS(context, Object)
7657
7658   // [scope_info]: Scope info.
7659   DECL_ACCESSORS(scope_info, ScopeInfo)
7660
7661   // Casting.
7662   static inline JSModule* cast(Object* obj);
7663
7664   // Dispatched behavior.
7665   DECLARE_PRINTER(JSModule)
7666   DECLARE_VERIFIER(JSModule)
7667
7668   // Layout description.
7669   static const int kContextOffset = JSObject::kHeaderSize;
7670   static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7671   static const int kSize = kScopeInfoOffset + kPointerSize;
7672
7673  private:
7674   DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7675 };
7676
7677
7678 // JSFunction describes JavaScript functions.
7679 class JSFunction: public JSObject {
7680  public:
7681   // [prototype_or_initial_map]:
7682   DECL_ACCESSORS(prototype_or_initial_map, Object)
7683
7684   // [shared]: The information about the function that
7685   // can be shared by instances.
7686   DECL_ACCESSORS(shared, SharedFunctionInfo)
7687
7688   // [context]: The context for this function.
7689   inline Context* context();
7690   inline void set_context(Object* context);
7691
7692   // [code]: The generated code object for this function.  Executed
7693   // when the function is invoked, e.g. foo() or new foo(). See
7694   // [[Call]] and [[Construct]] description in ECMA-262, section
7695   // 8.6.2, page 27.
7696   inline Code* code();
7697   inline void set_code(Code* code);
7698   inline void set_code_no_write_barrier(Code* code);
7699   inline void ReplaceCode(Code* code);
7700
7701   // Tells whether this function is builtin.
7702   inline bool IsBuiltin();
7703
7704   // Tells whether or not the function needs arguments adaption.
7705   inline bool NeedsArgumentsAdaption();
7706
7707   // Tells whether or not this function has been optimized.
7708   inline bool IsOptimized();
7709
7710   // Tells whether or not this function can be optimized.
7711   inline bool IsOptimizable();
7712
7713   // Mark this function for lazy recompilation. The function will be
7714   // recompiled the next time it is executed.
7715   void MarkForOptimization();
7716   void MarkForConcurrentOptimization();
7717   void MarkInOptimizationQueue();
7718
7719   // Tells whether or not the function is already marked for lazy
7720   // recompilation.
7721   inline bool IsMarkedForOptimization();
7722   inline bool IsMarkedForConcurrentOptimization();
7723
7724   // Tells whether or not the function is on the concurrent recompilation queue.
7725   inline bool IsInOptimizationQueue();
7726
7727   // [literals_or_bindings]: Fixed array holding either
7728   // the materialized literals or the bindings of a bound function.
7729   //
7730   // If the function contains object, regexp or array literals, the
7731   // literals array prefix contains the object, regexp, and array
7732   // function to be used when creating these literals.  This is
7733   // necessary so that we do not dynamically lookup the object, regexp
7734   // or array functions.  Performing a dynamic lookup, we might end up
7735   // using the functions from a new context that we should not have
7736   // access to.
7737   //
7738   // On bound functions, the array is a (copy-on-write) fixed-array containing
7739   // the function that was bound, bound this-value and any bound
7740   // arguments. Bound functions never contain literals.
7741   DECL_ACCESSORS(literals_or_bindings, FixedArray)
7742
7743   inline FixedArray* literals();
7744   inline void set_literals(FixedArray* literals);
7745
7746   inline FixedArray* function_bindings();
7747   inline void set_function_bindings(FixedArray* bindings);
7748
7749   // The initial map for an object created by this constructor.
7750   inline Map* initial_map();
7751   inline void set_initial_map(Map* value);
7752   inline bool has_initial_map();
7753   static void EnsureHasInitialMap(Handle<JSFunction> function);
7754
7755   // Get and set the prototype property on a JSFunction. If the
7756   // function has an initial map the prototype is set on the initial
7757   // map. Otherwise, the prototype is put in the initial map field
7758   // until an initial map is needed.
7759   inline bool has_prototype();
7760   inline bool has_instance_prototype();
7761   inline Object* prototype();
7762   inline Object* instance_prototype();
7763   static void SetPrototype(Handle<JSFunction> function,
7764                            Handle<Object> value);
7765   static void SetInstancePrototype(Handle<JSFunction> function,
7766                                    Handle<Object> value);
7767
7768   // After prototype is removed, it will not be created when accessed, and
7769   // [[Construct]] from this function will not be allowed.
7770   void RemovePrototype();
7771   inline bool should_have_prototype();
7772
7773   // Accessor for this function's initial map's [[class]]
7774   // property. This is primarily used by ECMA native functions.  This
7775   // method sets the class_name field of this function's initial map
7776   // to a given value. It creates an initial map if this function does
7777   // not have one. Note that this method does not copy the initial map
7778   // if it has one already, but simply replaces it with the new value.
7779   // Instances created afterwards will have a map whose [[class]] is
7780   // set to 'value', but there is no guarantees on instances created
7781   // before.
7782   void SetInstanceClassName(String* name);
7783
7784   // Returns if this function has been compiled to native code yet.
7785   inline bool is_compiled();
7786
7787   // [next_function_link]: Links functions into various lists, e.g. the list
7788   // of optimized functions hanging off the native_context. The CodeFlusher
7789   // uses this link to chain together flushing candidates. Treated weakly
7790   // by the garbage collector.
7791   DECL_ACCESSORS(next_function_link, Object)
7792
7793   // Prints the name of the function using PrintF.
7794   void PrintName(FILE* out = stdout);
7795
7796   // Casting.
7797   static inline JSFunction* cast(Object* obj);
7798
7799   // Iterates the objects, including code objects indirectly referenced
7800   // through pointers to the first instruction in the code object.
7801   void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7802
7803   // Dispatched behavior.
7804   DECLARE_PRINTER(JSFunction)
7805   DECLARE_VERIFIER(JSFunction)
7806
7807   // Returns the number of allocated literals.
7808   inline int NumberOfLiterals();
7809
7810   // Retrieve the native context from a function's literal array.
7811   static Context* NativeContextFromLiterals(FixedArray* literals);
7812
7813   // Used for flags such as --hydrogen-filter.
7814   bool PassesFilter(const char* raw_filter);
7815
7816   // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7817   // kSize) is weak and has special handling during garbage collection.
7818   static const int kCodeEntryOffset = JSObject::kHeaderSize;
7819   static const int kPrototypeOrInitialMapOffset =
7820       kCodeEntryOffset + kPointerSize;
7821   static const int kSharedFunctionInfoOffset =
7822       kPrototypeOrInitialMapOffset + kPointerSize;
7823   static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7824   static const int kLiteralsOffset = kContextOffset + kPointerSize;
7825   static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7826   static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7827   static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7828
7829   // Layout of the literals array.
7830   static const int kLiteralsPrefixSize = 1;
7831   static const int kLiteralNativeContextIndex = 0;
7832
7833   // Layout of the bound-function binding array.
7834   static const int kBoundFunctionIndex = 0;
7835   static const int kBoundThisIndex = 1;
7836   static const int kBoundArgumentsStartIndex = 2;
7837
7838  private:
7839   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7840 };
7841
7842
7843 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7844 // and the prototype is hidden. JSGlobalProxy always delegates
7845 // property accesses to its prototype if the prototype is not null.
7846 //
7847 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7848 //
7849 // Accessing a JSGlobalProxy requires security check.
7850
7851 class JSGlobalProxy : public JSObject {
7852  public:
7853   // [native_context]: the owner native context of this global proxy object.
7854   // It is null value if this object is not used by any context.
7855   DECL_ACCESSORS(native_context, Object)
7856
7857   // Casting.
7858   static inline JSGlobalProxy* cast(Object* obj);
7859
7860   inline bool IsDetachedFrom(GlobalObject* global);
7861
7862   // Dispatched behavior.
7863   DECLARE_PRINTER(JSGlobalProxy)
7864   DECLARE_VERIFIER(JSGlobalProxy)
7865
7866   // Layout description.
7867   static const int kNativeContextOffset = JSObject::kHeaderSize;
7868   static const int kSize = kNativeContextOffset + kPointerSize;
7869
7870  private:
7871   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7872 };
7873
7874
7875 // Forward declaration.
7876 class JSBuiltinsObject;
7877
7878 // Common super class for JavaScript global objects and the special
7879 // builtins global objects.
7880 class GlobalObject: public JSObject {
7881  public:
7882   // [builtins]: the object holding the runtime routines written in JS.
7883   DECL_ACCESSORS(builtins, JSBuiltinsObject)
7884
7885   // [native context]: the natives corresponding to this global object.
7886   DECL_ACCESSORS(native_context, Context)
7887
7888   // [global context]: the most recent (i.e. innermost) global context.
7889   DECL_ACCESSORS(global_context, Context)
7890
7891   // [global receiver]: the global receiver object of the context
7892   DECL_ACCESSORS(global_receiver, JSObject)
7893
7894   // Retrieve the property cell used to store a property.
7895   PropertyCell* GetPropertyCell(LookupResult* result);
7896
7897   // This is like GetProperty, but is used when you know the lookup won't fail
7898   // by throwing an exception.  This is for the debug and builtins global
7899   // objects, where it is known which properties can be expected to be present
7900   // on the object.
7901   Object* GetPropertyNoExceptionThrown(Name* key) {
7902     Object* answer = GetProperty(key)->ToObjectUnchecked();
7903     return answer;
7904   }
7905
7906   // Casting.
7907   static inline GlobalObject* cast(Object* obj);
7908
7909   // Layout description.
7910   static const int kBuiltinsOffset = JSObject::kHeaderSize;
7911   static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7912   static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7913   static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
7914   static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
7915
7916  private:
7917   DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7918 };
7919
7920
7921 // JavaScript global object.
7922 class JSGlobalObject: public GlobalObject {
7923  public:
7924   // Casting.
7925   static inline JSGlobalObject* cast(Object* obj);
7926
7927   // Ensure that the global object has a cell for the given property name.
7928   static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7929                                                  Handle<Name> name);
7930
7931   inline bool IsDetached();
7932
7933   // Dispatched behavior.
7934   DECLARE_PRINTER(JSGlobalObject)
7935   DECLARE_VERIFIER(JSGlobalObject)
7936
7937   // Layout description.
7938   static const int kSize = GlobalObject::kHeaderSize;
7939
7940  private:
7941   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7942 };
7943
7944
7945 // Builtins global object which holds the runtime routines written in
7946 // JavaScript.
7947 class JSBuiltinsObject: public GlobalObject {
7948  public:
7949   // Accessors for the runtime routines written in JavaScript.
7950   inline Object* javascript_builtin(Builtins::JavaScript id);
7951   inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7952
7953   // Accessors for code of the runtime routines written in JavaScript.
7954   inline Code* javascript_builtin_code(Builtins::JavaScript id);
7955   inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7956
7957   // Casting.
7958   static inline JSBuiltinsObject* cast(Object* obj);
7959
7960   // Dispatched behavior.
7961   DECLARE_PRINTER(JSBuiltinsObject)
7962   DECLARE_VERIFIER(JSBuiltinsObject)
7963
7964   // Layout description.  The size of the builtins object includes
7965   // room for two pointers per runtime routine written in javascript
7966   // (function and code object).
7967   static const int kJSBuiltinsCount = Builtins::id_count;
7968   static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7969   static const int kJSBuiltinsCodeOffset =
7970       GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7971   static const int kSize =
7972       kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7973
7974   static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7975     return kJSBuiltinsOffset + id * kPointerSize;
7976   }
7977
7978   static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7979     return kJSBuiltinsCodeOffset + id * kPointerSize;
7980   }
7981
7982  private:
7983   DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7984 };
7985
7986
7987 // Representation for JS Wrapper objects, String, Number, Float32x4, Int32x4,
7988 // Boolean, etc.
7989 class JSValue: public JSObject {
7990  public:
7991   // [value]: the object being wrapped.
7992   DECL_ACCESSORS(value, Object)
7993
7994   // Casting.
7995   static inline JSValue* cast(Object* obj);
7996
7997   // Dispatched behavior.
7998   DECLARE_PRINTER(JSValue)
7999   DECLARE_VERIFIER(JSValue)
8000
8001   // Layout description.
8002   static const int kValueOffset = JSObject::kHeaderSize;
8003   static const int kSize = kValueOffset + kPointerSize;
8004
8005  private:
8006   DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
8007 };
8008
8009
8010 class DateCache;
8011
8012 // Representation for JS date objects.
8013 class JSDate: public JSObject {
8014  public:
8015   // If one component is NaN, all of them are, indicating a NaN time value.
8016   // [value]: the time value.
8017   DECL_ACCESSORS(value, Object)
8018   // [year]: caches year. Either undefined, smi, or NaN.
8019   DECL_ACCESSORS(year, Object)
8020   // [month]: caches month. Either undefined, smi, or NaN.
8021   DECL_ACCESSORS(month, Object)
8022   // [day]: caches day. Either undefined, smi, or NaN.
8023   DECL_ACCESSORS(day, Object)
8024   // [weekday]: caches day of week. Either undefined, smi, or NaN.
8025   DECL_ACCESSORS(weekday, Object)
8026   // [hour]: caches hours. Either undefined, smi, or NaN.
8027   DECL_ACCESSORS(hour, Object)
8028   // [min]: caches minutes. Either undefined, smi, or NaN.
8029   DECL_ACCESSORS(min, Object)
8030   // [sec]: caches seconds. Either undefined, smi, or NaN.
8031   DECL_ACCESSORS(sec, Object)
8032   // [cache stamp]: sample of the date cache stamp at the
8033   // moment when local fields were cached.
8034   DECL_ACCESSORS(cache_stamp, Object)
8035
8036   // Casting.
8037   static inline JSDate* cast(Object* obj);
8038
8039   // Returns the date field with the specified index.
8040   // See FieldIndex for the list of date fields.
8041   static Object* GetField(Object* date, Smi* index);
8042
8043   void SetValue(Object* value, bool is_value_nan);
8044
8045
8046   // Dispatched behavior.
8047   DECLARE_PRINTER(JSDate)
8048   DECLARE_VERIFIER(JSDate)
8049
8050   // The order is important. It must be kept in sync with date macros
8051   // in macros.py.
8052   enum FieldIndex {
8053     kDateValue,
8054     kYear,
8055     kMonth,
8056     kDay,
8057     kWeekday,
8058     kHour,
8059     kMinute,
8060     kSecond,
8061     kFirstUncachedField,
8062     kMillisecond = kFirstUncachedField,
8063     kDays,
8064     kTimeInDay,
8065     kFirstUTCField,
8066     kYearUTC = kFirstUTCField,
8067     kMonthUTC,
8068     kDayUTC,
8069     kWeekdayUTC,
8070     kHourUTC,
8071     kMinuteUTC,
8072     kSecondUTC,
8073     kMillisecondUTC,
8074     kDaysUTC,
8075     kTimeInDayUTC,
8076     kTimezoneOffset
8077   };
8078
8079   // Layout description.
8080   static const int kValueOffset = JSObject::kHeaderSize;
8081   static const int kYearOffset = kValueOffset + kPointerSize;
8082   static const int kMonthOffset = kYearOffset + kPointerSize;
8083   static const int kDayOffset = kMonthOffset + kPointerSize;
8084   static const int kWeekdayOffset = kDayOffset + kPointerSize;
8085   static const int kHourOffset = kWeekdayOffset  + kPointerSize;
8086   static const int kMinOffset = kHourOffset + kPointerSize;
8087   static const int kSecOffset = kMinOffset + kPointerSize;
8088   static const int kCacheStampOffset = kSecOffset + kPointerSize;
8089   static const int kSize = kCacheStampOffset + kPointerSize;
8090
8091  private:
8092   inline Object* DoGetField(FieldIndex index);
8093
8094   Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
8095
8096   // Computes and caches the cacheable fields of the date.
8097   inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
8098
8099
8100   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
8101 };
8102
8103
8104 // Representation of message objects used for error reporting through
8105 // the API. The messages are formatted in JavaScript so this object is
8106 // a real JavaScript object. The information used for formatting the
8107 // error messages are not directly accessible from JavaScript to
8108 // prevent leaking information to user code called during error
8109 // formatting.
8110 class JSMessageObject: public JSObject {
8111  public:
8112   // [type]: the type of error message.
8113   DECL_ACCESSORS(type, String)
8114
8115   // [arguments]: the arguments for formatting the error message.
8116   DECL_ACCESSORS(arguments, JSArray)
8117
8118   // [script]: the script from which the error message originated.
8119   DECL_ACCESSORS(script, Object)
8120
8121   // [stack_frames]: an array of stack frames for this error object.
8122   DECL_ACCESSORS(stack_frames, Object)
8123
8124   // [start_position]: the start position in the script for the error message.
8125   inline int start_position();
8126   inline void set_start_position(int value);
8127
8128   // [end_position]: the end position in the script for the error message.
8129   inline int end_position();
8130   inline void set_end_position(int value);
8131
8132   // Casting.
8133   static inline JSMessageObject* cast(Object* obj);
8134
8135   // Dispatched behavior.
8136   DECLARE_PRINTER(JSMessageObject)
8137   DECLARE_VERIFIER(JSMessageObject)
8138
8139   // Layout description.
8140   static const int kTypeOffset = JSObject::kHeaderSize;
8141   static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8142   static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8143   static const int kStackFramesOffset = kScriptOffset + kPointerSize;
8144   static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8145   static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8146   static const int kSize = kEndPositionOffset + kPointerSize;
8147
8148   typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8149                               kStackFramesOffset + kPointerSize,
8150                               kSize> BodyDescriptor;
8151 };
8152
8153
8154 // Regular expressions
8155 // The regular expression holds a single reference to a FixedArray in
8156 // the kDataOffset field.
8157 // The FixedArray contains the following data:
8158 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8159 // - reference to the original source string
8160 // - reference to the original flag string
8161 // If it is an atom regexp
8162 // - a reference to a literal string to search for
8163 // If it is an irregexp regexp:
8164 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
8165 // used for tracking the last usage (used for code flushing).
8166 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8167 // used for tracking the last usage (used for code flushing)..
8168 // - max number of registers used by irregexp implementations.
8169 // - number of capture registers (output values) of the regexp.
8170 class JSRegExp: public JSObject {
8171  public:
8172   // Meaning of Type:
8173   // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8174   // ATOM: A simple string to match against using an indexOf operation.
8175   // IRREGEXP: Compiled with Irregexp.
8176   // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8177   enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8178   enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
8179
8180   class Flags {
8181    public:
8182     explicit Flags(uint32_t value) : value_(value) { }
8183     bool is_global() { return (value_ & GLOBAL) != 0; }
8184     bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8185     bool is_multiline() { return (value_ & MULTILINE) != 0; }
8186     uint32_t value() { return value_; }
8187    private:
8188     uint32_t value_;
8189   };
8190
8191   DECL_ACCESSORS(data, Object)
8192
8193   inline Type TypeTag();
8194   inline int CaptureCount();
8195   inline Flags GetFlags();
8196   inline String* Pattern();
8197   inline Object* DataAt(int index);
8198   // Set implementation data after the object has been prepared.
8199   inline void SetDataAt(int index, Object* value);
8200
8201   static int code_index(bool is_ascii) {
8202     if (is_ascii) {
8203       return kIrregexpASCIICodeIndex;
8204     } else {
8205       return kIrregexpUC16CodeIndex;
8206     }
8207   }
8208
8209   static int saved_code_index(bool is_ascii) {
8210     if (is_ascii) {
8211       return kIrregexpASCIICodeSavedIndex;
8212     } else {
8213       return kIrregexpUC16CodeSavedIndex;
8214     }
8215   }
8216
8217   static inline JSRegExp* cast(Object* obj);
8218
8219   // Dispatched behavior.
8220   DECLARE_VERIFIER(JSRegExp)
8221
8222   static const int kDataOffset = JSObject::kHeaderSize;
8223   static const int kSize = kDataOffset + kPointerSize;
8224
8225   // Indices in the data array.
8226   static const int kTagIndex = 0;
8227   static const int kSourceIndex = kTagIndex + 1;
8228   static const int kFlagsIndex = kSourceIndex + 1;
8229   static const int kDataIndex = kFlagsIndex + 1;
8230   // The data fields are used in different ways depending on the
8231   // value of the tag.
8232   // Atom regexps (literal strings).
8233   static const int kAtomPatternIndex = kDataIndex;
8234
8235   static const int kAtomDataSize = kAtomPatternIndex + 1;
8236
8237   // Irregexp compiled code or bytecode for ASCII. If compilation
8238   // fails, this fields hold an exception object that should be
8239   // thrown if the regexp is used again.
8240   static const int kIrregexpASCIICodeIndex = kDataIndex;
8241   // Irregexp compiled code or bytecode for UC16.  If compilation
8242   // fails, this fields hold an exception object that should be
8243   // thrown if the regexp is used again.
8244   static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8245
8246   // Saved instance of Irregexp compiled code or bytecode for ASCII that
8247   // is a potential candidate for flushing.
8248   static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
8249   // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8250   // a potential candidate for flushing.
8251   static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8252
8253   // Maximal number of registers used by either ASCII or UC16.
8254   // Only used to check that there is enough stack space
8255   static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8256   // Number of captures in the compiled regexp.
8257   static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8258
8259   static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8260
8261   // Offsets directly into the data fixed array.
8262   static const int kDataTagOffset =
8263       FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8264   static const int kDataAsciiCodeOffset =
8265       FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
8266   static const int kDataUC16CodeOffset =
8267       FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8268   static const int kIrregexpCaptureCountOffset =
8269       FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8270
8271   // In-object fields.
8272   static const int kSourceFieldIndex = 0;
8273   static const int kGlobalFieldIndex = 1;
8274   static const int kIgnoreCaseFieldIndex = 2;
8275   static const int kMultilineFieldIndex = 3;
8276   static const int kLastIndexFieldIndex = 4;
8277   static const int kInObjectFieldCount = 5;
8278
8279   // The uninitialized value for a regexp code object.
8280   static const int kUninitializedValue = -1;
8281
8282   // The compilation error value for the regexp code object. The real error
8283   // object is in the saved code field.
8284   static const int kCompilationErrorValue = -2;
8285
8286   // When we store the sweep generation at which we moved the code from the
8287   // code index to the saved code index we mask it of to be in the [0:255]
8288   // range.
8289   static const int kCodeAgeMask = 0xff;
8290 };
8291
8292
8293 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8294  public:
8295   static inline bool IsMatch(HashTableKey* key, Object* value) {
8296     return key->IsMatch(value);
8297   }
8298
8299   static inline uint32_t Hash(HashTableKey* key) {
8300     return key->Hash();
8301   }
8302
8303   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8304     return key->HashForObject(object);
8305   }
8306
8307   MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8308                                                HashTableKey* key) {
8309     return key->AsObject(heap);
8310   }
8311
8312   static const int kPrefixSize = 0;
8313   static const int kEntrySize = 2;
8314 };
8315
8316
8317 class CompilationCacheTable: public HashTable<CompilationCacheShape,
8318                                               HashTableKey*> {
8319  public:
8320   // Find cached value for a string key, otherwise return null.
8321   Object* Lookup(String* src, Context* context);
8322   Object* LookupEval(String* src,
8323                      Context* context,
8324                      StrictMode strict_mode,
8325                      int scope_position);
8326   Object* LookupRegExp(String* source, JSRegExp::Flags flags);
8327   MUST_USE_RESULT MaybeObject* Put(String* src,
8328                                    Context* context,
8329                                    Object* value);
8330   MUST_USE_RESULT MaybeObject* PutEval(String* src,
8331                                        Context* context,
8332                                        SharedFunctionInfo* value,
8333                                        int scope_position);
8334   MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
8335                                          JSRegExp::Flags flags,
8336                                          FixedArray* value);
8337
8338   // Remove given value from cache.
8339   void Remove(Object* value);
8340
8341   static inline CompilationCacheTable* cast(Object* obj);
8342
8343  private:
8344   DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8345 };
8346
8347
8348 class CodeCache: public Struct {
8349  public:
8350   DECL_ACCESSORS(default_cache, FixedArray)
8351   DECL_ACCESSORS(normal_type_cache, Object)
8352
8353   // Add the code object to the cache.
8354   MUST_USE_RESULT MaybeObject* Update(Name* name, Code* code);
8355
8356   // Lookup code object in the cache. Returns code object if found and undefined
8357   // if not.
8358   Object* Lookup(Name* name, Code::Flags flags);
8359
8360   // Get the internal index of a code object in the cache. Returns -1 if the
8361   // code object is not in that cache. This index can be used to later call
8362   // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8363   // RemoveByIndex.
8364   int GetIndex(Object* name, Code* code);
8365
8366   // Remove an object from the cache with the provided internal index.
8367   void RemoveByIndex(Object* name, Code* code, int index);
8368
8369   static inline CodeCache* cast(Object* obj);
8370
8371   // Dispatched behavior.
8372   DECLARE_PRINTER(CodeCache)
8373   DECLARE_VERIFIER(CodeCache)
8374
8375   static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8376   static const int kNormalTypeCacheOffset =
8377       kDefaultCacheOffset + kPointerSize;
8378   static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8379
8380  private:
8381   MUST_USE_RESULT MaybeObject* UpdateDefaultCache(Name* name, Code* code);
8382   MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(Name* name, Code* code);
8383   Object* LookupDefaultCache(Name* name, Code::Flags flags);
8384   Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8385
8386   // Code cache layout of the default cache. Elements are alternating name and
8387   // code objects for non normal load/store/call IC's.
8388   static const int kCodeCacheEntrySize = 2;
8389   static const int kCodeCacheEntryNameOffset = 0;
8390   static const int kCodeCacheEntryCodeOffset = 1;
8391
8392   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8393 };
8394
8395
8396 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8397  public:
8398   static inline bool IsMatch(HashTableKey* key, Object* value) {
8399     return key->IsMatch(value);
8400   }
8401
8402   static inline uint32_t Hash(HashTableKey* key) {
8403     return key->Hash();
8404   }
8405
8406   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8407     return key->HashForObject(object);
8408   }
8409
8410   MUST_USE_RESULT static MaybeObject* AsObject(Heap* heap,
8411                                                HashTableKey* key) {
8412     return key->AsObject(heap);
8413   }
8414
8415   static const int kPrefixSize = 0;
8416   static const int kEntrySize = 2;
8417 };
8418
8419
8420 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
8421                                            HashTableKey*> {
8422  public:
8423   Object* Lookup(Name* name, Code::Flags flags);
8424   MUST_USE_RESULT MaybeObject* Put(Name* name, Code* code);
8425
8426   int GetIndex(Name* name, Code::Flags flags);
8427   void RemoveByIndex(int index);
8428
8429   static inline CodeCacheHashTable* cast(Object* obj);
8430
8431   // Initial size of the fixed array backing the hash table.
8432   static const int kInitialSize = 64;
8433
8434  private:
8435   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8436 };
8437
8438
8439 class PolymorphicCodeCache: public Struct {
8440  public:
8441   DECL_ACCESSORS(cache, Object)
8442
8443   static void Update(Handle<PolymorphicCodeCache> cache,
8444                      MapHandleList* maps,
8445                      Code::Flags flags,
8446                      Handle<Code> code);
8447
8448   MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
8449                                       Code::Flags flags,
8450                                       Code* code);
8451
8452   // Returns an undefined value if the entry is not found.
8453   Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8454
8455   static inline PolymorphicCodeCache* cast(Object* obj);
8456
8457   // Dispatched behavior.
8458   DECLARE_PRINTER(PolymorphicCodeCache)
8459   DECLARE_VERIFIER(PolymorphicCodeCache)
8460
8461   static const int kCacheOffset = HeapObject::kHeaderSize;
8462   static const int kSize = kCacheOffset + kPointerSize;
8463
8464  private:
8465   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8466 };
8467
8468
8469 class PolymorphicCodeCacheHashTable
8470     : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
8471  public:
8472   Object* Lookup(MapHandleList* maps, int code_kind);
8473
8474   MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
8475                                    int code_kind,
8476                                    Code* code);
8477
8478   static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
8479
8480   static const int kInitialSize = 64;
8481  private:
8482   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8483 };
8484
8485
8486 class TypeFeedbackInfo: public Struct {
8487  public:
8488   inline int ic_total_count();
8489   inline void set_ic_total_count(int count);
8490
8491   inline int ic_with_type_info_count();
8492   inline void change_ic_with_type_info_count(int count);
8493
8494   inline void initialize_storage();
8495
8496   inline void change_own_type_change_checksum();
8497   inline int own_type_change_checksum();
8498
8499   inline void set_inlined_type_change_checksum(int checksum);
8500   inline bool matches_inlined_type_change_checksum(int checksum);
8501
8502   DECL_ACCESSORS(feedback_vector, FixedArray)
8503
8504   static inline TypeFeedbackInfo* cast(Object* obj);
8505
8506   // Dispatched behavior.
8507   DECLARE_PRINTER(TypeFeedbackInfo)
8508   DECLARE_VERIFIER(TypeFeedbackInfo)
8509
8510   static const int kStorage1Offset = HeapObject::kHeaderSize;
8511   static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8512   static const int kFeedbackVectorOffset =
8513       kStorage2Offset + kPointerSize;
8514   static const int kSize = kFeedbackVectorOffset + kPointerSize;
8515
8516   // The object that indicates an uninitialized cache.
8517   static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
8518
8519   // The object that indicates a megamorphic state.
8520   static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
8521
8522   // The object that indicates a monomorphic state of Array with
8523   // ElementsKind
8524   static inline Handle<Object> MonomorphicArraySentinel(Isolate* isolate,
8525       ElementsKind elements_kind);
8526
8527   // A raw version of the uninitialized sentinel that's safe to read during
8528   // garbage collection (e.g., for patching the cache).
8529   static inline Object* RawUninitializedSentinel(Heap* heap);
8530
8531   static const int kForInFastCaseMarker = 0;
8532   static const int kForInSlowCaseMarker = 1;
8533
8534  private:
8535   static const int kTypeChangeChecksumBits = 7;
8536
8537   class ICTotalCountField: public BitField<int, 0,
8538       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8539   class OwnTypeChangeChecksum: public BitField<int,
8540       kSmiValueSize - kTypeChangeChecksumBits,
8541       kTypeChangeChecksumBits> {};  // NOLINT
8542   class ICsWithTypeInfoCountField: public BitField<int, 0,
8543       kSmiValueSize - kTypeChangeChecksumBits> {};  // NOLINT
8544   class InlinedTypeChangeChecksum: public BitField<int,
8545       kSmiValueSize - kTypeChangeChecksumBits,
8546       kTypeChangeChecksumBits> {};  // NOLINT
8547
8548   DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8549 };
8550
8551
8552 enum AllocationSiteMode {
8553   DONT_TRACK_ALLOCATION_SITE,
8554   TRACK_ALLOCATION_SITE,
8555   LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8556 };
8557
8558
8559 class AllocationSite: public Struct {
8560  public:
8561   static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8562   static const double kPretenureRatio;
8563   static const int kPretenureMinimumCreated = 100;
8564
8565   // Values for pretenure decision field.
8566   enum PretenureDecision {
8567     kUndecided = 0,
8568     kDontTenure = 1,
8569     kTenure = 2,
8570     kZombie = 3,
8571     kLastPretenureDecisionValue = kZombie
8572   };
8573
8574   DECL_ACCESSORS(transition_info, Object)
8575   // nested_site threads a list of sites that represent nested literals
8576   // walked in a particular order. So [[1, 2], 1, 2] will have one
8577   // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8578   DECL_ACCESSORS(nested_site, Object)
8579   DECL_ACCESSORS(pretenure_data, Smi)
8580   DECL_ACCESSORS(pretenure_create_count, Smi)
8581   DECL_ACCESSORS(dependent_code, DependentCode)
8582   DECL_ACCESSORS(weak_next, Object)
8583
8584   inline void Initialize();
8585
8586   // This method is expensive, it should only be called for reporting.
8587   bool IsNestedSite();
8588
8589   // transition_info bitfields, for constructed array transition info.
8590   class ElementsKindBits:       public BitField<ElementsKind, 0,  15> {};
8591   class UnusedBits:             public BitField<int,          15, 14> {};
8592   class DoNotInlineBit:         public BitField<bool,         29,  1> {};
8593
8594   // Bitfields for pretenure_data
8595   class MementoFoundCountBits:  public BitField<int,               0, 27> {};
8596   class PretenureDecisionBits:  public BitField<PretenureDecision, 27, 2> {};
8597   class DeoptDependentCodeBit:  public BitField<bool,              29, 1> {};
8598   STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8599
8600   // Increments the mementos found counter and returns true when the first
8601   // memento was found for a given allocation site.
8602   inline bool IncrementMementoFoundCount();
8603
8604   inline void IncrementMementoCreateCount();
8605
8606   PretenureFlag GetPretenureMode();
8607
8608   void ResetPretenureDecision();
8609
8610   PretenureDecision pretenure_decision() {
8611     int value = pretenure_data()->value();
8612     return PretenureDecisionBits::decode(value);
8613   }
8614
8615   void set_pretenure_decision(PretenureDecision decision) {
8616     int value = pretenure_data()->value();
8617     set_pretenure_data(
8618         Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8619         SKIP_WRITE_BARRIER);
8620   }
8621
8622   bool deopt_dependent_code() {
8623     int value = pretenure_data()->value();
8624     return DeoptDependentCodeBit::decode(value);
8625   }
8626
8627   void set_deopt_dependent_code(bool deopt) {
8628     int value = pretenure_data()->value();
8629     set_pretenure_data(
8630         Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8631         SKIP_WRITE_BARRIER);
8632   }
8633
8634   int memento_found_count() {
8635     int value = pretenure_data()->value();
8636     return MementoFoundCountBits::decode(value);
8637   }
8638
8639   inline void set_memento_found_count(int count);
8640
8641   int memento_create_count() {
8642     return pretenure_create_count()->value();
8643   }
8644
8645   void set_memento_create_count(int count) {
8646     set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8647   }
8648
8649   // The pretenuring decision is made during gc, and the zombie state allows
8650   // us to recognize when an allocation site is just being kept alive because
8651   // a later traversal of new space may discover AllocationMementos that point
8652   // to this AllocationSite.
8653   bool IsZombie() {
8654     return pretenure_decision() == kZombie;
8655   }
8656
8657   inline void MarkZombie();
8658
8659   inline bool DigestPretenuringFeedback();
8660
8661   ElementsKind GetElementsKind() {
8662     ASSERT(!SitePointsToLiteral());
8663     int value = Smi::cast(transition_info())->value();
8664     return ElementsKindBits::decode(value);
8665   }
8666
8667   void SetElementsKind(ElementsKind kind) {
8668     int value = Smi::cast(transition_info())->value();
8669     set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8670                         SKIP_WRITE_BARRIER);
8671   }
8672
8673   bool CanInlineCall() {
8674     int value = Smi::cast(transition_info())->value();
8675     return DoNotInlineBit::decode(value) == 0;
8676   }
8677
8678   void SetDoNotInlineCall() {
8679     int value = Smi::cast(transition_info())->value();
8680     set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8681                         SKIP_WRITE_BARRIER);
8682   }
8683
8684   bool SitePointsToLiteral() {
8685     // If transition_info is a smi, then it represents an ElementsKind
8686     // for a constructed array. Otherwise, it must be a boilerplate
8687     // for an object or array literal.
8688     return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8689   }
8690
8691   static void DigestTransitionFeedback(Handle<AllocationSite> site,
8692                                        ElementsKind to_kind);
8693
8694   enum Reason {
8695     TENURING,
8696     TRANSITIONS
8697   };
8698
8699   static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8700                                           Reason reason,
8701                                           CompilationInfo* info);
8702
8703   DECLARE_PRINTER(AllocationSite)
8704   DECLARE_VERIFIER(AllocationSite)
8705
8706   static inline AllocationSite* cast(Object* obj);
8707   static inline AllocationSiteMode GetMode(
8708       ElementsKind boilerplate_elements_kind);
8709   static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8710   static inline bool CanTrack(InstanceType type);
8711
8712   static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8713   static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8714   static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8715   static const int kPretenureCreateCountOffset =
8716       kPretenureDataOffset + kPointerSize;
8717   static const int kDependentCodeOffset =
8718       kPretenureCreateCountOffset + kPointerSize;
8719   static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8720   static const int kSize = kWeakNextOffset + kPointerSize;
8721
8722   // During mark compact we need to take special care for the dependent code
8723   // field.
8724   static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8725   static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8726
8727   // For other visitors, use the fixed body descriptor below.
8728   typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8729                               kDependentCodeOffset + kPointerSize,
8730                               kSize> BodyDescriptor;
8731
8732  private:
8733   inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8734   bool PretenuringDecisionMade() {
8735     return pretenure_decision() != kUndecided;
8736   }
8737
8738   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8739 };
8740
8741
8742 class AllocationMemento: public Struct {
8743  public:
8744   static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8745   static const int kSize = kAllocationSiteOffset + kPointerSize;
8746
8747   DECL_ACCESSORS(allocation_site, Object)
8748
8749   bool IsValid() {
8750     return allocation_site()->IsAllocationSite() &&
8751         !AllocationSite::cast(allocation_site())->IsZombie();
8752   }
8753   AllocationSite* GetAllocationSite() {
8754     ASSERT(IsValid());
8755     return AllocationSite::cast(allocation_site());
8756   }
8757
8758   DECLARE_PRINTER(AllocationMemento)
8759   DECLARE_VERIFIER(AllocationMemento)
8760
8761   static inline AllocationMemento* cast(Object* obj);
8762
8763  private:
8764   DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8765 };
8766
8767
8768 // Representation of a slow alias as part of a sloppy arguments objects.
8769 // For fast aliases (if HasSloppyArgumentsElements()):
8770 // - the parameter map contains an index into the context
8771 // - all attributes of the element have default values
8772 // For slow aliases (if HasDictionaryArgumentsElements()):
8773 // - the parameter map contains no fast alias mapping (i.e. the hole)
8774 // - this struct (in the slow backing store) contains an index into the context
8775 // - all attributes are available as part if the property details
8776 class AliasedArgumentsEntry: public Struct {
8777  public:
8778   inline int aliased_context_slot();
8779   inline void set_aliased_context_slot(int count);
8780
8781   static inline AliasedArgumentsEntry* cast(Object* obj);
8782
8783   // Dispatched behavior.
8784   DECLARE_PRINTER(AliasedArgumentsEntry)
8785   DECLARE_VERIFIER(AliasedArgumentsEntry)
8786
8787   static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8788   static const int kSize = kAliasedContextSlot + kPointerSize;
8789
8790  private:
8791   DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8792 };
8793
8794
8795 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8796 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8797
8798
8799 class StringHasher {
8800  public:
8801   explicit inline StringHasher(int length, uint32_t seed);
8802
8803   template <typename schar>
8804   static inline uint32_t HashSequentialString(const schar* chars,
8805                                               int length,
8806                                               uint32_t seed);
8807
8808   // Reads all the data, even for long strings and computes the utf16 length.
8809   static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8810                                   uint32_t seed,
8811                                   int* utf16_length_out);
8812
8813   // Calculated hash value for a string consisting of 1 to
8814   // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8815   // value is represented decimal value.
8816   static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8817
8818   // No string is allowed to have a hash of zero.  That value is reserved
8819   // for internal properties.  If the hash calculation yields zero then we
8820   // use 27 instead.
8821   static const int kZeroHash = 27;
8822
8823   // Reusable parts of the hashing algorithm.
8824   INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8825   INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8826
8827  protected:
8828   // Returns the value to store in the hash field of a string with
8829   // the given length and contents.
8830   uint32_t GetHashField();
8831   // Returns true if the hash of this string can be computed without
8832   // looking at the contents.
8833   inline bool has_trivial_hash();
8834   // Adds a block of characters to the hash.
8835   template<typename Char>
8836   inline void AddCharacters(const Char* chars, int len);
8837
8838  private:
8839   // Add a character to the hash.
8840   inline void AddCharacter(uint16_t c);
8841   // Update index. Returns true if string is still an index.
8842   inline bool UpdateIndex(uint16_t c);
8843
8844   int length_;
8845   uint32_t raw_running_hash_;
8846   uint32_t array_index_;
8847   bool is_array_index_;
8848   bool is_first_char_;
8849   DISALLOW_COPY_AND_ASSIGN(StringHasher);
8850 };
8851
8852
8853 // The characteristics of a string are stored in its map.  Retrieving these
8854 // few bits of information is moderately expensive, involving two memory
8855 // loads where the second is dependent on the first.  To improve efficiency
8856 // the shape of the string is given its own class so that it can be retrieved
8857 // once and used for several string operations.  A StringShape is small enough
8858 // to be passed by value and is immutable, but be aware that flattening a
8859 // string can potentially alter its shape.  Also be aware that a GC caused by
8860 // something else can alter the shape of a string due to ConsString
8861 // shortcutting.  Keeping these restrictions in mind has proven to be error-
8862 // prone and so we no longer put StringShapes in variables unless there is a
8863 // concrete performance benefit at that particular point in the code.
8864 class StringShape BASE_EMBEDDED {
8865  public:
8866   inline explicit StringShape(String* s);
8867   inline explicit StringShape(Map* s);
8868   inline explicit StringShape(InstanceType t);
8869   inline bool IsSequential();
8870   inline bool IsExternal();
8871   inline bool IsCons();
8872   inline bool IsSliced();
8873   inline bool IsIndirect();
8874   inline bool IsExternalAscii();
8875   inline bool IsExternalTwoByte();
8876   inline bool IsSequentialAscii();
8877   inline bool IsSequentialTwoByte();
8878   inline bool IsInternalized();
8879   inline StringRepresentationTag representation_tag();
8880   inline uint32_t encoding_tag();
8881   inline uint32_t full_representation_tag();
8882   inline uint32_t size_tag();
8883 #ifdef DEBUG
8884   inline uint32_t type() { return type_; }
8885   inline void invalidate() { valid_ = false; }
8886   inline bool valid() { return valid_; }
8887 #else
8888   inline void invalidate() { }
8889 #endif
8890
8891  private:
8892   uint32_t type_;
8893 #ifdef DEBUG
8894   inline void set_valid() { valid_ = true; }
8895   bool valid_;
8896 #else
8897   inline void set_valid() { }
8898 #endif
8899 };
8900
8901
8902 // The Name abstract class captures anything that can be used as a property
8903 // name, i.e., strings and symbols.  All names store a hash value.
8904 class Name: public HeapObject {
8905  public:
8906   // Get and set the hash field of the name.
8907   inline uint32_t hash_field();
8908   inline void set_hash_field(uint32_t value);
8909
8910   // Tells whether the hash code has been computed.
8911   inline bool HasHashCode();
8912
8913   // Returns a hash value used for the property table
8914   inline uint32_t Hash();
8915
8916   // Equality operations.
8917   inline bool Equals(Name* other);
8918
8919   // Conversion.
8920   inline bool AsArrayIndex(uint32_t* index);
8921
8922   // Casting.
8923   static inline Name* cast(Object* obj);
8924
8925   bool IsCacheable(Isolate* isolate);
8926
8927   DECLARE_PRINTER(Name)
8928
8929   // Layout description.
8930   static const int kHashFieldOffset = HeapObject::kHeaderSize;
8931   static const int kSize = kHashFieldOffset + kPointerSize;
8932
8933   // Mask constant for checking if a name has a computed hash code
8934   // and if it is a string that is an array index.  The least significant bit
8935   // indicates whether a hash code has been computed.  If the hash code has
8936   // been computed the 2nd bit tells whether the string can be used as an
8937   // array index.
8938   static const int kHashNotComputedMask = 1;
8939   static const int kIsNotArrayIndexMask = 1 << 1;
8940   static const int kNofHashBitFields = 2;
8941
8942   // Shift constant retrieving hash code from hash field.
8943   static const int kHashShift = kNofHashBitFields;
8944
8945   // Only these bits are relevant in the hash, since the top two are shifted
8946   // out.
8947   static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8948
8949   // Array index strings this short can keep their index in the hash field.
8950   static const int kMaxCachedArrayIndexLength = 7;
8951
8952   // For strings which are array indexes the hash value has the string length
8953   // mixed into the hash, mainly to avoid a hash value of zero which would be
8954   // the case for the string '0'. 24 bits are used for the array index value.
8955   static const int kArrayIndexValueBits = 24;
8956   static const int kArrayIndexLengthBits =
8957       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8958
8959   STATIC_CHECK((kArrayIndexLengthBits > 0));
8960
8961   static const int kArrayIndexHashLengthShift =
8962       kArrayIndexValueBits + kNofHashBitFields;
8963
8964   static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
8965
8966   static const int kArrayIndexValueMask =
8967       ((1 << kArrayIndexValueBits) - 1) << kHashShift;
8968
8969   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8970   // could use a mask to test if the length of string is less than or equal to
8971   // kMaxCachedArrayIndexLength.
8972   STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8973
8974   static const unsigned int kContainsCachedArrayIndexMask =
8975       (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
8976       kIsNotArrayIndexMask;
8977
8978   // Value of empty hash field indicating that the hash is not computed.
8979   static const int kEmptyHashField =
8980       kIsNotArrayIndexMask | kHashNotComputedMask;
8981
8982  protected:
8983   static inline bool IsHashFieldComputed(uint32_t field);
8984
8985  private:
8986   DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8987 };
8988
8989
8990 // ES6 symbols.
8991 class Symbol: public Name {
8992  public:
8993   // [name]: the print name of a symbol, or undefined if none.
8994   DECL_ACCESSORS(name, Object)
8995
8996   DECL_ACCESSORS(flags, Smi)
8997
8998   // [is_private]: whether this is a private symbol.
8999   DECL_BOOLEAN_ACCESSORS(is_private)
9000
9001   // Casting.
9002   static inline Symbol* cast(Object* obj);
9003
9004   // Dispatched behavior.
9005   DECLARE_PRINTER(Symbol)
9006   DECLARE_VERIFIER(Symbol)
9007
9008   // Layout description.
9009   static const int kNameOffset = Name::kSize;
9010   static const int kFlagsOffset = kNameOffset + kPointerSize;
9011   static const int kSize = kFlagsOffset + kPointerSize;
9012
9013   typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
9014
9015  private:
9016   static const int kPrivateBit = 0;
9017
9018   DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
9019 };
9020
9021
9022 class ConsString;
9023
9024 // The String abstract class captures JavaScript string values:
9025 //
9026 // Ecma-262:
9027 //  4.3.16 String Value
9028 //    A string value is a member of the type String and is a finite
9029 //    ordered sequence of zero or more 16-bit unsigned integer values.
9030 //
9031 // All string values have a length field.
9032 class String: public Name {
9033  public:
9034   enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
9035
9036   // Representation of the flat content of a String.
9037   // A non-flat string doesn't have flat content.
9038   // A flat string has content that's encoded as a sequence of either
9039   // ASCII chars or two-byte UC16.
9040   // Returned by String::GetFlatContent().
9041   class FlatContent {
9042    public:
9043     // Returns true if the string is flat and this structure contains content.
9044     bool IsFlat() { return state_ != NON_FLAT; }
9045     // Returns true if the structure contains ASCII content.
9046     bool IsAscii() { return state_ == ASCII; }
9047     // Returns true if the structure contains two-byte content.
9048     bool IsTwoByte() { return state_ == TWO_BYTE; }
9049
9050     // Return the one byte content of the string. Only use if IsAscii() returns
9051     // true.
9052     Vector<const uint8_t> ToOneByteVector() {
9053       ASSERT_EQ(ASCII, state_);
9054       return buffer_;
9055     }
9056     // Return the two-byte content of the string. Only use if IsTwoByte()
9057     // returns true.
9058     Vector<const uc16> ToUC16Vector() {
9059       ASSERT_EQ(TWO_BYTE, state_);
9060       return Vector<const uc16>::cast(buffer_);
9061     }
9062
9063    private:
9064     enum State { NON_FLAT, ASCII, TWO_BYTE };
9065
9066     // Constructors only used by String::GetFlatContent().
9067     explicit FlatContent(Vector<const uint8_t> chars)
9068         : buffer_(chars),
9069           state_(ASCII) { }
9070     explicit FlatContent(Vector<const uc16> chars)
9071         : buffer_(Vector<const byte>::cast(chars)),
9072           state_(TWO_BYTE) { }
9073     FlatContent() : buffer_(), state_(NON_FLAT) { }
9074
9075     Vector<const uint8_t> buffer_;
9076     State state_;
9077
9078     friend class String;
9079   };
9080
9081   // Get and set the length of the string.
9082   inline int length();
9083   inline void set_length(int value);
9084
9085   // Returns whether this string has only ASCII chars, i.e. all of them can
9086   // be ASCII encoded.  This might be the case even if the string is
9087   // two-byte.  Such strings may appear when the embedder prefers
9088   // two-byte external representations even for ASCII data.
9089   inline bool IsOneByteRepresentation();
9090   inline bool IsTwoByteRepresentation();
9091
9092   // Cons and slices have an encoding flag that may not represent the actual
9093   // encoding of the underlying string.  This is taken into account here.
9094   // Requires: this->IsFlat()
9095   inline bool IsOneByteRepresentationUnderneath();
9096   inline bool IsTwoByteRepresentationUnderneath();
9097
9098   // NOTE: this should be considered only a hint.  False negatives are
9099   // possible.
9100   inline bool HasOnlyOneByteChars();
9101
9102   // Get and set individual two byte chars in the string.
9103   inline void Set(int index, uint16_t value);
9104   // Get individual two byte char in the string.  Repeated calls
9105   // to this method are not efficient unless the string is flat.
9106   INLINE(uint16_t Get(int index));
9107
9108   // Try to flatten the string.  Checks first inline to see if it is
9109   // necessary.  Does nothing if the string is not a cons string.
9110   // Flattening allocates a sequential string with the same data as
9111   // the given string and mutates the cons string to a degenerate
9112   // form, where the first component is the new sequential string and
9113   // the second component is the empty string.  If allocation fails,
9114   // this function returns a failure.  If flattening succeeds, this
9115   // function returns the sequential string that is now the first
9116   // component of the cons string.
9117   //
9118   // Degenerate cons strings are handled specially by the garbage
9119   // collector (see IsShortcutCandidate).
9120   //
9121   // Use FlattenString from Handles.cc to flatten even in case an
9122   // allocation failure happens.
9123   inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
9124
9125   // Convenience function.  Has exactly the same behavior as
9126   // TryFlatten(), except in the case of failure returns the original
9127   // string.
9128   inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
9129
9130   // Tries to return the content of a flat string as a structure holding either
9131   // a flat vector of char or of uc16.
9132   // If the string isn't flat, and therefore doesn't have flat content, the
9133   // returned structure will report so, and can't provide a vector of either
9134   // kind.
9135   FlatContent GetFlatContent();
9136
9137   // Returns the parent of a sliced string or first part of a flat cons string.
9138   // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9139   inline String* GetUnderlying();
9140
9141   // Mark the string as an undetectable object. It only applies to
9142   // ASCII and two byte string types.
9143   bool MarkAsUndetectable();
9144
9145   // String equality operations.
9146   inline bool Equals(String* other);
9147   bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9148   bool IsOneByteEqualTo(Vector<const uint8_t> str);
9149   bool IsTwoByteEqualTo(Vector<const uc16> str);
9150
9151   // Return a UTF8 representation of the string.  The string is null
9152   // terminated but may optionally contain nulls.  Length is returned
9153   // in length_output if length_output is not a null pointer  The string
9154   // should be nearly flat, otherwise the performance of this method may
9155   // be very slow (quadratic in the length).  Setting robustness_flag to
9156   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9157   // handles unexpected data without causing assert failures and it does not
9158   // do any heap allocations.  This is useful when printing stack traces.
9159   SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9160                                     RobustnessFlag robustness_flag,
9161                                     int offset,
9162                                     int length,
9163                                     int* length_output = 0);
9164   SmartArrayPointer<char> ToCString(
9165       AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9166       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9167       int* length_output = 0);
9168
9169   // Return a 16 bit Unicode representation of the string.
9170   // The string should be nearly flat, otherwise the performance of
9171   // of this method may be very bad.  Setting robustness_flag to
9172   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
9173   // handles unexpected data without causing assert failures and it does not
9174   // do any heap allocations.  This is useful when printing stack traces.
9175   SmartArrayPointer<uc16> ToWideCString(
9176       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9177
9178   bool ComputeArrayIndex(uint32_t* index);
9179
9180   // Externalization.
9181   bool MakeExternal(v8::String::ExternalStringResource* resource);
9182   bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
9183
9184   // Conversion.
9185   inline bool AsArrayIndex(uint32_t* index);
9186
9187   // Casting.
9188   static inline String* cast(Object* obj);
9189
9190   void PrintOn(FILE* out);
9191
9192   // For use during stack traces.  Performs rudimentary sanity check.
9193   bool LooksValid();
9194
9195   // Dispatched behavior.
9196   void StringShortPrint(StringStream* accumulator);
9197 #ifdef OBJECT_PRINT
9198   char* ToAsciiArray();
9199 #endif
9200   DECLARE_PRINTER(String)
9201   DECLARE_VERIFIER(String)
9202
9203   inline bool IsFlat();
9204
9205   // Layout description.
9206   static const int kLengthOffset = Name::kSize;
9207   static const int kSize = kLengthOffset + kPointerSize;
9208
9209   // Maximum number of characters to consider when trying to convert a string
9210   // value into an array index.
9211   static const int kMaxArrayIndexSize = 10;
9212   STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9213
9214   // Max char codes.
9215   static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9216   static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9217   static const int kMaxUtf16CodeUnit = 0xffff;
9218
9219   // Value of hash field containing computed hash equal to zero.
9220   static const int kEmptyStringHash = kIsNotArrayIndexMask;
9221
9222   // Maximal string length.
9223   static const int kMaxLength = (1 << 28) - 16;
9224
9225   // Max length for computing hash. For strings longer than this limit the
9226   // string length is used as the hash value.
9227   static const int kMaxHashCalcLength = 16383;
9228
9229   // Limit for truncation in short printing.
9230   static const int kMaxShortPrintLength = 1024;
9231
9232   // Support for regular expressions.
9233   const uc16* GetTwoByteData(unsigned start);
9234
9235   // Helper function for flattening strings.
9236   template <typename sinkchar>
9237   static void WriteToFlat(String* source,
9238                           sinkchar* sink,
9239                           int from,
9240                           int to);
9241
9242   // The return value may point to the first aligned word containing the
9243   // first non-ascii character, rather than directly to the non-ascii character.
9244   // If the return value is >= the passed length, the entire string was ASCII.
9245   static inline int NonAsciiStart(const char* chars, int length) {
9246     const char* start = chars;
9247     const char* limit = chars + length;
9248 #ifdef V8_HOST_CAN_READ_UNALIGNED
9249     ASSERT(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9250     const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9251     while (chars + sizeof(uintptr_t) <= limit) {
9252       if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
9253         return static_cast<int>(chars - start);
9254       }
9255       chars += sizeof(uintptr_t);
9256     }
9257 #endif
9258     while (chars < limit) {
9259       if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9260         return static_cast<int>(chars - start);
9261       }
9262       ++chars;
9263     }
9264     return static_cast<int>(chars - start);
9265   }
9266
9267   static inline bool IsAscii(const char* chars, int length) {
9268     return NonAsciiStart(chars, length) >= length;
9269   }
9270
9271   static inline bool IsAscii(const uint8_t* chars, int length) {
9272     return
9273         NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9274   }
9275
9276   static inline int NonOneByteStart(const uc16* chars, int length) {
9277     const uc16* limit = chars + length;
9278     const uc16* start = chars;
9279     while (chars < limit) {
9280       if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9281       ++chars;
9282     }
9283     return static_cast<int>(chars - start);
9284   }
9285
9286   static inline bool IsOneByte(const uc16* chars, int length) {
9287     return NonOneByteStart(chars, length) >= length;
9288   }
9289
9290   // TODO(dcarney): Replace all instances of this with VisitFlat.
9291   template<class Visitor, class ConsOp>
9292   static inline void Visit(String* string,
9293                            unsigned offset,
9294                            Visitor& visitor,
9295                            ConsOp& cons_op,
9296                            int32_t type,
9297                            unsigned length);
9298
9299   template<class Visitor>
9300   static inline ConsString* VisitFlat(Visitor* visitor,
9301                                       String* string,
9302                                       int offset,
9303                                       int length,
9304                                       int32_t type);
9305
9306   template<class Visitor>
9307   static inline ConsString* VisitFlat(Visitor* visitor,
9308                                       String* string,
9309                                       int offset = 0) {
9310     int32_t type = string->map()->instance_type();
9311     return VisitFlat(visitor, string, offset, string->length(), type);
9312   }
9313
9314  private:
9315   friend class Name;
9316
9317   // Try to flatten the top level ConsString that is hiding behind this
9318   // string.  This is a no-op unless the string is a ConsString.  Flatten
9319   // mutates the ConsString and might return a failure.
9320   MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
9321
9322   // Slow case of String::Equals.  This implementation works on any strings
9323   // but it is most efficient on strings that are almost flat.
9324   bool SlowEquals(String* other);
9325
9326   // Slow case of AsArrayIndex.
9327   bool SlowAsArrayIndex(uint32_t* index);
9328
9329   // Compute and set the hash code.
9330   uint32_t ComputeAndSetHash();
9331
9332   DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9333 };
9334
9335
9336 // The SeqString abstract class captures sequential string values.
9337 class SeqString: public String {
9338  public:
9339   // Casting.
9340   static inline SeqString* cast(Object* obj);
9341
9342   // Layout description.
9343   static const int kHeaderSize = String::kSize;
9344
9345   // Truncate the string in-place if possible and return the result.
9346   // In case of new_length == 0, the empty string is returned without
9347   // truncating the original string.
9348   MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9349                                                  int new_length);
9350  private:
9351   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9352 };
9353
9354
9355 // The AsciiString class captures sequential ASCII string objects.
9356 // Each character in the AsciiString is an ASCII character.
9357 class SeqOneByteString: public SeqString {
9358  public:
9359   static const bool kHasAsciiEncoding = true;
9360
9361   // Dispatched behavior.
9362   inline uint16_t SeqOneByteStringGet(int index);
9363   inline void SeqOneByteStringSet(int index, uint16_t value);
9364
9365   // Get the address of the characters in this string.
9366   inline Address GetCharsAddress();
9367
9368   inline uint8_t* GetChars();
9369
9370   // Casting
9371   static inline SeqOneByteString* cast(Object* obj);
9372
9373   // Garbage collection support.  This method is called by the
9374   // garbage collector to compute the actual size of an AsciiString
9375   // instance.
9376   inline int SeqOneByteStringSize(InstanceType instance_type);
9377
9378   // Computes the size for an AsciiString instance of a given length.
9379   static int SizeFor(int length) {
9380     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9381   }
9382
9383   // Maximal memory usage for a single sequential ASCII string.
9384   static const int kMaxSize = 512 * MB - 1;
9385   STATIC_CHECK((kMaxSize - kHeaderSize) >= String::kMaxLength);
9386
9387  private:
9388   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9389 };
9390
9391
9392 // The TwoByteString class captures sequential unicode string objects.
9393 // Each character in the TwoByteString is a two-byte uint16_t.
9394 class SeqTwoByteString: public SeqString {
9395  public:
9396   static const bool kHasAsciiEncoding = false;
9397
9398   // Dispatched behavior.
9399   inline uint16_t SeqTwoByteStringGet(int index);
9400   inline void SeqTwoByteStringSet(int index, uint16_t value);
9401
9402   // Get the address of the characters in this string.
9403   inline Address GetCharsAddress();
9404
9405   inline uc16* GetChars();
9406
9407   // For regexp code.
9408   const uint16_t* SeqTwoByteStringGetData(unsigned start);
9409
9410   // Casting
9411   static inline SeqTwoByteString* cast(Object* obj);
9412
9413   // Garbage collection support.  This method is called by the
9414   // garbage collector to compute the actual size of a TwoByteString
9415   // instance.
9416   inline int SeqTwoByteStringSize(InstanceType instance_type);
9417
9418   // Computes the size for a TwoByteString instance of a given length.
9419   static int SizeFor(int length) {
9420     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9421   }
9422
9423   // Maximal memory usage for a single sequential two-byte string.
9424   static const int kMaxSize = 512 * MB - 1;
9425   STATIC_CHECK(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9426                String::kMaxLength);
9427
9428  private:
9429   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9430 };
9431
9432
9433 // The ConsString class describes string values built by using the
9434 // addition operator on strings.  A ConsString is a pair where the
9435 // first and second components are pointers to other string values.
9436 // One or both components of a ConsString can be pointers to other
9437 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9438 // are non-ConsString string values.  The string value represented by
9439 // a ConsString can be obtained by concatenating the leaf string
9440 // values in a left-to-right depth-first traversal of the tree.
9441 class ConsString: public String {
9442  public:
9443   // First string of the cons cell.
9444   inline String* first();
9445   // Doesn't check that the result is a string, even in debug mode.  This is
9446   // useful during GC where the mark bits confuse the checks.
9447   inline Object* unchecked_first();
9448   inline void set_first(String* first,
9449                         WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9450
9451   // Second string of the cons cell.
9452   inline String* second();
9453   // Doesn't check that the result is a string, even in debug mode.  This is
9454   // useful during GC where the mark bits confuse the checks.
9455   inline Object* unchecked_second();
9456   inline void set_second(String* second,
9457                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9458
9459   // Dispatched behavior.
9460   uint16_t ConsStringGet(int index);
9461
9462   // Casting.
9463   static inline ConsString* cast(Object* obj);
9464
9465   // Layout description.
9466   static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9467   static const int kSecondOffset = kFirstOffset + kPointerSize;
9468   static const int kSize = kSecondOffset + kPointerSize;
9469
9470   // Minimum length for a cons string.
9471   static const int kMinLength = 13;
9472
9473   typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9474           BodyDescriptor;
9475
9476   DECLARE_VERIFIER(ConsString)
9477
9478  private:
9479   DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9480 };
9481
9482
9483 // The Sliced String class describes strings that are substrings of another
9484 // sequential string.  The motivation is to save time and memory when creating
9485 // a substring.  A Sliced String is described as a pointer to the parent,
9486 // the offset from the start of the parent string and the length.  Using
9487 // a Sliced String therefore requires unpacking of the parent string and
9488 // adding the offset to the start address.  A substring of a Sliced String
9489 // are not nested since the double indirection is simplified when creating
9490 // such a substring.
9491 // Currently missing features are:
9492 //  - handling externalized parent strings
9493 //  - external strings as parent
9494 //  - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9495 class SlicedString: public String {
9496  public:
9497   inline String* parent();
9498   inline void set_parent(String* parent,
9499                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9500   inline int offset();
9501   inline void set_offset(int offset);
9502
9503   // Dispatched behavior.
9504   uint16_t SlicedStringGet(int index);
9505
9506   // Casting.
9507   static inline SlicedString* cast(Object* obj);
9508
9509   // Layout description.
9510   static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9511   static const int kOffsetOffset = kParentOffset + kPointerSize;
9512   static const int kSize = kOffsetOffset + kPointerSize;
9513
9514   // Minimum length for a sliced string.
9515   static const int kMinLength = 13;
9516
9517   typedef FixedBodyDescriptor<kParentOffset,
9518                               kOffsetOffset + kPointerSize, kSize>
9519           BodyDescriptor;
9520
9521   DECLARE_VERIFIER(SlicedString)
9522
9523  private:
9524   DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9525 };
9526
9527
9528 // The ExternalString class describes string values that are backed by
9529 // a string resource that lies outside the V8 heap.  ExternalStrings
9530 // consist of the length field common to all strings, a pointer to the
9531 // external resource.  It is important to ensure (externally) that the
9532 // resource is not deallocated while the ExternalString is live in the
9533 // V8 heap.
9534 //
9535 // The API expects that all ExternalStrings are created through the
9536 // API.  Therefore, ExternalStrings should not be used internally.
9537 class ExternalString: public String {
9538  public:
9539   // Casting
9540   static inline ExternalString* cast(Object* obj);
9541
9542   // Layout description.
9543   static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9544   static const int kShortSize = kResourceOffset + kPointerSize;
9545   static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9546   static const int kSize = kResourceDataOffset + kPointerSize;
9547
9548   static const int kMaxShortLength =
9549       (kShortSize - SeqString::kHeaderSize) / kCharSize;
9550
9551   // Return whether external string is short (data pointer is not cached).
9552   inline bool is_short();
9553
9554   STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
9555
9556  private:
9557   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9558 };
9559
9560
9561 // The ExternalAsciiString class is an external string backed by an
9562 // ASCII string.
9563 class ExternalAsciiString: public ExternalString {
9564  public:
9565   static const bool kHasAsciiEncoding = true;
9566
9567   typedef v8::String::ExternalAsciiStringResource Resource;
9568
9569   // The underlying resource.
9570   inline const Resource* resource();
9571   inline void set_resource(const Resource* buffer);
9572
9573   // Update the pointer cache to the external character array.
9574   // The cached pointer is always valid, as the external character array does =
9575   // not move during lifetime.  Deserialization is the only exception, after
9576   // which the pointer cache has to be refreshed.
9577   inline void update_data_cache();
9578
9579   inline const uint8_t* GetChars();
9580
9581   // Dispatched behavior.
9582   inline uint16_t ExternalAsciiStringGet(int index);
9583
9584   // Casting.
9585   static inline ExternalAsciiString* cast(Object* obj);
9586
9587   // Garbage collection support.
9588   inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
9589
9590   template<typename StaticVisitor>
9591   inline void ExternalAsciiStringIterateBody();
9592
9593  private:
9594   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
9595 };
9596
9597
9598 // The ExternalTwoByteString class is an external string backed by a UTF-16
9599 // encoded string.
9600 class ExternalTwoByteString: public ExternalString {
9601  public:
9602   static const bool kHasAsciiEncoding = false;
9603
9604   typedef v8::String::ExternalStringResource Resource;
9605
9606   // The underlying string resource.
9607   inline const Resource* resource();
9608   inline void set_resource(const Resource* buffer);
9609
9610   // Update the pointer cache to the external character array.
9611   // The cached pointer is always valid, as the external character array does =
9612   // not move during lifetime.  Deserialization is the only exception, after
9613   // which the pointer cache has to be refreshed.
9614   inline void update_data_cache();
9615
9616   inline const uint16_t* GetChars();
9617
9618   // Dispatched behavior.
9619   inline uint16_t ExternalTwoByteStringGet(int index);
9620
9621   // For regexp code.
9622   inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9623
9624   // Casting.
9625   static inline ExternalTwoByteString* cast(Object* obj);
9626
9627   // Garbage collection support.
9628   inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9629
9630   template<typename StaticVisitor>
9631   inline void ExternalTwoByteStringIterateBody();
9632
9633  private:
9634   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9635 };
9636
9637
9638 // Utility superclass for stack-allocated objects that must be updated
9639 // on gc.  It provides two ways for the gc to update instances, either
9640 // iterating or updating after gc.
9641 class Relocatable BASE_EMBEDDED {
9642  public:
9643   explicit inline Relocatable(Isolate* isolate);
9644   inline virtual ~Relocatable();
9645   virtual void IterateInstance(ObjectVisitor* v) { }
9646   virtual void PostGarbageCollection() { }
9647
9648   static void PostGarbageCollectionProcessing(Isolate* isolate);
9649   static int ArchiveSpacePerThread();
9650   static char* ArchiveState(Isolate* isolate, char* to);
9651   static char* RestoreState(Isolate* isolate, char* from);
9652   static void Iterate(Isolate* isolate, ObjectVisitor* v);
9653   static void Iterate(ObjectVisitor* v, Relocatable* top);
9654   static char* Iterate(ObjectVisitor* v, char* t);
9655
9656  private:
9657   Isolate* isolate_;
9658   Relocatable* prev_;
9659 };
9660
9661
9662 // A flat string reader provides random access to the contents of a
9663 // string independent of the character width of the string.  The handle
9664 // must be valid as long as the reader is being used.
9665 class FlatStringReader : public Relocatable {
9666  public:
9667   FlatStringReader(Isolate* isolate, Handle<String> str);
9668   FlatStringReader(Isolate* isolate, Vector<const char> input);
9669   void PostGarbageCollection();
9670   inline uc32 Get(int index);
9671   int length() { return length_; }
9672  private:
9673   String** str_;
9674   bool is_ascii_;
9675   int length_;
9676   const void* start_;
9677 };
9678
9679
9680 // A ConsStringOp that returns null.
9681 // Useful when the operation to apply on a ConsString
9682 // requires an expensive data structure.
9683 class ConsStringNullOp {
9684  public:
9685   inline ConsStringNullOp() {}
9686   static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9687  private:
9688   DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9689 };
9690
9691
9692 // This maintains an off-stack representation of the stack frames required
9693 // to traverse a ConsString, allowing an entirely iterative and restartable
9694 // traversal of the entire string
9695 // Note: this class is not GC-safe.
9696 class ConsStringIteratorOp {
9697  public:
9698   inline ConsStringIteratorOp() {}
9699   String* Operate(String* string,
9700                   unsigned* offset_out,
9701                   int32_t* type_out,
9702                   unsigned* length_out);
9703   inline String* ContinueOperation(int32_t* type_out, unsigned* length_out);
9704   inline void Reset();
9705   inline bool HasMore();
9706
9707  private:
9708   // TODO(dcarney): Templatize this out for different stack sizes.
9709   static const unsigned kStackSize = 32;
9710   // Use a mask instead of doing modulo operations for stack wrapping.
9711   static const unsigned kDepthMask = kStackSize-1;
9712   STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9713   static inline unsigned OffsetForDepth(unsigned depth);
9714
9715   inline void PushLeft(ConsString* string);
9716   inline void PushRight(ConsString* string);
9717   inline void AdjustMaximumDepth();
9718   inline void Pop();
9719   String* NextLeaf(bool* blew_stack, int32_t* type_out, unsigned* length_out);
9720   String* Search(unsigned* offset_out,
9721                  int32_t* type_out,
9722                  unsigned* length_out);
9723
9724   unsigned depth_;
9725   unsigned maximum_depth_;
9726   // Stack must always contain only frames for which right traversal
9727   // has not yet been performed.
9728   ConsString* frames_[kStackSize];
9729   unsigned consumed_;
9730   ConsString* root_;
9731   DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9732 };
9733
9734
9735 // Note: this class is not GC-safe.
9736 class StringCharacterStream {
9737  public:
9738   inline StringCharacterStream(String* string,
9739                                ConsStringIteratorOp* op,
9740                                unsigned offset = 0);
9741   inline uint16_t GetNext();
9742   inline bool HasMore();
9743   inline void Reset(String* string, unsigned offset = 0);
9744   inline void VisitOneByteString(const uint8_t* chars, unsigned length);
9745   inline void VisitTwoByteString(const uint16_t* chars, unsigned length);
9746
9747  private:
9748   bool is_one_byte_;
9749   union {
9750     const uint8_t* buffer8_;
9751     const uint16_t* buffer16_;
9752   };
9753   const uint8_t* end_;
9754   ConsStringIteratorOp* op_;
9755   DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9756 };
9757
9758
9759 template <typename T>
9760 class VectorIterator {
9761  public:
9762   VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9763   explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9764   T GetNext() { return data_[index_++]; }
9765   bool has_more() { return index_ < data_.length(); }
9766  private:
9767   Vector<const T> data_;
9768   int index_;
9769 };
9770
9771
9772 // The Oddball describes objects null, undefined, true, and false.
9773 class Oddball: public HeapObject {
9774  public:
9775   // [to_string]: Cached to_string computed at startup.
9776   DECL_ACCESSORS(to_string, String)
9777
9778   // [to_number]: Cached to_number computed at startup.
9779   DECL_ACCESSORS(to_number, Object)
9780
9781   inline byte kind();
9782   inline void set_kind(byte kind);
9783
9784   // Casting.
9785   static inline Oddball* cast(Object* obj);
9786
9787   // Dispatched behavior.
9788   DECLARE_VERIFIER(Oddball)
9789
9790   // Initialize the fields.
9791   MUST_USE_RESULT MaybeObject* Initialize(Heap* heap,
9792                                           const char* to_string,
9793                                           Object* to_number,
9794                                           byte kind);
9795
9796   // Layout description.
9797   static const int kToStringOffset = HeapObject::kHeaderSize;
9798   static const int kToNumberOffset = kToStringOffset + kPointerSize;
9799   static const int kKindOffset = kToNumberOffset + kPointerSize;
9800   static const int kSize = kKindOffset + kPointerSize;
9801
9802   static const byte kFalse = 0;
9803   static const byte kTrue = 1;
9804   static const byte kNotBooleanMask = ~1;
9805   static const byte kTheHole = 2;
9806   static const byte kNull = 3;
9807   static const byte kArgumentMarker = 4;
9808   static const byte kUndefined = 5;
9809   static const byte kUninitialized = 6;
9810   static const byte kOther = 7;
9811
9812   typedef FixedBodyDescriptor<kToStringOffset,
9813                               kToNumberOffset + kPointerSize,
9814                               kSize> BodyDescriptor;
9815
9816   STATIC_CHECK(kKindOffset == Internals::kOddballKindOffset);
9817   STATIC_CHECK(kNull == Internals::kNullOddballKind);
9818   STATIC_CHECK(kUndefined == Internals::kUndefinedOddballKind);
9819
9820  private:
9821   DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9822 };
9823
9824
9825 class Cell: public HeapObject {
9826  public:
9827   // [value]: value of the global property.
9828   DECL_ACCESSORS(value, Object)
9829
9830   // Casting.
9831   static inline Cell* cast(Object* obj);
9832
9833   static inline Cell* FromValueAddress(Address value) {
9834     Object* result = FromAddress(value - kValueOffset);
9835     ASSERT(result->IsCell() || result->IsPropertyCell());
9836     return static_cast<Cell*>(result);
9837   }
9838
9839   inline Address ValueAddress() {
9840     return address() + kValueOffset;
9841   }
9842
9843   // Dispatched behavior.
9844   DECLARE_PRINTER(Cell)
9845   DECLARE_VERIFIER(Cell)
9846
9847   // Layout description.
9848   static const int kValueOffset = HeapObject::kHeaderSize;
9849   static const int kSize = kValueOffset + kPointerSize;
9850
9851   typedef FixedBodyDescriptor<kValueOffset,
9852                               kValueOffset + kPointerSize,
9853                               kSize> BodyDescriptor;
9854
9855  private:
9856   DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9857 };
9858
9859
9860 class PropertyCell: public Cell {
9861  public:
9862   // [type]: type of the global property.
9863   HeapType* type();
9864   void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9865
9866   // [dependent_code]: dependent code that depends on the type of the global
9867   // property.
9868   DECL_ACCESSORS(dependent_code, DependentCode)
9869
9870   // Sets the value of the cell and updates the type field to be the union
9871   // of the cell's current type and the value's type. If the change causes
9872   // a change of the type of the cell's contents, code dependent on the cell
9873   // will be deoptimized.
9874   static void SetValueInferType(Handle<PropertyCell> cell,
9875                                 Handle<Object> value);
9876
9877   // Computes the new type of the cell's contents for the given value, but
9878   // without actually modifying the 'type' field.
9879   static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9880                                       Handle<Object> value);
9881
9882   void AddDependentCompilationInfo(CompilationInfo* info);
9883
9884   void AddDependentCode(Handle<Code> code);
9885
9886   // Casting.
9887   static inline PropertyCell* cast(Object* obj);
9888
9889   inline Address TypeAddress() {
9890     return address() + kTypeOffset;
9891   }
9892
9893   // Dispatched behavior.
9894   DECLARE_PRINTER(PropertyCell)
9895   DECLARE_VERIFIER(PropertyCell)
9896
9897   // Layout description.
9898   static const int kTypeOffset = kValueOffset + kPointerSize;
9899   static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9900   static const int kSize = kDependentCodeOffset + kPointerSize;
9901
9902   static const int kPointerFieldsBeginOffset = kValueOffset;
9903   static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9904
9905   typedef FixedBodyDescriptor<kValueOffset,
9906                               kSize,
9907                               kSize> BodyDescriptor;
9908
9909  private:
9910   DECL_ACCESSORS(type_raw, Object)
9911   DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9912 };
9913
9914
9915 // The JSProxy describes EcmaScript Harmony proxies
9916 class JSProxy: public JSReceiver {
9917  public:
9918   // [handler]: The handler property.
9919   DECL_ACCESSORS(handler, Object)
9920
9921   // [hash]: The hash code property (undefined if not initialized yet).
9922   DECL_ACCESSORS(hash, Object)
9923
9924   // Casting.
9925   static inline JSProxy* cast(Object* obj);
9926
9927   MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
9928       Object* receiver,
9929       Name* name);
9930   MUST_USE_RESULT MaybeObject* GetElementWithHandler(
9931       Object* receiver,
9932       uint32_t index);
9933
9934   // If the handler defines an accessor property with a setter, invoke it.
9935   // If it defines an accessor property without a setter, or a data property
9936   // that is read-only, throw. In all these cases set '*done' to true,
9937   // otherwise set it to false.
9938   static Handle<Object> SetPropertyViaPrototypesWithHandler(
9939       Handle<JSProxy> proxy,
9940       Handle<JSReceiver> receiver,
9941       Handle<Name> name,
9942       Handle<Object> value,
9943       PropertyAttributes attributes,
9944       StrictMode strict_mode,
9945       bool* done);
9946
9947   static PropertyAttributes GetPropertyAttributeWithHandler(
9948       Handle<JSProxy> proxy,
9949       Handle<JSReceiver> receiver,
9950       Handle<Name> name);
9951   static PropertyAttributes GetElementAttributeWithHandler(
9952       Handle<JSProxy> proxy,
9953       Handle<JSReceiver> receiver,
9954       uint32_t index);
9955
9956   // Turn the proxy into an (empty) JSObject.
9957   static void Fix(Handle<JSProxy> proxy);
9958
9959   // Initializes the body after the handler slot.
9960   inline void InitializeBody(int object_size, Object* value);
9961
9962   // Invoke a trap by name. If the trap does not exist on this's handler,
9963   // but derived_trap is non-NULL, invoke that instead.  May cause GC.
9964   Handle<Object> CallTrap(const char* name,
9965                           Handle<Object> derived_trap,
9966                           int argc,
9967                           Handle<Object> args[]);
9968
9969   // Dispatched behavior.
9970   DECLARE_PRINTER(JSProxy)
9971   DECLARE_VERIFIER(JSProxy)
9972
9973   // Layout description. We add padding so that a proxy has the same
9974   // size as a virgin JSObject. This is essential for becoming a JSObject
9975   // upon freeze.
9976   static const int kHandlerOffset = HeapObject::kHeaderSize;
9977   static const int kHashOffset = kHandlerOffset + kPointerSize;
9978   static const int kPaddingOffset = kHashOffset + kPointerSize;
9979   static const int kSize = JSObject::kHeaderSize;
9980   static const int kHeaderSize = kPaddingOffset;
9981   static const int kPaddingSize = kSize - kPaddingOffset;
9982
9983   STATIC_CHECK(kPaddingSize >= 0);
9984
9985   typedef FixedBodyDescriptor<kHandlerOffset,
9986                               kPaddingOffset,
9987                               kSize> BodyDescriptor;
9988
9989  private:
9990   friend class JSReceiver;
9991
9992   static Handle<Object> SetPropertyWithHandler(Handle<JSProxy> proxy,
9993                                                Handle<JSReceiver> receiver,
9994                                                Handle<Name> name,
9995                                                Handle<Object> value,
9996                                                PropertyAttributes attributes,
9997                                                StrictMode strict_mode);
9998   static Handle<Object> SetElementWithHandler(Handle<JSProxy> proxy,
9999                                               Handle<JSReceiver> receiver,
10000                                               uint32_t index,
10001                                               Handle<Object> value,
10002                                               StrictMode strict_mode);
10003
10004   static bool HasPropertyWithHandler(Handle<JSProxy> proxy, Handle<Name> name);
10005   static bool HasElementWithHandler(Handle<JSProxy> proxy, uint32_t index);
10006
10007   static Handle<Object> DeletePropertyWithHandler(Handle<JSProxy> proxy,
10008                                                   Handle<Name> name,
10009                                                   DeleteMode mode);
10010   static Handle<Object> DeleteElementWithHandler(Handle<JSProxy> proxy,
10011                                                  uint32_t index,
10012                                                  DeleteMode mode);
10013
10014   MUST_USE_RESULT Object* GetIdentityHash();
10015
10016   static Handle<Object> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
10017
10018   DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
10019 };
10020
10021
10022 class JSFunctionProxy: public JSProxy {
10023  public:
10024   // [call_trap]: The call trap.
10025   DECL_ACCESSORS(call_trap, Object)
10026
10027   // [construct_trap]: The construct trap.
10028   DECL_ACCESSORS(construct_trap, Object)
10029
10030   // Casting.
10031   static inline JSFunctionProxy* cast(Object* obj);
10032
10033   // Dispatched behavior.
10034   DECLARE_PRINTER(JSFunctionProxy)
10035   DECLARE_VERIFIER(JSFunctionProxy)
10036
10037   // Layout description.
10038   static const int kCallTrapOffset = JSProxy::kPaddingOffset;
10039   static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
10040   static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
10041   static const int kSize = JSFunction::kSize;
10042   static const int kPaddingSize = kSize - kPaddingOffset;
10043
10044   STATIC_CHECK(kPaddingSize >= 0);
10045
10046   typedef FixedBodyDescriptor<kHandlerOffset,
10047                               kConstructTrapOffset + kPointerSize,
10048                               kSize> BodyDescriptor;
10049
10050  private:
10051   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
10052 };
10053
10054
10055 // The JSSet describes EcmaScript Harmony sets
10056 class JSSet: public JSObject {
10057  public:
10058   // [set]: the backing hash set containing keys.
10059   DECL_ACCESSORS(table, Object)
10060
10061   // Casting.
10062   static inline JSSet* cast(Object* obj);
10063
10064   // Dispatched behavior.
10065   DECLARE_PRINTER(JSSet)
10066   DECLARE_VERIFIER(JSSet)
10067
10068   static const int kTableOffset = JSObject::kHeaderSize;
10069   static const int kSize = kTableOffset + kPointerSize;
10070
10071  private:
10072   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10073 };
10074
10075
10076 // The JSMap describes EcmaScript Harmony maps
10077 class JSMap: public JSObject {
10078  public:
10079   // [table]: the backing hash table mapping keys to values.
10080   DECL_ACCESSORS(table, Object)
10081
10082   // Casting.
10083   static inline JSMap* cast(Object* obj);
10084
10085   // Dispatched behavior.
10086   DECLARE_PRINTER(JSMap)
10087   DECLARE_VERIFIER(JSMap)
10088
10089   static const int kTableOffset = JSObject::kHeaderSize;
10090   static const int kSize = kTableOffset + kPointerSize;
10091
10092  private:
10093   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10094 };
10095
10096
10097 // Base class for both JSWeakMap and JSWeakSet
10098 class JSWeakCollection: public JSObject {
10099  public:
10100   // [table]: the backing hash table mapping keys to values.
10101   DECL_ACCESSORS(table, Object)
10102
10103   // [next]: linked list of encountered weak maps during GC.
10104   DECL_ACCESSORS(next, Object)
10105
10106   static const int kTableOffset = JSObject::kHeaderSize;
10107   static const int kNextOffset = kTableOffset + kPointerSize;
10108   static const int kSize = kNextOffset + kPointerSize;
10109
10110  private:
10111   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10112 };
10113
10114
10115 // The JSWeakMap describes EcmaScript Harmony weak maps
10116 class JSWeakMap: public JSWeakCollection {
10117  public:
10118   // Casting.
10119   static inline JSWeakMap* cast(Object* obj);
10120
10121   // Dispatched behavior.
10122   DECLARE_PRINTER(JSWeakMap)
10123   DECLARE_VERIFIER(JSWeakMap)
10124
10125  private:
10126   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10127 };
10128
10129
10130 // The JSWeakSet describes EcmaScript Harmony weak sets
10131 class JSWeakSet: public JSWeakCollection {
10132  public:
10133   // Casting.
10134   static inline JSWeakSet* cast(Object* obj);
10135
10136   // Dispatched behavior.
10137   DECLARE_PRINTER(JSWeakSet)
10138   DECLARE_VERIFIER(JSWeakSet)
10139
10140  private:
10141   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10142 };
10143
10144
10145 class JSArrayBuffer: public JSObject {
10146  public:
10147   // [backing_store]: backing memory for this array
10148   DECL_ACCESSORS(backing_store, void)
10149
10150   // [byte_length]: length in bytes
10151   DECL_ACCESSORS(byte_length, Object)
10152
10153   // [flags]
10154   DECL_ACCESSORS(flag, Smi)
10155
10156   inline bool is_external();
10157   inline void set_is_external(bool value);
10158
10159   inline bool should_be_freed();
10160   inline void set_should_be_freed(bool value);
10161
10162   // [weak_next]: linked list of array buffers.
10163   DECL_ACCESSORS(weak_next, Object)
10164
10165   // [weak_first_array]: weak linked list of views.
10166   DECL_ACCESSORS(weak_first_view, Object)
10167
10168   // Casting.
10169   static inline JSArrayBuffer* cast(Object* obj);
10170
10171   // Neutering. Only neuters the buffer, not associated typed arrays.
10172   void Neuter();
10173
10174   // Dispatched behavior.
10175   DECLARE_PRINTER(JSArrayBuffer)
10176   DECLARE_VERIFIER(JSArrayBuffer)
10177
10178   static const int kBackingStoreOffset = JSObject::kHeaderSize;
10179   static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10180   static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10181   static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10182   static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10183   static const int kSize = kWeakFirstViewOffset + kPointerSize;
10184
10185   static const int kSizeWithInternalFields =
10186       kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10187
10188  private:
10189   // Bit position in a flag
10190   static const int kIsExternalBit = 0;
10191   static const int kShouldBeFreed = 1;
10192
10193   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10194 };
10195
10196
10197 class JSArrayBufferView: public JSObject {
10198  public:
10199   // [buffer]: ArrayBuffer that this typed array views.
10200   DECL_ACCESSORS(buffer, Object)
10201
10202   // [byte_length]: offset of typed array in bytes.
10203   DECL_ACCESSORS(byte_offset, Object)
10204
10205   // [byte_length]: length of typed array in bytes.
10206   DECL_ACCESSORS(byte_length, Object)
10207
10208   // [weak_next]: linked list of typed arrays over the same array buffer.
10209   DECL_ACCESSORS(weak_next, Object)
10210
10211   // Casting.
10212   static inline JSArrayBufferView* cast(Object* obj);
10213
10214   DECLARE_VERIFIER(JSArrayBufferView)
10215
10216   static const int kBufferOffset = JSObject::kHeaderSize;
10217   static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10218   static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10219   static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10220   static const int kViewSize = kWeakNextOffset + kPointerSize;
10221
10222  protected:
10223   void NeuterView();
10224
10225  private:
10226   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10227 };
10228
10229
10230 class JSTypedArray: public JSArrayBufferView {
10231  public:
10232   // [length]: length of typed array in elements.
10233   DECL_ACCESSORS(length, Object)
10234
10235   // Neutering. Only neuters this typed array.
10236   void Neuter();
10237
10238   // Casting.
10239   static inline JSTypedArray* cast(Object* obj);
10240
10241   ExternalArrayType type();
10242   size_t element_size();
10243
10244   Handle<JSArrayBuffer> GetBuffer();
10245
10246   // Dispatched behavior.
10247   DECLARE_PRINTER(JSTypedArray)
10248   DECLARE_VERIFIER(JSTypedArray)
10249
10250   static const int kLengthOffset = kViewSize + kPointerSize;
10251   static const int kSize = kLengthOffset + kPointerSize;
10252
10253   static const int kSizeWithInternalFields =
10254       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10255
10256  private:
10257   static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10258       Handle<JSTypedArray> typed_array);
10259
10260   DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10261 };
10262
10263
10264 class JSDataView: public JSArrayBufferView {
10265  public:
10266   // Only neuters this DataView
10267   void Neuter();
10268
10269   // Casting.
10270   static inline JSDataView* cast(Object* obj);
10271
10272   // Dispatched behavior.
10273   DECLARE_PRINTER(JSDataView)
10274   DECLARE_VERIFIER(JSDataView)
10275
10276   static const int kSize = kViewSize;
10277
10278   static const int kSizeWithInternalFields =
10279       kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10280
10281  private:
10282   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10283 };
10284
10285
10286 // Foreign describes objects pointing from JavaScript to C structures.
10287 // Since they cannot contain references to JS HeapObjects they can be
10288 // placed in old_data_space.
10289 class Foreign: public HeapObject {
10290  public:
10291   // [address]: field containing the address.
10292   inline Address foreign_address();
10293   inline void set_foreign_address(Address value);
10294
10295   // Casting.
10296   static inline Foreign* cast(Object* obj);
10297
10298   // Dispatched behavior.
10299   inline void ForeignIterateBody(ObjectVisitor* v);
10300
10301   template<typename StaticVisitor>
10302   inline void ForeignIterateBody();
10303
10304   // Dispatched behavior.
10305   DECLARE_PRINTER(Foreign)
10306   DECLARE_VERIFIER(Foreign)
10307
10308   // Layout description.
10309
10310   static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10311   static const int kSize = kForeignAddressOffset + kPointerSize;
10312
10313   STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
10314
10315  private:
10316   DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10317 };
10318
10319
10320 // The JSArray describes JavaScript Arrays
10321 //  Such an array can be in one of two modes:
10322 //    - fast, backing storage is a FixedArray and length <= elements.length();
10323 //       Please note: push and pop can be used to grow and shrink the array.
10324 //    - slow, backing storage is a HashTable with numbers as keys.
10325 class JSArray: public JSObject {
10326  public:
10327   // [length]: The length property.
10328   DECL_ACCESSORS(length, Object)
10329
10330   // Overload the length setter to skip write barrier when the length
10331   // is set to a smi. This matches the set function on FixedArray.
10332   inline void set_length(Smi* length);
10333
10334   static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10335                                            uint32_t index,
10336                                            Handle<Object> value);
10337
10338   MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
10339                                                             Object* value);
10340
10341   // Initialize the array with the given capacity. The function may
10342   // fail due to out-of-memory situations, but only if the requested
10343   // capacity is non-zero.
10344   static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10345
10346   // Initializes the array to a certain length.
10347   inline bool AllowsSetElementsLength();
10348   // Can cause GC.
10349   static Handle<Object> SetElementsLength(Handle<JSArray> array,
10350                                           Handle<Object> length);
10351
10352   // Set the content of the array to the content of storage.
10353   static inline void SetContent(Handle<JSArray> array,
10354                                 Handle<FixedArrayBase> storage);
10355
10356   // Casting.
10357   static inline JSArray* cast(Object* obj);
10358
10359   // Ensures that the fixed array backing the JSArray has at
10360   // least the stated size.
10361   static inline void EnsureSize(Handle<JSArray> array,
10362                                 int minimum_size_of_backing_fixed_array);
10363
10364   // Expand the fixed array backing of a fast-case JSArray to at least
10365   // the requested size.
10366   static void Expand(Handle<JSArray> array,
10367                      int minimum_size_of_backing_fixed_array);
10368
10369   // Dispatched behavior.
10370   DECLARE_PRINTER(JSArray)
10371   DECLARE_VERIFIER(JSArray)
10372
10373   // Number of element slots to pre-allocate for an empty array.
10374   static const int kPreallocatedArrayElements = 4;
10375
10376   // Layout description.
10377   static const int kLengthOffset = JSObject::kHeaderSize;
10378   static const int kSize = kLengthOffset + kPointerSize;
10379
10380  private:
10381   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10382 };
10383
10384
10385 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10386                                        Handle<Map> initial_map);
10387
10388
10389 // JSRegExpResult is just a JSArray with a specific initial map.
10390 // This initial map adds in-object properties for "index" and "input"
10391 // properties, as assigned by RegExp.prototype.exec, which allows
10392 // faster creation of RegExp exec results.
10393 // This class just holds constants used when creating the result.
10394 // After creation the result must be treated as a JSArray in all regards.
10395 class JSRegExpResult: public JSArray {
10396  public:
10397   // Offsets of object fields.
10398   static const int kIndexOffset = JSArray::kSize;
10399   static const int kInputOffset = kIndexOffset + kPointerSize;
10400   static const int kSize = kInputOffset + kPointerSize;
10401   // Indices of in-object properties.
10402   static const int kIndexIndex = 0;
10403   static const int kInputIndex = 1;
10404  private:
10405   DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10406 };
10407
10408
10409 class AccessorInfo: public Struct {
10410  public:
10411   DECL_ACCESSORS(name, Object)
10412   DECL_ACCESSORS(flag, Smi)
10413   DECL_ACCESSORS(expected_receiver_type, Object)
10414
10415   inline bool all_can_read();
10416   inline void set_all_can_read(bool value);
10417
10418   inline bool all_can_write();
10419   inline void set_all_can_write(bool value);
10420
10421   inline bool prohibits_overwriting();
10422   inline void set_prohibits_overwriting(bool value);
10423
10424   inline PropertyAttributes property_attributes();
10425   inline void set_property_attributes(PropertyAttributes attributes);
10426
10427   // Checks whether the given receiver is compatible with this accessor.
10428   inline bool IsCompatibleReceiver(Object* receiver);
10429
10430   static inline AccessorInfo* cast(Object* obj);
10431
10432   // Dispatched behavior.
10433   DECLARE_VERIFIER(AccessorInfo)
10434
10435   // Append all descriptors to the array that are not already there.
10436   // Return number added.
10437   static int AppendUnique(Handle<Object> descriptors,
10438                           Handle<FixedArray> array,
10439                           int valid_descriptors);
10440
10441   static const int kNameOffset = HeapObject::kHeaderSize;
10442   static const int kFlagOffset = kNameOffset + kPointerSize;
10443   static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10444   static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10445
10446  private:
10447   // Bit positions in flag.
10448   static const int kAllCanReadBit = 0;
10449   static const int kAllCanWriteBit = 1;
10450   static const int kProhibitsOverwritingBit = 2;
10451   class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
10452
10453   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10454 };
10455
10456
10457 enum AccessorDescriptorType {
10458   kDescriptorBitmaskCompare,
10459   kDescriptorPointerCompare,
10460   kDescriptorPrimitiveValue,
10461   kDescriptorObjectDereference,
10462   kDescriptorPointerDereference,
10463   kDescriptorPointerShift,
10464   kDescriptorReturnObject
10465 };
10466
10467
10468 struct BitmaskCompareDescriptor {
10469   uint32_t bitmask;
10470   uint32_t compare_value;
10471   uint8_t size;  // Must be in {1,2,4}.
10472 };
10473
10474
10475 struct PointerCompareDescriptor {
10476   void* compare_value;
10477 };
10478
10479
10480 struct PrimitiveValueDescriptor {
10481   v8::DeclaredAccessorDescriptorDataType data_type;
10482   uint8_t bool_offset;  // Must be in [0,7], used for kDescriptorBoolType.
10483 };
10484
10485
10486 struct ObjectDerefenceDescriptor {
10487   uint8_t internal_field;
10488 };
10489
10490
10491 struct PointerShiftDescriptor {
10492   int16_t byte_offset;
10493 };
10494
10495
10496 struct DeclaredAccessorDescriptorData {
10497   AccessorDescriptorType type;
10498   union {
10499     struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10500     struct PointerCompareDescriptor pointer_compare_descriptor;
10501     struct PrimitiveValueDescriptor primitive_value_descriptor;
10502     struct ObjectDerefenceDescriptor object_dereference_descriptor;
10503     struct PointerShiftDescriptor pointer_shift_descriptor;
10504   };
10505 };
10506
10507
10508 class DeclaredAccessorDescriptor;
10509
10510
10511 class DeclaredAccessorDescriptorIterator {
10512  public:
10513   explicit DeclaredAccessorDescriptorIterator(
10514       DeclaredAccessorDescriptor* descriptor);
10515   const DeclaredAccessorDescriptorData* Next();
10516   bool Complete() const { return length_ == offset_; }
10517  private:
10518   uint8_t* array_;
10519   const int length_;
10520   int offset_;
10521   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10522 };
10523
10524
10525 class DeclaredAccessorDescriptor: public Struct {
10526  public:
10527   DECL_ACCESSORS(serialized_data, ByteArray)
10528
10529   static inline DeclaredAccessorDescriptor* cast(Object* obj);
10530
10531   static Handle<DeclaredAccessorDescriptor> Create(
10532       Isolate* isolate,
10533       const DeclaredAccessorDescriptorData& data,
10534       Handle<DeclaredAccessorDescriptor> previous);
10535
10536   // Dispatched behavior.
10537   DECLARE_PRINTER(DeclaredAccessorDescriptor)
10538   DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10539
10540   static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10541   static const int kSize = kSerializedDataOffset + kPointerSize;
10542
10543  private:
10544   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10545 };
10546
10547
10548 class DeclaredAccessorInfo: public AccessorInfo {
10549  public:
10550   DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10551
10552   static inline DeclaredAccessorInfo* cast(Object* obj);
10553
10554   // Dispatched behavior.
10555   DECLARE_PRINTER(DeclaredAccessorInfo)
10556   DECLARE_VERIFIER(DeclaredAccessorInfo)
10557
10558   static const int kDescriptorOffset = AccessorInfo::kSize;
10559   static const int kSize = kDescriptorOffset + kPointerSize;
10560
10561  private:
10562   DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10563 };
10564
10565
10566 // An accessor must have a getter, but can have no setter.
10567 //
10568 // When setting a property, V8 searches accessors in prototypes.
10569 // If an accessor was found and it does not have a setter,
10570 // the request is ignored.
10571 //
10572 // If the accessor in the prototype has the READ_ONLY property attribute, then
10573 // a new value is added to the local object when the property is set.
10574 // This shadows the accessor in the prototype.
10575 class ExecutableAccessorInfo: public AccessorInfo {
10576  public:
10577   DECL_ACCESSORS(getter, Object)
10578   DECL_ACCESSORS(setter, Object)
10579   DECL_ACCESSORS(data, Object)
10580
10581   static inline ExecutableAccessorInfo* cast(Object* obj);
10582
10583   // Dispatched behavior.
10584   DECLARE_PRINTER(ExecutableAccessorInfo)
10585   DECLARE_VERIFIER(ExecutableAccessorInfo)
10586
10587   static const int kGetterOffset = AccessorInfo::kSize;
10588   static const int kSetterOffset = kGetterOffset + kPointerSize;
10589   static const int kDataOffset = kSetterOffset + kPointerSize;
10590   static const int kSize = kDataOffset + kPointerSize;
10591
10592  private:
10593   DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10594 };
10595
10596
10597 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10598 // accessor can either be
10599 //   * a pointer to a JavaScript function or proxy: a real accessor
10600 //   * undefined: considered an accessor by the spec, too, strangely enough
10601 //   * the hole: an accessor which has not been set
10602 //   * a pointer to a map: a transition used to ensure map sharing
10603 // access_flags provides the ability to override access checks on access check
10604 // failure.
10605 class AccessorPair: public Struct {
10606  public:
10607   DECL_ACCESSORS(getter, Object)
10608   DECL_ACCESSORS(setter, Object)
10609   DECL_ACCESSORS(access_flags, Smi)
10610
10611   inline void set_access_flags(v8::AccessControl access_control);
10612   inline bool all_can_read();
10613   inline bool all_can_write();
10614   inline bool prohibits_overwriting();
10615
10616   static inline AccessorPair* cast(Object* obj);
10617
10618   static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10619
10620   Object* get(AccessorComponent component) {
10621     return component == ACCESSOR_GETTER ? getter() : setter();
10622   }
10623
10624   void set(AccessorComponent component, Object* value) {
10625     if (component == ACCESSOR_GETTER) {
10626       set_getter(value);
10627     } else {
10628       set_setter(value);
10629     }
10630   }
10631
10632   // Note: Returns undefined instead in case of a hole.
10633   Object* GetComponent(AccessorComponent component);
10634
10635   // Set both components, skipping arguments which are a JavaScript null.
10636   void SetComponents(Object* getter, Object* setter) {
10637     if (!getter->IsNull()) set_getter(getter);
10638     if (!setter->IsNull()) set_setter(setter);
10639   }
10640
10641   bool ContainsAccessor() {
10642     return IsJSAccessor(getter()) || IsJSAccessor(setter());
10643   }
10644
10645   // Dispatched behavior.
10646   DECLARE_PRINTER(AccessorPair)
10647   DECLARE_VERIFIER(AccessorPair)
10648
10649   static const int kGetterOffset = HeapObject::kHeaderSize;
10650   static const int kSetterOffset = kGetterOffset + kPointerSize;
10651   static const int kAccessFlagsOffset = kSetterOffset + kPointerSize;
10652   static const int kSize = kAccessFlagsOffset + kPointerSize;
10653
10654  private:
10655   static const int kAllCanReadBit = 0;
10656   static const int kAllCanWriteBit = 1;
10657   static const int kProhibitsOverwritingBit = 2;
10658
10659   // Strangely enough, in addition to functions and harmony proxies, the spec
10660   // requires us to consider undefined as a kind of accessor, too:
10661   //    var obj = {};
10662   //    Object.defineProperty(obj, "foo", {get: undefined});
10663   //    assertTrue("foo" in obj);
10664   bool IsJSAccessor(Object* obj) {
10665     return obj->IsSpecFunction() || obj->IsUndefined();
10666   }
10667
10668   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10669 };
10670
10671
10672 class AccessCheckInfo: public Struct {
10673  public:
10674   DECL_ACCESSORS(named_callback, Object)
10675   DECL_ACCESSORS(indexed_callback, Object)
10676   DECL_ACCESSORS(data, Object)
10677
10678   static inline AccessCheckInfo* cast(Object* obj);
10679
10680   // Dispatched behavior.
10681   DECLARE_PRINTER(AccessCheckInfo)
10682   DECLARE_VERIFIER(AccessCheckInfo)
10683
10684   static const int kNamedCallbackOffset   = HeapObject::kHeaderSize;
10685   static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10686   static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10687   static const int kSize = kDataOffset + kPointerSize;
10688
10689  private:
10690   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10691 };
10692
10693
10694 class InterceptorInfo: public Struct {
10695  public:
10696   DECL_ACCESSORS(getter, Object)
10697   DECL_ACCESSORS(setter, Object)
10698   DECL_ACCESSORS(query, Object)
10699   DECL_ACCESSORS(deleter, Object)
10700   DECL_ACCESSORS(enumerator, Object)
10701   DECL_ACCESSORS(data, Object)
10702
10703   static inline InterceptorInfo* cast(Object* obj);
10704
10705   // Dispatched behavior.
10706   DECLARE_PRINTER(InterceptorInfo)
10707   DECLARE_VERIFIER(InterceptorInfo)
10708
10709   static const int kGetterOffset = HeapObject::kHeaderSize;
10710   static const int kSetterOffset = kGetterOffset + kPointerSize;
10711   static const int kQueryOffset = kSetterOffset + kPointerSize;
10712   static const int kDeleterOffset = kQueryOffset + kPointerSize;
10713   static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10714   static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10715   static const int kSize = kDataOffset + kPointerSize;
10716
10717  private:
10718   DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10719 };
10720
10721
10722 class CallHandlerInfo: public Struct {
10723  public:
10724   DECL_ACCESSORS(callback, Object)
10725   DECL_ACCESSORS(data, Object)
10726
10727   static inline CallHandlerInfo* cast(Object* obj);
10728
10729   // Dispatched behavior.
10730   DECLARE_PRINTER(CallHandlerInfo)
10731   DECLARE_VERIFIER(CallHandlerInfo)
10732
10733   static const int kCallbackOffset = HeapObject::kHeaderSize;
10734   static const int kDataOffset = kCallbackOffset + kPointerSize;
10735   static const int kSize = kDataOffset + kPointerSize;
10736
10737  private:
10738   DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10739 };
10740
10741
10742 class TemplateInfo: public Struct {
10743  public:
10744   DECL_ACCESSORS(tag, Object)
10745   DECL_ACCESSORS(property_list, Object)
10746   DECL_ACCESSORS(property_accessors, Object)
10747
10748   DECLARE_VERIFIER(TemplateInfo)
10749
10750   static const int kTagOffset = HeapObject::kHeaderSize;
10751   static const int kPropertyListOffset = kTagOffset + kPointerSize;
10752   static const int kPropertyAccessorsOffset =
10753       kPropertyListOffset + kPointerSize;
10754   static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10755
10756  private:
10757   DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10758 };
10759
10760
10761 class FunctionTemplateInfo: public TemplateInfo {
10762  public:
10763   DECL_ACCESSORS(serial_number, Object)
10764   DECL_ACCESSORS(call_code, Object)
10765   DECL_ACCESSORS(prototype_template, Object)
10766   DECL_ACCESSORS(parent_template, Object)
10767   DECL_ACCESSORS(named_property_handler, Object)
10768   DECL_ACCESSORS(indexed_property_handler, Object)
10769   DECL_ACCESSORS(instance_template, Object)
10770   DECL_ACCESSORS(class_name, Object)
10771   DECL_ACCESSORS(signature, Object)
10772   DECL_ACCESSORS(instance_call_handler, Object)
10773   DECL_ACCESSORS(access_check_info, Object)
10774   DECL_ACCESSORS(flag, Smi)
10775
10776   inline int length();
10777   inline void set_length(int value);
10778
10779   // Following properties use flag bits.
10780   DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10781   DECL_BOOLEAN_ACCESSORS(undetectable)
10782   // If the bit is set, object instances created by this function
10783   // requires access check.
10784   DECL_BOOLEAN_ACCESSORS(needs_access_check)
10785   DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10786   DECL_BOOLEAN_ACCESSORS(remove_prototype)
10787   DECL_BOOLEAN_ACCESSORS(do_not_cache)
10788
10789   static inline FunctionTemplateInfo* cast(Object* obj);
10790
10791   // Dispatched behavior.
10792   DECLARE_PRINTER(FunctionTemplateInfo)
10793   DECLARE_VERIFIER(FunctionTemplateInfo)
10794
10795   static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10796   static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10797   static const int kPrototypeTemplateOffset =
10798       kCallCodeOffset + kPointerSize;
10799   static const int kParentTemplateOffset =
10800       kPrototypeTemplateOffset + kPointerSize;
10801   static const int kNamedPropertyHandlerOffset =
10802       kParentTemplateOffset + kPointerSize;
10803   static const int kIndexedPropertyHandlerOffset =
10804       kNamedPropertyHandlerOffset + kPointerSize;
10805   static const int kInstanceTemplateOffset =
10806       kIndexedPropertyHandlerOffset + kPointerSize;
10807   static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10808   static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10809   static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10810   static const int kAccessCheckInfoOffset =
10811       kInstanceCallHandlerOffset + kPointerSize;
10812   static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10813   static const int kLengthOffset = kFlagOffset + kPointerSize;
10814   static const int kSize = kLengthOffset + kPointerSize;
10815
10816   // Returns true if |object| is an instance of this function template.
10817   bool IsTemplateFor(Object* object);
10818   bool IsTemplateFor(Map* map);
10819
10820  private:
10821   // Bit position in the flag, from least significant bit position.
10822   static const int kHiddenPrototypeBit   = 0;
10823   static const int kUndetectableBit      = 1;
10824   static const int kNeedsAccessCheckBit  = 2;
10825   static const int kReadOnlyPrototypeBit = 3;
10826   static const int kRemovePrototypeBit   = 4;
10827   static const int kDoNotCacheBit        = 5;
10828
10829   DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10830 };
10831
10832
10833 class ObjectTemplateInfo: public TemplateInfo {
10834  public:
10835   DECL_ACCESSORS(constructor, Object)
10836   DECL_ACCESSORS(internal_field_count, Object)
10837
10838   static inline ObjectTemplateInfo* cast(Object* obj);
10839
10840   // Dispatched behavior.
10841   DECLARE_PRINTER(ObjectTemplateInfo)
10842   DECLARE_VERIFIER(ObjectTemplateInfo)
10843
10844   static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10845   static const int kInternalFieldCountOffset =
10846       kConstructorOffset + kPointerSize;
10847   static const int kSize = kInternalFieldCountOffset + kPointerSize;
10848 };
10849
10850
10851 class SignatureInfo: public Struct {
10852  public:
10853   DECL_ACCESSORS(receiver, Object)
10854   DECL_ACCESSORS(args, Object)
10855
10856   static inline SignatureInfo* cast(Object* obj);
10857
10858   // Dispatched behavior.
10859   DECLARE_PRINTER(SignatureInfo)
10860   DECLARE_VERIFIER(SignatureInfo)
10861
10862   static const int kReceiverOffset = Struct::kHeaderSize;
10863   static const int kArgsOffset     = kReceiverOffset + kPointerSize;
10864   static const int kSize           = kArgsOffset + kPointerSize;
10865
10866  private:
10867   DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10868 };
10869
10870
10871 class TypeSwitchInfo: public Struct {
10872  public:
10873   DECL_ACCESSORS(types, Object)
10874
10875   static inline TypeSwitchInfo* cast(Object* obj);
10876
10877   // Dispatched behavior.
10878   DECLARE_PRINTER(TypeSwitchInfo)
10879   DECLARE_VERIFIER(TypeSwitchInfo)
10880
10881   static const int kTypesOffset = Struct::kHeaderSize;
10882   static const int kSize        = kTypesOffset + kPointerSize;
10883 };
10884
10885
10886 #ifdef ENABLE_DEBUGGER_SUPPORT
10887 // The DebugInfo class holds additional information for a function being
10888 // debugged.
10889 class DebugInfo: public Struct {
10890  public:
10891   // The shared function info for the source being debugged.
10892   DECL_ACCESSORS(shared, SharedFunctionInfo)
10893   // Code object for the original code.
10894   DECL_ACCESSORS(original_code, Code)
10895   // Code object for the patched code. This code object is the code object
10896   // currently active for the function.
10897   DECL_ACCESSORS(code, Code)
10898   // Fixed array holding status information for each active break point.
10899   DECL_ACCESSORS(break_points, FixedArray)
10900
10901   // Check if there is a break point at a code position.
10902   bool HasBreakPoint(int code_position);
10903   // Get the break point info object for a code position.
10904   Object* GetBreakPointInfo(int code_position);
10905   // Clear a break point.
10906   static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10907                               int code_position,
10908                               Handle<Object> break_point_object);
10909   // Set a break point.
10910   static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10911                             int source_position, int statement_position,
10912                             Handle<Object> break_point_object);
10913   // Get the break point objects for a code position.
10914   Object* GetBreakPointObjects(int code_position);
10915   // Find the break point info holding this break point object.
10916   static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10917                                     Handle<Object> break_point_object);
10918   // Get the number of break points for this function.
10919   int GetBreakPointCount();
10920
10921   static inline DebugInfo* cast(Object* obj);
10922
10923   // Dispatched behavior.
10924   DECLARE_PRINTER(DebugInfo)
10925   DECLARE_VERIFIER(DebugInfo)
10926
10927   static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10928   static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10929   static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10930   static const int kActiveBreakPointsCountIndex =
10931       kPatchedCodeIndex + kPointerSize;
10932   static const int kBreakPointsStateIndex =
10933       kActiveBreakPointsCountIndex + kPointerSize;
10934   static const int kSize = kBreakPointsStateIndex + kPointerSize;
10935
10936  private:
10937   static const int kNoBreakPointInfo = -1;
10938
10939   // Lookup the index in the break_points array for a code position.
10940   int GetBreakPointInfoIndex(int code_position);
10941
10942   DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10943 };
10944
10945
10946 // The BreakPointInfo class holds information for break points set in a
10947 // function. The DebugInfo object holds a BreakPointInfo object for each code
10948 // position with one or more break points.
10949 class BreakPointInfo: public Struct {
10950  public:
10951   // The position in the code for the break point.
10952   DECL_ACCESSORS(code_position, Smi)
10953   // The position in the source for the break position.
10954   DECL_ACCESSORS(source_position, Smi)
10955   // The position in the source for the last statement before this break
10956   // position.
10957   DECL_ACCESSORS(statement_position, Smi)
10958   // List of related JavaScript break points.
10959   DECL_ACCESSORS(break_point_objects, Object)
10960
10961   // Removes a break point.
10962   static void ClearBreakPoint(Handle<BreakPointInfo> info,
10963                               Handle<Object> break_point_object);
10964   // Set a break point.
10965   static void SetBreakPoint(Handle<BreakPointInfo> info,
10966                             Handle<Object> break_point_object);
10967   // Check if break point info has this break point object.
10968   static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10969                                   Handle<Object> break_point_object);
10970   // Get the number of break points for this code position.
10971   int GetBreakPointCount();
10972
10973   static inline BreakPointInfo* cast(Object* obj);
10974
10975   // Dispatched behavior.
10976   DECLARE_PRINTER(BreakPointInfo)
10977   DECLARE_VERIFIER(BreakPointInfo)
10978
10979   static const int kCodePositionIndex = Struct::kHeaderSize;
10980   static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10981   static const int kStatementPositionIndex =
10982       kSourcePositionIndex + kPointerSize;
10983   static const int kBreakPointObjectsIndex =
10984       kStatementPositionIndex + kPointerSize;
10985   static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10986
10987  private:
10988   DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10989 };
10990 #endif  // ENABLE_DEBUGGER_SUPPORT
10991
10992
10993 #undef DECL_BOOLEAN_ACCESSORS
10994 #undef DECL_ACCESSORS
10995 #undef DECLARE_VERIFIER
10996
10997 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V)                            \
10998   V(kStringTable, "string_table", "(Internalized strings)")             \
10999   V(kExternalStringsTable, "external_strings_table", "(External strings)") \
11000   V(kStrongRootList, "strong_root_list", "(Strong roots)")              \
11001   V(kSmiRootList, "smi_root_list", "(Smi roots)")                       \
11002   V(kInternalizedString, "internalized_string", "(Internal string)")    \
11003   V(kBootstrapper, "bootstrapper", "(Bootstrapper)")                    \
11004   V(kTop, "top", "(Isolate)")                                           \
11005   V(kRelocatable, "relocatable", "(Relocatable)")                       \
11006   V(kDebug, "debug", "(Debugger)")                                      \
11007   V(kCompilationCache, "compilationcache", "(Compilation cache)")       \
11008   V(kHandleScope, "handlescope", "(Handle scope)")                      \
11009   V(kBuiltins, "builtins", "(Builtins)")                                \
11010   V(kGlobalHandles, "globalhandles", "(Global handles)")                \
11011   V(kEternalHandles, "eternalhandles", "(Eternal handles)")             \
11012   V(kThreadManager, "threadmanager", "(Thread manager)")                \
11013   V(kExtensions, "Extensions", "(Extensions)")
11014
11015 class VisitorSynchronization : public AllStatic {
11016  public:
11017 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
11018   enum SyncTag {
11019     VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
11020     kNumberOfSyncTags
11021   };
11022 #undef DECLARE_ENUM
11023
11024   static const char* const kTags[kNumberOfSyncTags];
11025   static const char* const kTagNames[kNumberOfSyncTags];
11026 };
11027
11028 // Abstract base class for visiting, and optionally modifying, the
11029 // pointers contained in Objects. Used in GC and serialization/deserialization.
11030 class ObjectVisitor BASE_EMBEDDED {
11031  public:
11032   virtual ~ObjectVisitor() {}
11033
11034   // Visits a contiguous arrays of pointers in the half-open range
11035   // [start, end). Any or all of the values may be modified on return.
11036   virtual void VisitPointers(Object** start, Object** end) = 0;
11037
11038   // Handy shorthand for visiting a single pointer.
11039   virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
11040
11041   // Visit weak next_code_link in Code object.
11042   virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
11043
11044   // To allow lazy clearing of inline caches the visitor has
11045   // a rich interface for iterating over Code objects..
11046
11047   // Visits a code target in the instruction stream.
11048   virtual void VisitCodeTarget(RelocInfo* rinfo);
11049
11050   // Visits a code entry in a JS function.
11051   virtual void VisitCodeEntry(Address entry_address);
11052
11053   // Visits a global property cell reference in the instruction stream.
11054   virtual void VisitCell(RelocInfo* rinfo);
11055
11056   // Visits a runtime entry in the instruction stream.
11057   virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
11058
11059   // Visits the resource of an ASCII or two-byte string.
11060   virtual void VisitExternalAsciiString(
11061       v8::String::ExternalAsciiStringResource** resource) {}
11062   virtual void VisitExternalTwoByteString(
11063       v8::String::ExternalStringResource** resource) {}
11064
11065   // Visits a debug call target in the instruction stream.
11066   virtual void VisitDebugTarget(RelocInfo* rinfo);
11067
11068   // Visits the byte sequence in a function's prologue that contains information
11069   // about the code's age.
11070   virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11071
11072   // Visit pointer embedded into a code object.
11073   virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11074
11075   // Visits an external reference embedded into a code object.
11076   virtual void VisitExternalReference(RelocInfo* rinfo);
11077
11078   // Visits an external reference. The value may be modified on return.
11079   virtual void VisitExternalReference(Address* p) {}
11080
11081   // Visits a handle that has an embedder-assigned class ID.
11082   virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11083
11084   // Intended for serialization/deserialization checking: insert, or
11085   // check for the presence of, a tag at this position in the stream.
11086   // Also used for marking up GC roots in heap snapshots.
11087   virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11088 };
11089
11090
11091 class StructBodyDescriptor : public
11092   FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11093  public:
11094   static inline int SizeOf(Map* map, HeapObject* object) {
11095     return map->instance_size();
11096   }
11097 };
11098
11099
11100 // BooleanBit is a helper class for setting and getting a bit in an
11101 // integer or Smi.
11102 class BooleanBit : public AllStatic {
11103  public:
11104   static inline bool get(Smi* smi, int bit_position) {
11105     return get(smi->value(), bit_position);
11106   }
11107
11108   static inline bool get(int value, int bit_position) {
11109     return (value & (1 << bit_position)) != 0;
11110   }
11111
11112   static inline Smi* set(Smi* smi, int bit_position, bool v) {
11113     return Smi::FromInt(set(smi->value(), bit_position, v));
11114   }
11115
11116   static inline int set(int value, int bit_position, bool v) {
11117     if (v) {
11118       value |= (1 << bit_position);
11119     } else {
11120       value &= ~(1 << bit_position);
11121     }
11122     return value;
11123   }
11124 };
11125
11126 } }  // namespace v8::internal
11127
11128 #endif  // V8_OBJECTS_H_