a2884caddd84f8d543dab2daf5bbbe5c597a4fe3
[profile/ivi/qtjsbackend.git] / src / 3rdparty / 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 "builtins.h"
33 #include "list.h"
34 #include "property-details.h"
35 #include "smart-array-pointer.h"
36 #include "unicode-inl.h"
37 #if V8_TARGET_ARCH_ARM
38 #include "arm/constants-arm.h"
39 #elif V8_TARGET_ARCH_MIPS
40 #include "mips/constants-mips.h"
41 #endif
42 #include "v8checks.h"
43
44
45 //
46 // Most object types in the V8 JavaScript are described in this file.
47 //
48 // Inheritance hierarchy:
49 // - MaybeObject    (an object or a failure)
50 //   - Failure      (immediate for marking failed operation)
51 //   - Object
52 //     - Smi          (immediate small integer)
53 //     - HeapObject   (superclass for everything allocated in the heap)
54 //       - JSReceiver  (suitable for property access)
55 //         - JSObject
56 //           - JSArray
57 //           - JSSet
58 //           - JSMap
59 //           - JSWeakMap
60 //           - JSRegExp
61 //           - JSFunction
62 //           - JSModule
63 //           - GlobalObject
64 //             - JSGlobalObject
65 //             - JSBuiltinsObject
66 //           - JSGlobalProxy
67 //           - JSValue
68 //             - JSDate
69 //           - JSMessageObject
70 //         - JSProxy
71 //           - JSFunctionProxy
72 //       - FixedArrayBase
73 //         - ByteArray
74 //         - FixedArray
75 //           - DescriptorArray
76 //           - HashTable
77 //             - Dictionary
78 //             - SymbolTable
79 //             - CompilationCacheTable
80 //             - CodeCacheHashTable
81 //             - MapCache
82 //           - Context
83 //           - JSFunctionResultCache
84 //           - ScopeInfo
85 //         - FixedDoubleArray
86 //         - ExternalArray
87 //           - ExternalPixelArray
88 //           - ExternalByteArray
89 //           - ExternalUnsignedByteArray
90 //           - ExternalShortArray
91 //           - ExternalUnsignedShortArray
92 //           - ExternalIntArray
93 //           - ExternalUnsignedIntArray
94 //           - ExternalFloatArray
95 //       - String
96 //         - SeqString
97 //           - SeqAsciiString
98 //           - SeqTwoByteString
99 //         - SlicedString
100 //         - ConsString
101 //         - ExternalString
102 //           - ExternalAsciiString
103 //           - ExternalTwoByteString
104 //       - HeapNumber
105 //       - Code
106 //       - Map
107 //       - Oddball
108 //       - Foreign
109 //       - SharedFunctionInfo
110 //       - Struct
111 //         - AccessorInfo
112 //         - AccessorPair
113 //         - AccessCheckInfo
114 //         - InterceptorInfo
115 //         - CallHandlerInfo
116 //         - TemplateInfo
117 //           - FunctionTemplateInfo
118 //           - ObjectTemplateInfo
119 //         - Script
120 //         - SignatureInfo
121 //         - TypeSwitchInfo
122 //         - DebugInfo
123 //         - BreakPointInfo
124 //         - CodeCache
125 //
126 // Formats of Object*:
127 //  Smi:        [31 bit signed int] 0
128 //  HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
129 //  Failure:    [30 bit signed int] 11
130
131 namespace v8 {
132 namespace internal {
133
134 enum ElementsKind {
135   // The "fast" kind for elements that only contain SMI values. Must be first
136   // to make it possible to efficiently check maps for this kind.
137   FAST_SMI_ONLY_ELEMENTS,
138
139   // The "fast" kind for tagged values. Must be second to make it possible to
140   // efficiently check maps for this and the FAST_SMI_ONLY_ELEMENTS kind
141   // together at once.
142   FAST_ELEMENTS,
143
144   // The "fast" kind for unwrapped, non-tagged double values.
145   FAST_DOUBLE_ELEMENTS,
146
147   // The "slow" kind.
148   DICTIONARY_ELEMENTS,
149   NON_STRICT_ARGUMENTS_ELEMENTS,
150   // The "fast" kind for external arrays
151   EXTERNAL_BYTE_ELEMENTS,
152   EXTERNAL_UNSIGNED_BYTE_ELEMENTS,
153   EXTERNAL_SHORT_ELEMENTS,
154   EXTERNAL_UNSIGNED_SHORT_ELEMENTS,
155   EXTERNAL_INT_ELEMENTS,
156   EXTERNAL_UNSIGNED_INT_ELEMENTS,
157   EXTERNAL_FLOAT_ELEMENTS,
158   EXTERNAL_DOUBLE_ELEMENTS,
159   EXTERNAL_PIXEL_ELEMENTS,
160
161   // Derived constants from ElementsKind
162   FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_BYTE_ELEMENTS,
163   LAST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS,
164   FIRST_ELEMENTS_KIND = FAST_SMI_ONLY_ELEMENTS,
165   LAST_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS
166 };
167
168 enum CompareMapMode {
169   REQUIRE_EXACT_MAP,
170   ALLOW_ELEMENT_TRANSITION_MAPS
171 };
172
173 enum KeyedAccessGrowMode {
174   DO_NOT_ALLOW_JSARRAY_GROWTH,
175   ALLOW_JSARRAY_GROWTH
176 };
177
178 const int kElementsKindCount = LAST_ELEMENTS_KIND - FIRST_ELEMENTS_KIND + 1;
179
180 void PrintElementsKind(FILE* out, ElementsKind kind);
181
182 inline bool IsMoreGeneralElementsKindTransition(ElementsKind from_kind,
183                                                 ElementsKind to_kind);
184
185 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
186 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
187
188
189 // PropertyNormalizationMode is used to specify whether to keep
190 // inobject properties when normalizing properties of a JSObject.
191 enum PropertyNormalizationMode {
192   CLEAR_INOBJECT_PROPERTIES,
193   KEEP_INOBJECT_PROPERTIES
194 };
195
196
197 // NormalizedMapSharingMode is used to specify whether a map may be shared
198 // by different objects with normalized properties.
199 enum NormalizedMapSharingMode {
200   UNIQUE_NORMALIZED_MAP,
201   SHARED_NORMALIZED_MAP
202 };
203
204
205 // Indicates whether a get method should implicitly create the object looked up.
206 enum CreationFlag {
207   ALLOW_CREATION,
208   OMIT_CREATION
209 };
210
211
212 // Instance size sentinel for objects of variable size.
213 const int kVariableSizeSentinel = 0;
214
215
216 // All Maps have a field instance_type containing a InstanceType.
217 // It describes the type of the instances.
218 //
219 // As an example, a JavaScript object is a heap object and its map
220 // instance_type is JS_OBJECT_TYPE.
221 //
222 // The names of the string instance types are intended to systematically
223 // mirror their encoding in the instance_type field of the map.  The default
224 // encoding is considered TWO_BYTE.  It is not mentioned in the name.  ASCII
225 // encoding is mentioned explicitly in the name.  Likewise, the default
226 // representation is considered sequential.  It is not mentioned in the
227 // name.  The other representations (e.g. CONS, EXTERNAL) are explicitly
228 // mentioned.  Finally, the string is either a SYMBOL_TYPE (if it is a
229 // symbol) or a STRING_TYPE (if it is not a symbol).
230 //
231 // NOTE: The following things are some that depend on the string types having
232 // instance_types that are less than those of all other types:
233 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
234 // Object::IsString.
235 //
236 // NOTE: Everything following JS_VALUE_TYPE is considered a
237 // JSObject for GC purposes. The first four entries here have typeof
238 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
239 #define INSTANCE_TYPE_LIST_ALL(V)                                              \
240   V(SYMBOL_TYPE)                                                               \
241   V(ASCII_SYMBOL_TYPE)                                                         \
242   V(CONS_SYMBOL_TYPE)                                                          \
243   V(CONS_ASCII_SYMBOL_TYPE)                                                    \
244   V(EXTERNAL_SYMBOL_TYPE)                                                      \
245   V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE)                                      \
246   V(EXTERNAL_ASCII_SYMBOL_TYPE)                                                \
247   V(SHORT_EXTERNAL_SYMBOL_TYPE)                                                \
248   V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE)                                \
249   V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE)                                          \
250   V(STRING_TYPE)                                                               \
251   V(ASCII_STRING_TYPE)                                                         \
252   V(CONS_STRING_TYPE)                                                          \
253   V(CONS_ASCII_STRING_TYPE)                                                    \
254   V(SLICED_STRING_TYPE)                                                        \
255   V(EXTERNAL_STRING_TYPE)                                                      \
256   V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE)                                      \
257   V(EXTERNAL_ASCII_STRING_TYPE)                                                \
258   V(SHORT_EXTERNAL_STRING_TYPE)                                                \
259   V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE)                                \
260   V(SHORT_EXTERNAL_ASCII_STRING_TYPE)                                          \
261   V(PRIVATE_EXTERNAL_ASCII_STRING_TYPE)                                        \
262                                                                                \
263   V(MAP_TYPE)                                                                  \
264   V(CODE_TYPE)                                                                 \
265   V(ODDBALL_TYPE)                                                              \
266   V(JS_GLOBAL_PROPERTY_CELL_TYPE)                                              \
267                                                                                \
268   V(HEAP_NUMBER_TYPE)                                                          \
269   V(FOREIGN_TYPE)                                                              \
270   V(BYTE_ARRAY_TYPE)                                                           \
271   V(FREE_SPACE_TYPE)                                                           \
272   /* Note: the order of these external array */                                \
273   /* types is relied upon in */                                                \
274   /* Object::IsExternalArray(). */                                             \
275   V(EXTERNAL_BYTE_ARRAY_TYPE)                                                  \
276   V(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE)                                         \
277   V(EXTERNAL_SHORT_ARRAY_TYPE)                                                 \
278   V(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE)                                        \
279   V(EXTERNAL_INT_ARRAY_TYPE)                                                   \
280   V(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE)                                          \
281   V(EXTERNAL_FLOAT_ARRAY_TYPE)                                                 \
282   V(EXTERNAL_PIXEL_ARRAY_TYPE)                                                 \
283   V(FILLER_TYPE)                                                               \
284                                                                                \
285   V(ACCESSOR_INFO_TYPE)                                                        \
286   V(ACCESSOR_PAIR_TYPE)                                                        \
287   V(ACCESS_CHECK_INFO_TYPE)                                                    \
288   V(INTERCEPTOR_INFO_TYPE)                                                     \
289   V(CALL_HANDLER_INFO_TYPE)                                                    \
290   V(FUNCTION_TEMPLATE_INFO_TYPE)                                               \
291   V(OBJECT_TEMPLATE_INFO_TYPE)                                                 \
292   V(SIGNATURE_INFO_TYPE)                                                       \
293   V(TYPE_SWITCH_INFO_TYPE)                                                     \
294   V(SCRIPT_TYPE)                                                               \
295   V(CODE_CACHE_TYPE)                                                           \
296   V(POLYMORPHIC_CODE_CACHE_TYPE)                                               \
297   V(TYPE_FEEDBACK_INFO_TYPE)                                                   \
298   V(ALIASED_ARGUMENTS_ENTRY_TYPE)                                              \
299                                                                                \
300   V(FIXED_ARRAY_TYPE)                                                          \
301   V(FIXED_DOUBLE_ARRAY_TYPE)                                                   \
302   V(SHARED_FUNCTION_INFO_TYPE)                                                 \
303                                                                                \
304   V(JS_MESSAGE_OBJECT_TYPE)                                                    \
305                                                                                \
306   V(JS_VALUE_TYPE)                                                             \
307   V(JS_DATE_TYPE)                                                              \
308   V(JS_OBJECT_TYPE)                                                            \
309   V(JS_CONTEXT_EXTENSION_OBJECT_TYPE)                                          \
310   V(JS_MODULE_TYPE)                                                            \
311   V(JS_GLOBAL_OBJECT_TYPE)                                                     \
312   V(JS_BUILTINS_OBJECT_TYPE)                                                   \
313   V(JS_GLOBAL_PROXY_TYPE)                                                      \
314   V(JS_ARRAY_TYPE)                                                             \
315   V(JS_PROXY_TYPE)                                                             \
316   V(JS_WEAK_MAP_TYPE)                                                          \
317   V(JS_REGEXP_TYPE)                                                            \
318                                                                                \
319   V(JS_FUNCTION_TYPE)                                                          \
320   V(JS_FUNCTION_PROXY_TYPE)                                                    \
321
322 #ifdef ENABLE_DEBUGGER_SUPPORT
323 #define INSTANCE_TYPE_LIST_DEBUGGER(V)                                         \
324   V(DEBUG_INFO_TYPE)                                                           \
325   V(BREAK_POINT_INFO_TYPE)
326 #else
327 #define INSTANCE_TYPE_LIST_DEBUGGER(V)
328 #endif
329
330 #define INSTANCE_TYPE_LIST(V)                                                  \
331   INSTANCE_TYPE_LIST_ALL(V)                                                    \
332   INSTANCE_TYPE_LIST_DEBUGGER(V)
333
334
335 // Since string types are not consecutive, this macro is used to
336 // iterate over them.
337 #define STRING_TYPE_LIST(V)                                                    \
338   V(SYMBOL_TYPE,                                                               \
339     kVariableSizeSentinel,                                                     \
340     symbol,                                                                    \
341     Symbol)                                                                    \
342   V(ASCII_SYMBOL_TYPE,                                                         \
343     kVariableSizeSentinel,                                                     \
344     ascii_symbol,                                                              \
345     AsciiSymbol)                                                               \
346   V(CONS_SYMBOL_TYPE,                                                          \
347     ConsString::kSize,                                                         \
348     cons_symbol,                                                               \
349     ConsSymbol)                                                                \
350   V(CONS_ASCII_SYMBOL_TYPE,                                                    \
351     ConsString::kSize,                                                         \
352     cons_ascii_symbol,                                                         \
353     ConsAsciiSymbol)                                                           \
354   V(EXTERNAL_SYMBOL_TYPE,                                                      \
355     ExternalTwoByteString::kSize,                                              \
356     external_symbol,                                                           \
357     ExternalSymbol)                                                            \
358   V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE,                                      \
359     ExternalTwoByteString::kSize,                                              \
360     external_symbol_with_ascii_data,                                           \
361     ExternalSymbolWithAsciiData)                                               \
362   V(EXTERNAL_ASCII_SYMBOL_TYPE,                                                \
363     ExternalAsciiString::kSize,                                                \
364     external_ascii_symbol,                                                     \
365     ExternalAsciiSymbol)                                                       \
366   V(SHORT_EXTERNAL_SYMBOL_TYPE,                                                \
367     ExternalTwoByteString::kShortSize,                                         \
368     short_external_symbol,                                                     \
369     ShortExternalSymbol)                                                       \
370   V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE,                                \
371     ExternalTwoByteString::kShortSize,                                         \
372     short_external_symbol_with_ascii_data,                                     \
373     ShortExternalSymbolWithAsciiData)                                          \
374   V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE,                                          \
375     ExternalAsciiString::kShortSize,                                           \
376     short_external_ascii_symbol,                                               \
377     ShortExternalAsciiSymbol)                                                  \
378   V(STRING_TYPE,                                                               \
379     kVariableSizeSentinel,                                                     \
380     string,                                                                    \
381     String)                                                                    \
382   V(ASCII_STRING_TYPE,                                                         \
383     kVariableSizeSentinel,                                                     \
384     ascii_string,                                                              \
385     AsciiString)                                                               \
386   V(CONS_STRING_TYPE,                                                          \
387     ConsString::kSize,                                                         \
388     cons_string,                                                               \
389     ConsString)                                                                \
390   V(CONS_ASCII_STRING_TYPE,                                                    \
391     ConsString::kSize,                                                         \
392     cons_ascii_string,                                                         \
393     ConsAsciiString)                                                           \
394   V(SLICED_STRING_TYPE,                                                        \
395     SlicedString::kSize,                                                       \
396     sliced_string,                                                             \
397     SlicedString)                                                              \
398   V(SLICED_ASCII_STRING_TYPE,                                                  \
399     SlicedString::kSize,                                                       \
400     sliced_ascii_string,                                                       \
401     SlicedAsciiString)                                                         \
402   V(EXTERNAL_STRING_TYPE,                                                      \
403     ExternalTwoByteString::kSize,                                              \
404     external_string,                                                           \
405     ExternalString)                                                            \
406   V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE,                                      \
407     ExternalTwoByteString::kSize,                                              \
408     external_string_with_ascii_data,                                           \
409     ExternalStringWithAsciiData)                                               \
410   V(EXTERNAL_ASCII_STRING_TYPE,                                                \
411     ExternalAsciiString::kSize,                                                \
412     external_ascii_string,                                                     \
413     ExternalAsciiString)                                                       \
414   V(SHORT_EXTERNAL_STRING_TYPE,                                                \
415     ExternalTwoByteString::kShortSize,                                         \
416     short_external_string,                                                     \
417     ShortExternalString)                                                       \
418   V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE,                                \
419     ExternalTwoByteString::kShortSize,                                         \
420     short_external_string_with_ascii_data,                                     \
421     ShortExternalStringWithAsciiData)                                          \
422   V(SHORT_EXTERNAL_ASCII_STRING_TYPE,                                          \
423     ExternalAsciiString::kShortSize,                                           \
424     short_external_ascii_string,                                               \
425     ShortExternalAsciiString)
426
427 // A struct is a simple object a set of object-valued fields.  Including an
428 // object type in this causes the compiler to generate most of the boilerplate
429 // code for the class including allocation and garbage collection routines,
430 // casts and predicates.  All you need to define is the class, methods and
431 // object verification routines.  Easy, no?
432 //
433 // Note that for subtle reasons related to the ordering or numerical values of
434 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
435 // manually.
436 #define STRUCT_LIST_ALL(V)                                                     \
437   V(ACCESSOR_INFO, AccessorInfo, accessor_info)                                \
438   V(ACCESSOR_PAIR, AccessorPair, accessor_pair)                                \
439   V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info)                     \
440   V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info)                       \
441   V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info)                     \
442   V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info)      \
443   V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info)            \
444   V(SIGNATURE_INFO, SignatureInfo, signature_info)                             \
445   V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info)                        \
446   V(SCRIPT, Script, script)                                                    \
447   V(CODE_CACHE, CodeCache, code_cache)                                         \
448   V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache)      \
449   V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info)                  \
450   V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
451
452 #ifdef ENABLE_DEBUGGER_SUPPORT
453 #define STRUCT_LIST_DEBUGGER(V)                                                \
454   V(DEBUG_INFO, DebugInfo, debug_info)                                         \
455   V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
456 #else
457 #define STRUCT_LIST_DEBUGGER(V)
458 #endif
459
460 #define STRUCT_LIST(V)                                                         \
461   STRUCT_LIST_ALL(V)                                                           \
462   STRUCT_LIST_DEBUGGER(V)
463
464 // We use the full 8 bits of the instance_type field to encode heap object
465 // instance types.  The high-order bit (bit 7) is set if the object is not a
466 // string, and cleared if it is a string.
467 const uint32_t kIsNotStringMask = 0x80;
468 const uint32_t kStringTag = 0x0;
469 const uint32_t kNotStringTag = 0x80;
470
471 // Bit 6 indicates that the object is a symbol (if set) or not (if cleared).
472 // There are not enough types that the non-string types (with bit 7 set) can
473 // have bit 6 set too.
474 const uint32_t kIsSymbolMask = 0x40;
475 const uint32_t kNotSymbolTag = 0x0;
476 const uint32_t kSymbolTag = 0x40;
477
478 // If bit 7 is clear then bit 2 indicates whether the string consists of
479 // two-byte characters or one-byte characters.
480 const uint32_t kStringEncodingMask = 0x4;
481 const uint32_t kTwoByteStringTag = 0x0;
482 const uint32_t kAsciiStringTag = 0x4;
483
484 // If bit 7 is clear, the low-order 2 bits indicate the representation
485 // of the string.
486 const uint32_t kStringRepresentationMask = 0x03;
487 enum StringRepresentationTag {
488   kSeqStringTag = 0x0,
489   kConsStringTag = 0x1,
490   kExternalStringTag = 0x2,
491   kSlicedStringTag = 0x3
492 };
493 const uint32_t kIsIndirectStringMask = 0x1;
494 const uint32_t kIsIndirectStringTag = 0x1;
495 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
496 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
497 STATIC_ASSERT(
498     (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
499 STATIC_ASSERT(
500     (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
501
502 // Use this mask to distinguish between cons and slice only after making
503 // sure that the string is one of the two (an indirect string).
504 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
505 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
506
507 // If bit 7 is clear, then bit 3 indicates whether this two-byte
508 // string actually contains ASCII data.
509 const uint32_t kAsciiDataHintMask = 0x08;
510 const uint32_t kAsciiDataHintTag = 0x08;
511
512 // If bit 7 is clear and string representation indicates an external string,
513 // then bit 4 indicates whether the data pointer is cached.
514 const uint32_t kShortExternalStringMask = 0x10;
515 const uint32_t kShortExternalStringTag = 0x10;
516
517
518 // A ConsString with an empty string as the right side is a candidate
519 // for being shortcut by the garbage collector unless it is a
520 // symbol. It's not common to have non-flat symbols, so we do not
521 // shortcut them thereby avoiding turning symbols into strings. See
522 // heap.cc and mark-compact.cc.
523 const uint32_t kShortcutTypeMask =
524     kIsNotStringMask |
525     kIsSymbolMask |
526     kStringRepresentationMask;
527 const uint32_t kShortcutTypeTag = kConsStringTag;
528
529
530 enum InstanceType {
531   // String types.
532   SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kSeqStringTag,
533   ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kSeqStringTag,
534   CONS_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kConsStringTag,
535   CONS_ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kConsStringTag,
536   SHORT_EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag |
537                                kExternalStringTag | kShortExternalStringTag,
538   SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
539       kTwoByteStringTag | kSymbolTag | kExternalStringTag |
540       kAsciiDataHintTag | kShortExternalStringTag,
541   SHORT_EXTERNAL_ASCII_SYMBOL_TYPE = kAsciiStringTag | kExternalStringTag |
542                                      kSymbolTag | kShortExternalStringTag,
543   EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kExternalStringTag,
544   EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
545       kTwoByteStringTag | kSymbolTag | kExternalStringTag | kAsciiDataHintTag,
546   EXTERNAL_ASCII_SYMBOL_TYPE =
547       kAsciiStringTag | kSymbolTag | kExternalStringTag,
548   STRING_TYPE = kTwoByteStringTag | kSeqStringTag,
549   ASCII_STRING_TYPE = kAsciiStringTag | kSeqStringTag,
550   CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag,
551   CONS_ASCII_STRING_TYPE = kAsciiStringTag | kConsStringTag,
552   SLICED_STRING_TYPE = kTwoByteStringTag | kSlicedStringTag,
553   SLICED_ASCII_STRING_TYPE = kAsciiStringTag | kSlicedStringTag,
554   SHORT_EXTERNAL_STRING_TYPE =
555       kTwoByteStringTag | kExternalStringTag | kShortExternalStringTag,
556   SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
557       kTwoByteStringTag | kExternalStringTag |
558       kAsciiDataHintTag | kShortExternalStringTag,
559   SHORT_EXTERNAL_ASCII_STRING_TYPE =
560       kAsciiStringTag | kExternalStringTag | kShortExternalStringTag,
561   EXTERNAL_STRING_TYPE = kTwoByteStringTag | kExternalStringTag,
562   EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
563       kTwoByteStringTag | kExternalStringTag | kAsciiDataHintTag,
564   // LAST_STRING_TYPE
565   EXTERNAL_ASCII_STRING_TYPE = kAsciiStringTag | kExternalStringTag,
566   PRIVATE_EXTERNAL_ASCII_STRING_TYPE = EXTERNAL_ASCII_STRING_TYPE,
567
568   // Objects allocated in their own spaces (never in new space).
569   MAP_TYPE = kNotStringTag,  // FIRST_NONSTRING_TYPE
570   CODE_TYPE,
571   ODDBALL_TYPE,
572   JS_GLOBAL_PROPERTY_CELL_TYPE,
573
574   // "Data", objects that cannot contain non-map-word pointers to heap
575   // objects.
576   HEAP_NUMBER_TYPE,
577   FOREIGN_TYPE,
578   BYTE_ARRAY_TYPE,
579   FREE_SPACE_TYPE,
580   EXTERNAL_BYTE_ARRAY_TYPE,  // FIRST_EXTERNAL_ARRAY_TYPE
581   EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
582   EXTERNAL_SHORT_ARRAY_TYPE,
583   EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
584   EXTERNAL_INT_ARRAY_TYPE,
585   EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
586   EXTERNAL_FLOAT_ARRAY_TYPE,
587   EXTERNAL_DOUBLE_ARRAY_TYPE,
588   EXTERNAL_PIXEL_ARRAY_TYPE,  // LAST_EXTERNAL_ARRAY_TYPE
589   FIXED_DOUBLE_ARRAY_TYPE,
590   FILLER_TYPE,  // LAST_DATA_TYPE
591
592   // Structs.
593   ACCESSOR_INFO_TYPE,
594   ACCESSOR_PAIR_TYPE,
595   ACCESS_CHECK_INFO_TYPE,
596   INTERCEPTOR_INFO_TYPE,
597   CALL_HANDLER_INFO_TYPE,
598   FUNCTION_TEMPLATE_INFO_TYPE,
599   OBJECT_TEMPLATE_INFO_TYPE,
600   SIGNATURE_INFO_TYPE,
601   TYPE_SWITCH_INFO_TYPE,
602   SCRIPT_TYPE,
603   CODE_CACHE_TYPE,
604   POLYMORPHIC_CODE_CACHE_TYPE,
605   TYPE_FEEDBACK_INFO_TYPE,
606   ALIASED_ARGUMENTS_ENTRY_TYPE,
607   // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
608   // is defined. However as include/v8.h contain some of the instance type
609   // constants always having them avoids them getting different numbers
610   // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
611   DEBUG_INFO_TYPE,
612   BREAK_POINT_INFO_TYPE,
613
614   FIXED_ARRAY_TYPE,
615   SHARED_FUNCTION_INFO_TYPE,
616
617   JS_MESSAGE_OBJECT_TYPE,
618
619   // All the following types are subtypes of JSReceiver, which corresponds to
620   // objects in the JS sense. The first and the last type in this range are
621   // the two forms of function. This organization enables using the same
622   // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
623   // NONCALLABLE_JS_OBJECT range.
624   JS_FUNCTION_PROXY_TYPE,  // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
625   JS_PROXY_TYPE,  // LAST_JS_PROXY_TYPE
626
627   JS_VALUE_TYPE,  // FIRST_JS_OBJECT_TYPE
628   JS_DATE_TYPE,
629   JS_OBJECT_TYPE,
630   JS_CONTEXT_EXTENSION_OBJECT_TYPE,
631   JS_MODULE_TYPE,
632   JS_GLOBAL_OBJECT_TYPE,
633   JS_BUILTINS_OBJECT_TYPE,
634   JS_GLOBAL_PROXY_TYPE,
635   JS_ARRAY_TYPE,
636   JS_SET_TYPE,
637   JS_MAP_TYPE,
638   JS_WEAK_MAP_TYPE,
639
640   JS_REGEXP_TYPE,
641
642   JS_FUNCTION_TYPE,  // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
643
644   // Pseudo-types
645   FIRST_TYPE = 0x0,
646   LAST_TYPE = JS_FUNCTION_TYPE,
647   INVALID_TYPE = FIRST_TYPE - 1,
648   FIRST_NONSTRING_TYPE = MAP_TYPE,
649   // Boundaries for testing for an external array.
650   FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_BYTE_ARRAY_TYPE,
651   LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_PIXEL_ARRAY_TYPE,
652   // Boundary for promotion to old data space/old pointer space.
653   LAST_DATA_TYPE = FILLER_TYPE,
654   // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
655   // Note that there is no range for JSObject or JSProxy, since their subtypes
656   // are not continuous in this enum! The enum ranges instead reflect the
657   // external class names, where proxies are treated as either ordinary objects,
658   // or functions.
659   FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
660   LAST_JS_RECEIVER_TYPE = LAST_TYPE,
661   // Boundaries for testing the types represented as JSObject
662   FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
663   LAST_JS_OBJECT_TYPE = LAST_TYPE,
664   // Boundaries for testing the types represented as JSProxy
665   FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
666   LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
667   // Boundaries for testing whether the type is a JavaScript object.
668   FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
669   LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
670   // Boundaries for testing the types for which typeof is "object".
671   FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
672   LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
673   // Note that the types for which typeof is "function" are not continuous.
674   // Define this so that we can put assertions on discrete checks.
675   NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
676 };
677
678 const int kExternalArrayTypeCount =
679     LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
680
681 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
682 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
683 STATIC_CHECK(ODDBALL_TYPE == Internals::kOddballType);
684 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
685
686
687 enum CompareResult {
688   LESS      = -1,
689   EQUAL     =  0,
690   GREATER   =  1,
691
692   NOT_EQUAL = GREATER
693 };
694
695
696 #define DECL_BOOLEAN_ACCESSORS(name)   \
697   inline bool name();                  \
698   inline void set_##name(bool value);  \
699
700
701 #define DECL_ACCESSORS(name, type)                                      \
702   inline type* name();                                                  \
703   inline void set_##name(type* value,                                   \
704                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
705
706
707 class DictionaryElementsAccessor;
708 class ElementsAccessor;
709 class FixedArrayBase;
710 class ObjectVisitor;
711 class StringStream;
712 class Failure;
713
714 struct ValueInfo : public Malloced {
715   ValueInfo() : type(FIRST_TYPE), ptr(NULL), str(NULL), number(0) { }
716   InstanceType type;
717   Object* ptr;
718   const char* str;
719   double number;
720 };
721
722
723 // A template-ized version of the IsXXX functions.
724 template <class C> static inline bool Is(Object* obj);
725
726
727 class MaybeObject BASE_EMBEDDED {
728  public:
729   inline bool IsFailure();
730   inline bool IsRetryAfterGC();
731   inline bool IsOutOfMemory();
732   inline bool IsException();
733   INLINE(bool IsTheHole());
734   inline bool ToObject(Object** obj) {
735     if (IsFailure()) return false;
736     *obj = reinterpret_cast<Object*>(this);
737     return true;
738   }
739   inline Failure* ToFailureUnchecked() {
740     ASSERT(IsFailure());
741     return reinterpret_cast<Failure*>(this);
742   }
743   inline Object* ToObjectUnchecked() {
744     ASSERT(!IsFailure());
745     return reinterpret_cast<Object*>(this);
746   }
747   inline Object* ToObjectChecked() {
748     CHECK(!IsFailure());
749     return reinterpret_cast<Object*>(this);
750   }
751
752   template<typename T>
753   inline bool To(T** obj) {
754     if (IsFailure()) return false;
755     *obj = T::cast(reinterpret_cast<Object*>(this));
756     return true;
757   }
758
759 #ifdef OBJECT_PRINT
760   // Prints this object with details.
761   inline void Print() {
762     Print(stdout);
763   }
764   inline void PrintLn() {
765     PrintLn(stdout);
766   }
767   void Print(FILE* out);
768   void PrintLn(FILE* out);
769 #endif
770 #ifdef DEBUG
771   // Verifies the object.
772   void Verify();
773 #endif
774 };
775
776
777 #define OBJECT_TYPE_LIST(V)                    \
778   V(Smi)                                       \
779   V(HeapObject)                                \
780   V(Number)                                    \
781
782 #define HEAP_OBJECT_TYPE_LIST(V)               \
783   V(HeapNumber)                                \
784   V(String)                                    \
785   V(Symbol)                                    \
786   V(SeqString)                                 \
787   V(ExternalString)                            \
788   V(ConsString)                                \
789   V(SlicedString)                              \
790   V(ExternalTwoByteString)                     \
791   V(ExternalAsciiString)                       \
792   V(SeqTwoByteString)                          \
793   V(SeqAsciiString)                            \
794                                                \
795   V(ExternalArray)                             \
796   V(ExternalByteArray)                         \
797   V(ExternalUnsignedByteArray)                 \
798   V(ExternalShortArray)                        \
799   V(ExternalUnsignedShortArray)                \
800   V(ExternalIntArray)                          \
801   V(ExternalUnsignedIntArray)                  \
802   V(ExternalFloatArray)                        \
803   V(ExternalDoubleArray)                       \
804   V(ExternalPixelArray)                        \
805   V(ByteArray)                                 \
806   V(FreeSpace)                                 \
807   V(JSReceiver)                                \
808   V(JSObject)                                  \
809   V(JSContextExtensionObject)                  \
810   V(JSModule)                                  \
811   V(Map)                                       \
812   V(DescriptorArray)                           \
813   V(DeoptimizationInputData)                   \
814   V(DeoptimizationOutputData)                  \
815   V(TypeFeedbackCells)                         \
816   V(FixedArray)                                \
817   V(FixedDoubleArray)                          \
818   V(Context)                                   \
819   V(GlobalContext)                             \
820   V(ModuleContext)                             \
821   V(ScopeInfo)                                 \
822   V(JSFunction)                                \
823   V(Code)                                      \
824   V(Oddball)                                   \
825   V(SharedFunctionInfo)                        \
826   V(JSValue)                                   \
827   V(JSDate)                                    \
828   V(JSMessageObject)                           \
829   V(StringWrapper)                             \
830   V(Foreign)                                   \
831   V(Boolean)                                   \
832   V(JSArray)                                   \
833   V(JSProxy)                                   \
834   V(JSFunctionProxy)                           \
835   V(JSSet)                                     \
836   V(JSMap)                                     \
837   V(JSWeakMap)                                 \
838   V(JSRegExp)                                  \
839   V(HashTable)                                 \
840   V(Dictionary)                                \
841   V(SymbolTable)                               \
842   V(JSFunctionResultCache)                     \
843   V(NormalizedMapCache)                        \
844   V(CompilationCacheTable)                     \
845   V(CodeCacheHashTable)                        \
846   V(PolymorphicCodeCacheHashTable)             \
847   V(MapCache)                                  \
848   V(Primitive)                                 \
849   V(GlobalObject)                              \
850   V(JSGlobalObject)                            \
851   V(JSBuiltinsObject)                          \
852   V(JSGlobalProxy)                             \
853   V(UndetectableObject)                        \
854   V(AccessCheckNeeded)                         \
855   V(JSGlobalPropertyCell)                      \
856
857
858 class JSReceiver;
859
860 // Object is the abstract superclass for all classes in the
861 // object hierarchy.
862 // Object does not use any virtual functions to avoid the
863 // allocation of the C++ vtable.
864 // Since Smi and Failure are subclasses of Object no
865 // data members can be present in Object.
866 class Object : public MaybeObject {
867  public:
868   // Type testing.
869   bool IsObject() { return true; }
870
871 #define IS_TYPE_FUNCTION_DECL(type_)  inline bool Is##type_();
872   OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
873   HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
874 #undef IS_TYPE_FUNCTION_DECL
875
876   inline bool IsFixedArrayBase();
877
878   // Returns true if this object is an instance of the specified
879   // function template.
880   inline bool IsInstanceOf(FunctionTemplateInfo* type);
881
882   inline bool IsStruct();
883 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
884   STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
885 #undef DECLARE_STRUCT_PREDICATE
886
887   INLINE(bool IsSpecObject());
888   INLINE(bool IsSpecFunction());
889
890   // Oddball testing.
891   INLINE(bool IsUndefined());
892   INLINE(bool IsNull());
893   INLINE(bool IsTheHole());  // Shadows MaybeObject's implementation.
894   INLINE(bool IsTrue());
895   INLINE(bool IsFalse());
896   inline bool IsArgumentsMarker();
897   inline bool NonFailureIsHeapObject();
898
899   // Filler objects (fillers and free space objects).
900   inline bool IsFiller();
901
902   // Extract the number.
903   inline double Number();
904   inline bool IsNaN();
905
906   // Returns true if the object is of the correct type to be used as a
907   // implementation of a JSObject's elements.
908   inline bool HasValidElements();
909
910   inline bool HasSpecificClassOf(String* name);
911
912   MUST_USE_RESULT MaybeObject* ToObject();             // ECMA-262 9.9.
913   Object* ToBoolean();                                 // ECMA-262 9.2.
914
915   // Convert to a JSObject if needed.
916   // global_context is used when creating wrapper object.
917   MUST_USE_RESULT MaybeObject* ToObject(Context* global_context);
918
919   // Converts this to a Smi if possible.
920   // Failure is returned otherwise.
921   MUST_USE_RESULT inline MaybeObject* ToSmi();
922
923   void Lookup(String* name, LookupResult* result);
924
925   // Property access.
926   MUST_USE_RESULT inline MaybeObject* GetProperty(String* key);
927   MUST_USE_RESULT inline MaybeObject* GetProperty(
928       String* key,
929       PropertyAttributes* attributes);
930   MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
931       Object* receiver,
932       String* key,
933       PropertyAttributes* attributes);
934
935   static Handle<Object> GetProperty(Handle<Object> object,
936                                     Handle<Object> receiver,
937                                     LookupResult* result,
938                                     Handle<String> key,
939                                     PropertyAttributes* attributes);
940
941   MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
942                                            LookupResult* result,
943                                            String* key,
944                                            PropertyAttributes* attributes);
945
946   MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
947                                                             JSReceiver* getter);
948
949   static Handle<Object> GetElement(Handle<Object> object, uint32_t index);
950   MUST_USE_RESULT inline MaybeObject* GetElement(uint32_t index);
951   // For use when we know that no exception can be thrown.
952   inline Object* GetElementNoExceptionThrown(uint32_t index);
953   MUST_USE_RESULT MaybeObject* GetElementWithReceiver(Object* receiver,
954                                                       uint32_t index);
955
956   // Return the object's prototype (might be Heap::null_value()).
957   Object* GetPrototype();
958
959   // Returns the permanent hash code associated with this object depending on
960   // the actual object type.  Might return a failure in case no hash was
961   // created yet or GC was caused by creation.
962   MUST_USE_RESULT MaybeObject* GetHash(CreationFlag flag);
963
964   // Checks whether this object has the same value as the given one.  This
965   // function is implemented according to ES5, section 9.12 and can be used
966   // to implement the Harmony "egal" function.
967   bool SameValue(Object* other);
968
969   // Tries to convert an object to an array index.  Returns true and sets
970   // the output parameter if it succeeds.
971   inline bool ToArrayIndex(uint32_t* index);
972
973   // Returns true if this is a JSValue containing a string and the index is
974   // < the length of the string.  Used to implement [] on strings.
975   inline bool IsStringObjectWithCharacterAt(uint32_t index);
976
977 #ifdef DEBUG
978   // Verify a pointer is a valid object pointer.
979   static void VerifyPointer(Object* p);
980 #endif
981
982   // Prints this object without details.
983   inline void ShortPrint() {
984     ShortPrint(stdout);
985   }
986   void ShortPrint(FILE* out);
987
988   // Prints this object without details to a message accumulator.
989   void ShortPrint(StringStream* accumulator);
990
991   // Casting: This cast is only needed to satisfy macros in objects-inl.h.
992   static Object* cast(Object* value) { return value; }
993
994   // Layout description.
995   static const int kHeaderSize = 0;  // Object does not take up any space.
996
997  private:
998   DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
999 };
1000
1001
1002 // Smi represents integer Numbers that can be stored in 31 bits.
1003 // Smis are immediate which means they are NOT allocated in the heap.
1004 // The this pointer has the following format: [31 bit signed int] 0
1005 // For long smis it has the following format:
1006 //     [32 bit signed int] [31 bits zero padding] 0
1007 // Smi stands for small integer.
1008 class Smi: public Object {
1009  public:
1010   // Returns the integer value.
1011   inline int value();
1012
1013   // Convert a value to a Smi object.
1014   static inline Smi* FromInt(int value);
1015
1016   static inline Smi* FromIntptr(intptr_t value);
1017
1018   // Returns whether value can be represented in a Smi.
1019   static inline bool IsValid(intptr_t value);
1020
1021   // Casting.
1022   static inline Smi* cast(Object* object);
1023
1024   // Dispatched behavior.
1025   inline void SmiPrint() {
1026     SmiPrint(stdout);
1027   }
1028   void SmiPrint(FILE* out);
1029   void SmiPrint(StringStream* accumulator);
1030 #ifdef DEBUG
1031   void SmiVerify();
1032 #endif
1033
1034   static const int kMinValue =
1035       (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1036   static const int kMaxValue = -(kMinValue + 1);
1037
1038  private:
1039   DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1040 };
1041
1042
1043 // Failure is used for reporting out of memory situations and
1044 // propagating exceptions through the runtime system.  Failure objects
1045 // are transient and cannot occur as part of the object graph.
1046 //
1047 // Failures are a single word, encoded as follows:
1048 // +-------------------------+---+--+--+
1049 // |.........unused..........|sss|tt|11|
1050 // +-------------------------+---+--+--+
1051 //                          7 6 4 32 10
1052 //
1053 //
1054 // The low two bits, 0-1, are the failure tag, 11.  The next two bits,
1055 // 2-3, are a failure type tag 'tt' with possible values:
1056 //   00 RETRY_AFTER_GC
1057 //   01 EXCEPTION
1058 //   10 INTERNAL_ERROR
1059 //   11 OUT_OF_MEMORY_EXCEPTION
1060 //
1061 // The next three bits, 4-6, are an allocation space tag 'sss'.  The
1062 // allocation space tag is 000 for all failure types except
1063 // RETRY_AFTER_GC.  For RETRY_AFTER_GC, the possible values are the
1064 // allocation spaces (the encoding is found in globals.h).
1065
1066 // Failure type tag info.
1067 const int kFailureTypeTagSize = 2;
1068 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1069
1070 class Failure: public MaybeObject {
1071  public:
1072   // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1073   enum Type {
1074     RETRY_AFTER_GC = 0,
1075     EXCEPTION = 1,       // Returning this marker tells the real exception
1076                          // is in Isolate::pending_exception.
1077     INTERNAL_ERROR = 2,
1078     OUT_OF_MEMORY_EXCEPTION = 3
1079   };
1080
1081   inline Type type() const;
1082
1083   // Returns the space that needs to be collected for RetryAfterGC failures.
1084   inline AllocationSpace allocation_space() const;
1085
1086   inline bool IsInternalError() const;
1087   inline bool IsOutOfMemoryException() const;
1088
1089   static inline Failure* RetryAfterGC(AllocationSpace space);
1090   static inline Failure* RetryAfterGC();  // NEW_SPACE
1091   static inline Failure* Exception();
1092   static inline Failure* InternalError();
1093   static inline Failure* OutOfMemoryException();
1094   // Casting.
1095   static inline Failure* cast(MaybeObject* object);
1096
1097   // Dispatched behavior.
1098   inline void FailurePrint() {
1099     FailurePrint(stdout);
1100   }
1101   void FailurePrint(FILE* out);
1102   void FailurePrint(StringStream* accumulator);
1103 #ifdef DEBUG
1104   void FailureVerify();
1105 #endif
1106
1107  private:
1108   inline intptr_t value() const;
1109   static inline Failure* Construct(Type type, intptr_t value = 0);
1110
1111   DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1112 };
1113
1114
1115 // Heap objects typically have a map pointer in their first word.  However,
1116 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1117 // encoded in the first word.  The class MapWord is an abstraction of the
1118 // value in a heap object's first word.
1119 class MapWord BASE_EMBEDDED {
1120  public:
1121   // Normal state: the map word contains a map pointer.
1122
1123   // Create a map word from a map pointer.
1124   static inline MapWord FromMap(Map* map);
1125
1126   // View this map word as a map pointer.
1127   inline Map* ToMap();
1128
1129
1130   // Scavenge collection: the map word of live objects in the from space
1131   // contains a forwarding address (a heap object pointer in the to space).
1132
1133   // True if this map word is a forwarding address for a scavenge
1134   // collection.  Only valid during a scavenge collection (specifically,
1135   // when all map words are heap object pointers, i.e. not during a full GC).
1136   inline bool IsForwardingAddress();
1137
1138   // Create a map word from a forwarding address.
1139   static inline MapWord FromForwardingAddress(HeapObject* object);
1140
1141   // View this map word as a forwarding address.
1142   inline HeapObject* ToForwardingAddress();
1143
1144   static inline MapWord FromRawValue(uintptr_t value) {
1145     return MapWord(value);
1146   }
1147
1148   inline uintptr_t ToRawValue() {
1149     return value_;
1150   }
1151
1152  private:
1153   // HeapObject calls the private constructor and directly reads the value.
1154   friend class HeapObject;
1155
1156   explicit MapWord(uintptr_t value) : value_(value) {}
1157
1158   uintptr_t value_;
1159 };
1160
1161
1162 // HeapObject is the superclass for all classes describing heap allocated
1163 // objects.
1164 class HeapObject: public Object {
1165  public:
1166   // [map]: Contains a map which contains the object's reflective
1167   // information.
1168   inline Map* map();
1169   inline void set_map(Map* value);
1170   // The no-write-barrier version.  This is OK if the object is white and in
1171   // new space, or if the value is an immortal immutable object, like the maps
1172   // of primitive (non-JS) objects like strings, heap numbers etc.
1173   inline void set_map_no_write_barrier(Map* value);
1174
1175   // During garbage collection, the map word of a heap object does not
1176   // necessarily contain a map pointer.
1177   inline MapWord map_word();
1178   inline void set_map_word(MapWord map_word);
1179
1180   // The Heap the object was allocated in. Used also to access Isolate.
1181   inline Heap* GetHeap();
1182
1183   // Convenience method to get current isolate. This method can be
1184   // accessed only when its result is the same as
1185   // Isolate::Current(), it ASSERTs this. See also comment for GetHeap.
1186   inline Isolate* GetIsolate();
1187
1188   // Converts an address to a HeapObject pointer.
1189   static inline HeapObject* FromAddress(Address address);
1190
1191   // Returns the address of this HeapObject.
1192   inline Address address();
1193
1194   // Iterates over pointers contained in the object (including the Map)
1195   void Iterate(ObjectVisitor* v);
1196
1197   // Iterates over all pointers contained in the object except the
1198   // first map pointer.  The object type is given in the first
1199   // parameter. This function does not access the map pointer in the
1200   // object, and so is safe to call while the map pointer is modified.
1201   void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1202
1203   // Returns the heap object's size in bytes
1204   inline int Size();
1205
1206   // Given a heap object's map pointer, returns the heap size in bytes
1207   // Useful when the map pointer field is used for other purposes.
1208   // GC internal.
1209   inline int SizeFromMap(Map* map);
1210
1211   // Returns the field at offset in obj, as a read/write Object* reference.
1212   // Does no checking, and is safe to use during GC, while maps are invalid.
1213   // Does not invoke write barrier, so should only be assigned to
1214   // during marking GC.
1215   static inline Object** RawField(HeapObject* obj, int offset);
1216
1217   // Casting.
1218   static inline HeapObject* cast(Object* obj);
1219
1220   // Return the write barrier mode for this. Callers of this function
1221   // must be able to present a reference to an AssertNoAllocation
1222   // object as a sign that they are not going to use this function
1223   // from code that allocates and thus invalidates the returned write
1224   // barrier mode.
1225   inline WriteBarrierMode GetWriteBarrierMode(const AssertNoAllocation&);
1226
1227   // Dispatched behavior.
1228   void HeapObjectShortPrint(StringStream* accumulator);
1229 #ifdef OBJECT_PRINT
1230   inline void HeapObjectPrint() {
1231     HeapObjectPrint(stdout);
1232   }
1233   void HeapObjectPrint(FILE* out);
1234   void PrintHeader(FILE* out, const char* id);
1235 #endif
1236
1237 #ifdef DEBUG
1238   void HeapObjectVerify();
1239   inline void VerifyObjectField(int offset);
1240   inline void VerifySmiField(int offset);
1241
1242   // Verify a pointer is a valid HeapObject pointer that points to object
1243   // areas in the heap.
1244   static void VerifyHeapPointer(Object* p);
1245 #endif
1246
1247   // Layout description.
1248   // First field in a heap object is map.
1249   static const int kMapOffset = Object::kHeaderSize;
1250   static const int kHeaderSize = kMapOffset + kPointerSize;
1251
1252   STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1253
1254  protected:
1255   // helpers for calling an ObjectVisitor to iterate over pointers in the
1256   // half-open range [start, end) specified as integer offsets
1257   inline void IteratePointers(ObjectVisitor* v, int start, int end);
1258   // as above, for the single element at "offset"
1259   inline void IteratePointer(ObjectVisitor* v, int offset);
1260
1261  private:
1262   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1263 };
1264
1265
1266 #define SLOT_ADDR(obj, offset) \
1267   reinterpret_cast<Object**>((obj)->address() + offset)
1268
1269 // This class describes a body of an object of a fixed size
1270 // in which all pointer fields are located in the [start_offset, end_offset)
1271 // interval.
1272 template<int start_offset, int end_offset, int size>
1273 class FixedBodyDescriptor {
1274  public:
1275   static const int kStartOffset = start_offset;
1276   static const int kEndOffset = end_offset;
1277   static const int kSize = size;
1278
1279   static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1280
1281   template<typename StaticVisitor>
1282   static inline void IterateBody(HeapObject* obj) {
1283     StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1284                                  SLOT_ADDR(obj, end_offset));
1285   }
1286 };
1287
1288
1289 // This class describes a body of an object of a variable size
1290 // in which all pointer fields are located in the [start_offset, object_size)
1291 // interval.
1292 template<int start_offset>
1293 class FlexibleBodyDescriptor {
1294  public:
1295   static const int kStartOffset = start_offset;
1296
1297   static inline void IterateBody(HeapObject* obj,
1298                                  int object_size,
1299                                  ObjectVisitor* v);
1300
1301   template<typename StaticVisitor>
1302   static inline void IterateBody(HeapObject* obj, int object_size) {
1303     StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1304                                  SLOT_ADDR(obj, object_size));
1305   }
1306 };
1307
1308 #undef SLOT_ADDR
1309
1310
1311 // The HeapNumber class describes heap allocated numbers that cannot be
1312 // represented in a Smi (small integer)
1313 class HeapNumber: public HeapObject {
1314  public:
1315   // [value]: number value.
1316   inline double value();
1317   inline void set_value(double value);
1318
1319   // Casting.
1320   static inline HeapNumber* cast(Object* obj);
1321
1322   // Dispatched behavior.
1323   Object* HeapNumberToBoolean();
1324   inline void HeapNumberPrint() {
1325     HeapNumberPrint(stdout);
1326   }
1327   void HeapNumberPrint(FILE* out);
1328   void HeapNumberPrint(StringStream* accumulator);
1329 #ifdef DEBUG
1330   void HeapNumberVerify();
1331 #endif
1332
1333   inline int get_exponent();
1334   inline int get_sign();
1335
1336   // Layout description.
1337   static const int kValueOffset = HeapObject::kHeaderSize;
1338   // IEEE doubles are two 32 bit words.  The first is just mantissa, the second
1339   // is a mixture of sign, exponent and mantissa.  Our current platforms are all
1340   // little endian apart from non-EABI arm which is little endian with big
1341   // endian floating point word ordering!
1342   static const int kMantissaOffset = kValueOffset;
1343   static const int kExponentOffset = kValueOffset + 4;
1344
1345   static const int kSize = kValueOffset + kDoubleSize;
1346   static const uint32_t kSignMask = 0x80000000u;
1347   static const uint32_t kExponentMask = 0x7ff00000u;
1348   static const uint32_t kMantissaMask = 0xfffffu;
1349   static const int kMantissaBits = 52;
1350   static const int kExponentBits = 11;
1351   static const int kExponentBias = 1023;
1352   static const int kExponentShift = 20;
1353   static const int kMantissaBitsInTopWord = 20;
1354   static const int kNonMantissaBitsInTopWord = 12;
1355
1356  private:
1357   DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1358 };
1359
1360
1361 enum EnsureElementsMode {
1362   DONT_ALLOW_DOUBLE_ELEMENTS,
1363   ALLOW_COPIED_DOUBLE_ELEMENTS,
1364   ALLOW_CONVERTED_DOUBLE_ELEMENTS
1365 };
1366
1367
1368 // Indicates whether a property should be set or (re)defined.  Setting of a
1369 // property causes attributes to remain unchanged, writability to be checked
1370 // and callbacks to be called.  Defining of a property causes attributes to
1371 // be updated and callbacks to be overridden.
1372 enum SetPropertyMode {
1373   SET_PROPERTY,
1374   DEFINE_PROPERTY
1375 };
1376
1377
1378 // Indicator for one component of an AccessorPair.
1379 enum AccessorComponent {
1380   ACCESSOR_GETTER,
1381   ACCESSOR_SETTER
1382 };
1383
1384
1385 // JSReceiver includes types on which properties can be defined, i.e.,
1386 // JSObject and JSProxy.
1387 class JSReceiver: public HeapObject {
1388  public:
1389   enum DeleteMode {
1390     NORMAL_DELETION,
1391     STRICT_DELETION,
1392     FORCE_DELETION
1393   };
1394
1395   // Casting.
1396   static inline JSReceiver* cast(Object* obj);
1397
1398   static Handle<Object> SetProperty(Handle<JSReceiver> object,
1399                                     Handle<String> key,
1400                                     Handle<Object> value,
1401                                     PropertyAttributes attributes,
1402                                     StrictModeFlag strict_mode,
1403                                     bool skip_fallback_interceptor = false);
1404   // Can cause GC.
1405   MUST_USE_RESULT MaybeObject* SetProperty(String* key,
1406                                            Object* value,
1407                                            PropertyAttributes attributes,
1408                                            StrictModeFlag strict_mode,
1409                                            bool skip_fallback_interceptor = false);
1410   MUST_USE_RESULT MaybeObject* SetProperty(LookupResult* result,
1411                                            String* key,
1412                                            Object* value,
1413                                            PropertyAttributes attributes,
1414                                            StrictModeFlag strict_mode);
1415   MUST_USE_RESULT MaybeObject* SetPropertyWithDefinedSetter(JSReceiver* setter,
1416                                                             Object* value);
1417
1418   MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1419   MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1420
1421   // Set the index'th array element.
1422   // Can cause GC, or return failure if GC is required.
1423   MUST_USE_RESULT MaybeObject* SetElement(uint32_t index,
1424                                           Object* value,
1425                                           PropertyAttributes attributes,
1426                                           StrictModeFlag strict_mode,
1427                                           bool check_prototype);
1428
1429   // Tests for the fast common case for property enumeration.
1430   bool IsSimpleEnum();
1431
1432   // Returns the class name ([[Class]] property in the specification).
1433   String* class_name();
1434
1435   // Returns the constructor name (the name (possibly, inferred name) of the
1436   // function that was used to instantiate the object).
1437   String* constructor_name();
1438
1439   inline PropertyAttributes GetPropertyAttribute(String* name);
1440   PropertyAttributes GetPropertyAttributeWithReceiver(JSReceiver* receiver,
1441                                                       String* name);
1442   PropertyAttributes GetLocalPropertyAttribute(String* name);
1443
1444   // Can cause a GC.
1445   inline bool HasProperty(String* name);
1446   inline bool HasLocalProperty(String* name);
1447   inline bool HasElement(uint32_t index);
1448
1449   // Return the object's prototype (might be Heap::null_value()).
1450   inline Object* GetPrototype();
1451
1452   // Set the object's prototype (only JSReceiver and null are allowed).
1453   MUST_USE_RESULT MaybeObject* SetPrototype(Object* value,
1454                                             bool skip_hidden_prototypes);
1455
1456   // Retrieves a permanent object identity hash code. The undefined value might
1457   // be returned in case no hash was created yet and OMIT_CREATION was used.
1458   inline MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1459
1460   // Lookup a property.  If found, the result is valid and has
1461   // detailed information.
1462   void LocalLookup(String* name,
1463                    LookupResult* result,
1464                    bool skip_fallback_interceptor = false);
1465   void Lookup(String* name,
1466               LookupResult* result,
1467               bool skip_fallback_interceptor = false);
1468
1469  protected:
1470   Smi* GenerateIdentityHash();
1471
1472  private:
1473   PropertyAttributes GetPropertyAttribute(JSReceiver* receiver,
1474                                           LookupResult* result,
1475                                           String* name,
1476                                           bool continue_search);
1477
1478   DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1479 };
1480
1481 // The JSObject describes real heap allocated JavaScript objects with
1482 // properties.
1483 // Note that the map of JSObject changes during execution to enable inline
1484 // caching.
1485 class JSObject: public JSReceiver {
1486  public:
1487   // [properties]: Backing storage for properties.
1488   // properties is a FixedArray in the fast case and a Dictionary in the
1489   // slow case.
1490   DECL_ACCESSORS(properties, FixedArray)  // Get and set fast properties.
1491   inline void initialize_properties();
1492   inline bool HasFastProperties();
1493   inline StringDictionary* property_dictionary();  // Gets slow properties.
1494
1495   // [elements]: The elements (properties with names that are integers).
1496   //
1497   // Elements can be in two general modes: fast and slow. Each mode
1498   // corrensponds to a set of object representations of elements that
1499   // have something in common.
1500   //
1501   // In the fast mode elements is a FixedArray and so each element can
1502   // be quickly accessed. This fact is used in the generated code. The
1503   // elements array can have one of three maps in this mode:
1504   // fixed_array_map, non_strict_arguments_elements_map or
1505   // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1506   // the elements array may be shared by a few objects and so before
1507   // writing to any element the array must be copied. Use
1508   // EnsureWritableFastElements in this case.
1509   //
1510   // In the slow mode the elements is either a NumberDictionary, an
1511   // ExternalArray, or a FixedArray parameter map for a (non-strict)
1512   // arguments object.
1513   DECL_ACCESSORS(elements, FixedArrayBase)
1514   inline void initialize_elements();
1515   MUST_USE_RESULT inline MaybeObject* ResetElements();
1516   inline ElementsKind GetElementsKind();
1517   inline ElementsAccessor* GetElementsAccessor();
1518   inline bool HasFastSmiOnlyElements();
1519   inline bool HasFastElements();
1520   // Returns if an object has either FAST_ELEMENT or FAST_SMI_ONLY_ELEMENT
1521   // elements.  TODO(danno): Rename HasFastTypeElements to HasFastElements() and
1522   // HasFastElements to HasFastObjectElements.
1523   inline bool HasFastTypeElements();
1524   inline bool HasFastDoubleElements();
1525   inline bool HasNonStrictArgumentsElements();
1526   inline bool HasDictionaryElements();
1527   inline bool HasExternalPixelElements();
1528   inline bool HasExternalArrayElements();
1529   inline bool HasExternalByteElements();
1530   inline bool HasExternalUnsignedByteElements();
1531   inline bool HasExternalShortElements();
1532   inline bool HasExternalUnsignedShortElements();
1533   inline bool HasExternalIntElements();
1534   inline bool HasExternalUnsignedIntElements();
1535   inline bool HasExternalFloatElements();
1536   inline bool HasExternalDoubleElements();
1537   bool HasFastArgumentsElements();
1538   bool HasDictionaryArgumentsElements();
1539   inline SeededNumberDictionary* element_dictionary();  // Gets slow elements.
1540
1541   inline void set_map_and_elements(
1542       Map* map,
1543       FixedArrayBase* value,
1544       WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
1545
1546   // Requires: HasFastElements().
1547   MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
1548
1549   // Collects elements starting at index 0.
1550   // Undefined values are placed after non-undefined values.
1551   // Returns the number of non-undefined values.
1552   MUST_USE_RESULT MaybeObject* PrepareElementsForSort(uint32_t limit);
1553   // As PrepareElementsForSort, but only on objects where elements is
1554   // a dictionary, and it will stay a dictionary.
1555   MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
1556
1557   MUST_USE_RESULT MaybeObject* GetPropertyWithCallback(Object* receiver,
1558                                                        Object* structure,
1559                                                        String* name);
1560
1561   // Can cause GC.
1562   MUST_USE_RESULT MaybeObject* SetPropertyForResult(LookupResult* result,
1563                                            String* key,
1564                                            Object* value,
1565                                            PropertyAttributes attributes,
1566                                            StrictModeFlag strict_mode);
1567   MUST_USE_RESULT MaybeObject* SetPropertyWithFailedAccessCheck(
1568       LookupResult* result,
1569       String* name,
1570       Object* value,
1571       bool check_prototype,
1572       StrictModeFlag strict_mode);
1573   MUST_USE_RESULT MaybeObject* SetPropertyWithCallback(
1574       Object* structure,
1575       String* name,
1576       Object* value,
1577       JSObject* holder,
1578       StrictModeFlag strict_mode);
1579   MUST_USE_RESULT MaybeObject* SetPropertyWithInterceptor(
1580       String* name,
1581       Object* value,
1582       PropertyAttributes attributes,
1583       StrictModeFlag strict_mode);
1584   MUST_USE_RESULT MaybeObject* SetPropertyPostInterceptor(
1585       String* name,
1586       Object* value,
1587       PropertyAttributes attributes,
1588       StrictModeFlag strict_mode);
1589
1590   static Handle<Object> SetLocalPropertyIgnoreAttributes(
1591       Handle<JSObject> object,
1592       Handle<String> key,
1593       Handle<Object> value,
1594       PropertyAttributes attributes);
1595
1596   // Can cause GC.
1597   MUST_USE_RESULT MaybeObject* SetLocalPropertyIgnoreAttributes(
1598       String* key,
1599       Object* value,
1600       PropertyAttributes attributes);
1601
1602   // Retrieve a value in a normalized object given a lookup result.
1603   // Handles the special representation of JS global objects.
1604   Object* GetNormalizedProperty(LookupResult* result);
1605
1606   // Sets the property value in a normalized object given a lookup result.
1607   // Handles the special representation of JS global objects.
1608   Object* SetNormalizedProperty(LookupResult* result, Object* value);
1609
1610   // Sets the property value in a normalized object given (key, value, details).
1611   // Handles the special representation of JS global objects.
1612   static Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
1613                                               Handle<String> key,
1614                                               Handle<Object> value,
1615                                               PropertyDetails details);
1616
1617   MUST_USE_RESULT MaybeObject* SetNormalizedProperty(String* name,
1618                                                      Object* value,
1619                                                      PropertyDetails details);
1620
1621   // Deletes the named property in a normalized object.
1622   MUST_USE_RESULT MaybeObject* DeleteNormalizedProperty(String* name,
1623                                                         DeleteMode mode);
1624
1625   // Retrieve interceptors.
1626   InterceptorInfo* GetNamedInterceptor();
1627   InterceptorInfo* GetIndexedInterceptor();
1628
1629   // Used from JSReceiver.
1630   PropertyAttributes GetPropertyAttributePostInterceptor(JSObject* receiver,
1631                                                          String* name,
1632                                                          bool continue_search);
1633   PropertyAttributes GetPropertyAttributeWithInterceptor(JSObject* receiver,
1634                                                          String* name,
1635                                                          bool continue_search);
1636   PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
1637       Object* receiver,
1638       LookupResult* result,
1639       String* name,
1640       bool continue_search);
1641
1642   static void DefineAccessor(Handle<JSObject> object,
1643                              Handle<String> name,
1644                              Handle<Object> getter,
1645                              Handle<Object> setter,
1646                              PropertyAttributes attributes);
1647   MUST_USE_RESULT MaybeObject* DefineAccessor(String* name,
1648                                               Object* getter,
1649                                               Object* setter,
1650                                               PropertyAttributes attributes);
1651   Object* LookupAccessor(String* name, AccessorComponent component);
1652
1653   MUST_USE_RESULT MaybeObject* DefineAccessor(AccessorInfo* info);
1654
1655   // Used from Object::GetProperty().
1656   MUST_USE_RESULT MaybeObject* GetPropertyWithFailedAccessCheck(
1657       Object* receiver,
1658       LookupResult* result,
1659       String* name,
1660       PropertyAttributes* attributes);
1661   MUST_USE_RESULT MaybeObject* GetPropertyWithInterceptor(
1662       JSReceiver* receiver,
1663       String* name,
1664       PropertyAttributes* attributes);
1665   MUST_USE_RESULT MaybeObject* GetPropertyPostInterceptor(
1666       JSReceiver* receiver,
1667       String* name,
1668       PropertyAttributes* attributes);
1669   MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
1670       JSReceiver* receiver,
1671       String* name,
1672       PropertyAttributes* attributes);
1673
1674   // Returns true if this is an instance of an api function and has
1675   // been modified since it was created.  May give false positives.
1676   bool IsDirty();
1677
1678   // If the receiver is a JSGlobalProxy this method will return its prototype,
1679   // otherwise the result is the receiver itself.
1680   inline Object* BypassGlobalProxy();
1681
1682   // Accessors for hidden properties object.
1683   //
1684   // Hidden properties are not local properties of the object itself.
1685   // Instead they are stored in an auxiliary structure kept as a local
1686   // property with a special name Heap::hidden_symbol(). But if the
1687   // receiver is a JSGlobalProxy then the auxiliary object is a property
1688   // of its prototype, and if it's a detached proxy, then you can't have
1689   // hidden properties.
1690
1691   // Sets a hidden property on this object. Returns this object if successful,
1692   // undefined if called on a detached proxy.
1693   static Handle<Object> SetHiddenProperty(Handle<JSObject> obj,
1694                                           Handle<String> key,
1695                                           Handle<Object> value);
1696   // Returns a failure if a GC is required.
1697   MUST_USE_RESULT MaybeObject* SetHiddenProperty(String* key, Object* value);
1698   // Gets the value of a hidden property with the given key. Returns undefined
1699   // if the property doesn't exist (or if called on a detached proxy),
1700   // otherwise returns the value set for the key.
1701   Object* GetHiddenProperty(String* key);
1702   // Deletes a hidden property. Deleting a non-existing property is
1703   // considered successful.
1704   void DeleteHiddenProperty(String* key);
1705   // Returns true if the object has a property with the hidden symbol as name.
1706   bool HasHiddenProperties();
1707
1708   static int GetIdentityHash(Handle<JSObject> obj);
1709   MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1710   MUST_USE_RESULT MaybeObject* SetIdentityHash(Object* hash, CreationFlag flag);
1711
1712   static Handle<Object> DeleteProperty(Handle<JSObject> obj,
1713                                        Handle<String> name);
1714   MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1715
1716   static Handle<Object> DeleteElement(Handle<JSObject> obj, uint32_t index);
1717   MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1718
1719   inline void ValidateSmiOnlyElements();
1720
1721   // Makes sure that this object can contain HeapObject as elements.
1722   MUST_USE_RESULT inline MaybeObject* EnsureCanContainHeapObjectElements();
1723
1724   // Makes sure that this object can contain the specified elements.
1725   MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1726       Object** elements,
1727       uint32_t count,
1728       EnsureElementsMode mode);
1729   MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1730       FixedArrayBase* elements,
1731       EnsureElementsMode mode);
1732   MUST_USE_RESULT MaybeObject* EnsureCanContainElements(
1733       Arguments* arguments,
1734       uint32_t first_arg,
1735       uint32_t arg_count,
1736       EnsureElementsMode mode);
1737
1738   // Do we want to keep the elements in fast case when increasing the
1739   // capacity?
1740   bool ShouldConvertToSlowElements(int new_capacity);
1741   // Returns true if the backing storage for the slow-case elements of
1742   // this object takes up nearly as much space as a fast-case backing
1743   // storage would.  In that case the JSObject should have fast
1744   // elements.
1745   bool ShouldConvertToFastElements();
1746   // Returns true if the elements of JSObject contains only values that can be
1747   // represented in a FixedDoubleArray and has at least one value that can only
1748   // be represented as a double and not a Smi.
1749   bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1750
1751   // Tells whether the index'th element is present.
1752   bool HasElementWithReceiver(JSReceiver* receiver, uint32_t index);
1753
1754   // Computes the new capacity when expanding the elements of a JSObject.
1755   static int NewElementsCapacity(int old_capacity) {
1756     // (old_capacity + 50%) + 16
1757     return old_capacity + (old_capacity >> 1) + 16;
1758   }
1759
1760   // Tells whether the index'th element is present and how it is stored.
1761   enum LocalElementType {
1762     // There is no element with given index.
1763     UNDEFINED_ELEMENT,
1764
1765     // Element with given index is handled by interceptor.
1766     INTERCEPTED_ELEMENT,
1767
1768     // Element with given index is character in string.
1769     STRING_CHARACTER_ELEMENT,
1770
1771     // Element with given index is stored in fast backing store.
1772     FAST_ELEMENT,
1773
1774     // Element with given index is stored in slow backing store.
1775     DICTIONARY_ELEMENT
1776   };
1777
1778   LocalElementType HasLocalElement(uint32_t index);
1779
1780   bool HasElementWithInterceptor(JSReceiver* receiver, uint32_t index);
1781
1782   MUST_USE_RESULT MaybeObject* SetFastElement(uint32_t index,
1783                                               Object* value,
1784                                               StrictModeFlag strict_mode,
1785                                               bool check_prototype);
1786
1787   MUST_USE_RESULT MaybeObject* SetDictionaryElement(
1788       uint32_t index,
1789       Object* value,
1790       PropertyAttributes attributes,
1791       StrictModeFlag strict_mode,
1792       bool check_prototype,
1793       SetPropertyMode set_mode = SET_PROPERTY);
1794
1795   MUST_USE_RESULT MaybeObject* SetFastDoubleElement(
1796       uint32_t index,
1797       Object* value,
1798       StrictModeFlag strict_mode,
1799       bool check_prototype = true);
1800
1801   static Handle<Object> SetOwnElement(Handle<JSObject> object,
1802                                       uint32_t index,
1803                                       Handle<Object> value,
1804                                       StrictModeFlag strict_mode);
1805
1806   // Empty handle is returned if the element cannot be set to the given value.
1807   static MUST_USE_RESULT Handle<Object> SetElement(
1808       Handle<JSObject> object,
1809       uint32_t index,
1810       Handle<Object> value,
1811       PropertyAttributes attr,
1812       StrictModeFlag strict_mode,
1813       SetPropertyMode set_mode = SET_PROPERTY);
1814
1815   // A Failure object is returned if GC is needed.
1816   MUST_USE_RESULT MaybeObject* SetElement(
1817       uint32_t index,
1818       Object* value,
1819       PropertyAttributes attributes,
1820       StrictModeFlag strict_mode,
1821       bool check_prototype = true,
1822       SetPropertyMode set_mode = SET_PROPERTY);
1823
1824   // Returns the index'th element.
1825   // The undefined object if index is out of bounds.
1826   MUST_USE_RESULT MaybeObject* GetElementWithInterceptor(Object* receiver,
1827                                                          uint32_t index);
1828
1829   enum SetFastElementsCapacityMode {
1830     kAllowSmiOnlyElements,
1831     kForceSmiOnlyElements,
1832     kDontAllowSmiOnlyElements
1833   };
1834
1835   // Replace the elements' backing store with fast elements of the given
1836   // capacity.  Update the length for JSArrays.  Returns the new backing
1837   // store.
1838   MUST_USE_RESULT MaybeObject* SetFastElementsCapacityAndLength(
1839       int capacity,
1840       int length,
1841       SetFastElementsCapacityMode set_capacity_mode);
1842   MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
1843       int capacity,
1844       int length);
1845
1846   // Lookup interceptors are used for handling properties controlled by host
1847   // objects.
1848   inline bool HasNamedInterceptor();
1849   inline bool HasIndexedInterceptor();
1850
1851   // Support functions for v8 api (needed for correct interceptor behavior).
1852   bool HasRealNamedProperty(String* key);
1853   bool HasRealElementProperty(uint32_t index);
1854   bool HasRealNamedCallbackProperty(String* key);
1855
1856   // Get the header size for a JSObject.  Used to compute the index of
1857   // internal fields as well as the number of internal fields.
1858   inline int GetHeaderSize();
1859
1860   inline int GetInternalFieldCount();
1861   inline int GetInternalFieldOffset(int index);
1862   inline Object* GetInternalField(int index);
1863   inline void SetInternalField(int index, Object* value);
1864   inline void SetInternalField(int index, Smi* value);
1865
1866   inline void SetExternalResourceObject(Object *);
1867   inline Object *GetExternalResourceObject();
1868
1869   // The following lookup functions skip interceptors.
1870   void LocalLookupRealNamedProperty(String* name, LookupResult* result);
1871   void LookupRealNamedProperty(String* name, LookupResult* result);
1872   void LookupRealNamedPropertyInPrototypes(String* name, LookupResult* result);
1873   void LookupCallbackSetterInPrototypes(String* name, LookupResult* result);
1874   MUST_USE_RESULT MaybeObject* SetElementWithCallbackSetterInPrototypes(
1875       uint32_t index, Object* value, bool* found, StrictModeFlag strict_mode);
1876   void LookupCallback(String* name, LookupResult* result);
1877
1878   // Returns the number of properties on this object filtering out properties
1879   // with the specified attributes (ignoring interceptors).
1880   int NumberOfLocalProperties(PropertyAttributes filter = NONE);
1881   // Fill in details for properties into storage starting at the specified
1882   // index.
1883   void GetLocalPropertyNames(FixedArray* storage, int index);
1884
1885   // Returns the number of properties on this object filtering out properties
1886   // with the specified attributes (ignoring interceptors).
1887   int NumberOfLocalElements(PropertyAttributes filter);
1888   // Returns the number of enumerable elements (ignoring interceptors).
1889   int NumberOfEnumElements();
1890   // Returns the number of elements on this object filtering out elements
1891   // with the specified attributes (ignoring interceptors).
1892   int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
1893   // Count and fill in the enumerable elements into storage.
1894   // (storage->length() == NumberOfEnumElements()).
1895   // If storage is NULL, will count the elements without adding
1896   // them to any storage.
1897   // Returns the number of enumerable elements.
1898   int GetEnumElementKeys(FixedArray* storage);
1899
1900   // Add a property to a fast-case object using a map transition to
1901   // new_map.
1902   MUST_USE_RESULT MaybeObject* AddFastPropertyUsingMap(Map* new_map,
1903                                                        String* name,
1904                                                        Object* value);
1905
1906   // Add a constant function property to a fast-case object.
1907   // This leaves a CONSTANT_TRANSITION in the old map, and
1908   // if it is called on a second object with this map, a
1909   // normal property is added instead, with a map transition.
1910   // This avoids the creation of many maps with the same constant
1911   // function, all orphaned.
1912   MUST_USE_RESULT MaybeObject* AddConstantFunctionProperty(
1913       String* name,
1914       JSFunction* function,
1915       PropertyAttributes attributes);
1916
1917   MUST_USE_RESULT MaybeObject* ReplaceSlowProperty(
1918       String* name,
1919       Object* value,
1920       PropertyAttributes attributes);
1921
1922   // Returns a new map with all transitions dropped from the object's current
1923   // map and the ElementsKind set.
1924   static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
1925                                               ElementsKind to_kind);
1926   inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
1927       Isolate* isolate,
1928       ElementsKind elements_kind);
1929   MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
1930       ElementsKind elements_kind);
1931
1932   static Handle<Object> TransitionElementsKind(Handle<JSObject> object,
1933                                                ElementsKind to_kind);
1934
1935   MUST_USE_RESULT MaybeObject* TransitionElementsKind(ElementsKind to_kind);
1936
1937   // Converts a descriptor of any other type to a real field,
1938   // backed by the properties array.  Descriptors of visible
1939   // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1940   // Converts the descriptor on the original object's map to a
1941   // map transition, and the the new field is on the object's new map.
1942   MUST_USE_RESULT MaybeObject* ConvertDescriptorToFieldAndMapTransition(
1943       String* name,
1944       Object* new_value,
1945       PropertyAttributes attributes);
1946
1947   // Converts a descriptor of any other type to a real field,
1948   // backed by the properties array.  Descriptors of visible
1949   // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1950   MUST_USE_RESULT MaybeObject* ConvertDescriptorToField(
1951       String* name,
1952       Object* new_value,
1953       PropertyAttributes attributes);
1954
1955   // Add a property to a fast-case object.
1956   MUST_USE_RESULT MaybeObject* AddFastProperty(String* name,
1957                                                Object* value,
1958                                                PropertyAttributes attributes);
1959
1960   // Add a property to a slow-case object.
1961   MUST_USE_RESULT MaybeObject* AddSlowProperty(String* name,
1962                                                Object* value,
1963                                                PropertyAttributes attributes);
1964
1965   // Add a property to an object.
1966   MUST_USE_RESULT MaybeObject* AddProperty(String* name,
1967                                            Object* value,
1968                                            PropertyAttributes attributes,
1969                                            StrictModeFlag strict_mode);
1970
1971   // Convert the object to use the canonical dictionary
1972   // representation. If the object is expected to have additional properties
1973   // added this number can be indicated to have the backing store allocated to
1974   // an initial capacity for holding these properties.
1975   static void NormalizeProperties(Handle<JSObject> object,
1976                                   PropertyNormalizationMode mode,
1977                                   int expected_additional_properties);
1978
1979   MUST_USE_RESULT MaybeObject* NormalizeProperties(
1980       PropertyNormalizationMode mode,
1981       int expected_additional_properties);
1982
1983   // Convert and update the elements backing store to be a
1984   // SeededNumberDictionary dictionary.  Returns the backing after conversion.
1985   static Handle<SeededNumberDictionary> NormalizeElements(
1986       Handle<JSObject> object);
1987
1988   MUST_USE_RESULT MaybeObject* NormalizeElements();
1989
1990   static void UpdateMapCodeCache(Handle<JSObject> object,
1991                                  Handle<String> name,
1992                                  Handle<Code> code);
1993
1994   MUST_USE_RESULT MaybeObject* UpdateMapCodeCache(String* name, Code* code);
1995
1996   // Transform slow named properties to fast variants.
1997   // Returns failure if allocation failed.
1998   static void TransformToFastProperties(Handle<JSObject> object,
1999                                         int unused_property_fields);
2000
2001   MUST_USE_RESULT MaybeObject* TransformToFastProperties(
2002       int unused_property_fields);
2003
2004   // Access fast-case object properties at index.
2005   inline Object* FastPropertyAt(int index);
2006   inline Object* FastPropertyAtPut(int index, Object* value);
2007
2008   // Access to in object properties.
2009   inline int GetInObjectPropertyOffset(int index);
2010   inline Object* InObjectPropertyAt(int index);
2011   inline Object* InObjectPropertyAtPut(int index,
2012                                        Object* value,
2013                                        WriteBarrierMode mode
2014                                        = UPDATE_WRITE_BARRIER);
2015
2016   // Initializes the body after properties slot, properties slot is
2017   // initialized by set_properties.  Fill the pre-allocated fields with
2018   // pre_allocated_value and the rest with filler_value.
2019   // Note: this call does not update write barrier, the caller is responsible
2020   // to ensure that |filler_value| can be collected without WB here.
2021   inline void InitializeBody(Map* map,
2022                              Object* pre_allocated_value,
2023                              Object* filler_value);
2024
2025   // Check whether this object references another object
2026   bool ReferencesObject(Object* obj);
2027
2028   // Casting.
2029   static inline JSObject* cast(Object* obj);
2030
2031   // Disalow further properties to be added to the object.
2032   static Handle<Object> PreventExtensions(Handle<JSObject> object);
2033   MUST_USE_RESULT MaybeObject* PreventExtensions();
2034
2035
2036   // Dispatched behavior.
2037   void JSObjectShortPrint(StringStream* accumulator);
2038 #ifdef OBJECT_PRINT
2039   inline void JSObjectPrint() {
2040     JSObjectPrint(stdout);
2041   }
2042   void JSObjectPrint(FILE* out);
2043 #endif
2044 #ifdef DEBUG
2045   void JSObjectVerify();
2046 #endif
2047 #ifdef OBJECT_PRINT
2048   inline void PrintProperties() {
2049     PrintProperties(stdout);
2050   }
2051   void PrintProperties(FILE* out);
2052
2053   inline void PrintElements() {
2054     PrintElements(stdout);
2055   }
2056   void PrintElements(FILE* out);
2057 #endif
2058
2059   void PrintElementsTransition(
2060       FILE* file, ElementsKind from_kind, FixedArrayBase* from_elements,
2061       ElementsKind to_kind, FixedArrayBase* to_elements);
2062
2063 #ifdef DEBUG
2064   // Structure for collecting spill information about JSObjects.
2065   class SpillInformation {
2066    public:
2067     void Clear();
2068     void Print();
2069     int number_of_objects_;
2070     int number_of_objects_with_fast_properties_;
2071     int number_of_objects_with_fast_elements_;
2072     int number_of_fast_used_fields_;
2073     int number_of_fast_unused_fields_;
2074     int number_of_slow_used_properties_;
2075     int number_of_slow_unused_properties_;
2076     int number_of_fast_used_elements_;
2077     int number_of_fast_unused_elements_;
2078     int number_of_slow_used_elements_;
2079     int number_of_slow_unused_elements_;
2080   };
2081
2082   void IncrementSpillStatistics(SpillInformation* info);
2083 #endif
2084   Object* SlowReverseLookup(Object* value);
2085
2086   // Maximal number of fast properties for the JSObject. Used to
2087   // restrict the number of map transitions to avoid an explosion in
2088   // the number of maps for objects used as dictionaries.
2089   inline int MaxFastProperties();
2090
2091   // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2092   // Also maximal value of JSArray's length property.
2093   static const uint32_t kMaxElementCount = 0xffffffffu;
2094
2095   // Constants for heuristics controlling conversion of fast elements
2096   // to slow elements.
2097
2098   // Maximal gap that can be introduced by adding an element beyond
2099   // the current elements length.
2100   static const uint32_t kMaxGap = 1024;
2101
2102   // Maximal length of fast elements array that won't be checked for
2103   // being dense enough on expansion.
2104   static const int kMaxUncheckedFastElementsLength = 5000;
2105
2106   // Same as above but for old arrays. This limit is more strict. We
2107   // don't want to be wasteful with long lived objects.
2108   static const int kMaxUncheckedOldFastElementsLength = 500;
2109
2110   static const int kInitialMaxFastElementArray = 100000;
2111   static const int kMaxFastProperties = 12;
2112   static const int kMaxInstanceSize = 255 * kPointerSize;
2113   // When extending the backing storage for property values, we increase
2114   // its size by more than the 1 entry necessary, so sequentially adding fields
2115   // to the same object requires fewer allocations and copies.
2116   static const int kFieldsAdded = 3;
2117
2118   // Layout description.
2119   static const int kPropertiesOffset = HeapObject::kHeaderSize;
2120   static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2121   static const int kHeaderSize = kElementsOffset + kPointerSize;
2122
2123   STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2124
2125   class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2126    public:
2127     static inline int SizeOf(Map* map, HeapObject* object);
2128   };
2129
2130  private:
2131   friend class DictionaryElementsAccessor;
2132
2133   MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2134                                                       Object* structure,
2135                                                       uint32_t index,
2136                                                       Object* holder);
2137   MUST_USE_RESULT MaybeObject* SetElementWithCallback(
2138       Object* structure,
2139       uint32_t index,
2140       Object* value,
2141       JSObject* holder,
2142       StrictModeFlag strict_mode);
2143   MUST_USE_RESULT MaybeObject* SetElementWithInterceptor(
2144       uint32_t index,
2145       Object* value,
2146       PropertyAttributes attributes,
2147       StrictModeFlag strict_mode,
2148       bool check_prototype,
2149       SetPropertyMode set_mode);
2150   MUST_USE_RESULT MaybeObject* SetElementWithoutInterceptor(
2151       uint32_t index,
2152       Object* value,
2153       PropertyAttributes attributes,
2154       StrictModeFlag strict_mode,
2155       bool check_prototype,
2156       SetPropertyMode set_mode);
2157
2158   // Searches the prototype chain for a callback setter and sets the property
2159   // with the setter if it finds one. The '*found' flag indicates whether
2160   // a setter was found or not.
2161   // This function can cause GC and can return a failure result with
2162   // '*found==true'.
2163   MUST_USE_RESULT MaybeObject* SetPropertyWithCallbackSetterInPrototypes(
2164       String* name,
2165       Object* value,
2166       PropertyAttributes attributes,
2167       bool* found,
2168       StrictModeFlag strict_mode);
2169
2170   MUST_USE_RESULT MaybeObject* DeletePropertyPostInterceptor(String* name,
2171                                                              DeleteMode mode);
2172   MUST_USE_RESULT MaybeObject* DeletePropertyWithInterceptor(String* name);
2173
2174   MUST_USE_RESULT MaybeObject* DeleteElementWithInterceptor(uint32_t index);
2175
2176   MUST_USE_RESULT MaybeObject* DeleteFastElement(uint32_t index);
2177   MUST_USE_RESULT MaybeObject* DeleteDictionaryElement(uint32_t index,
2178                                                        DeleteMode mode);
2179
2180   bool ReferencesObjectFromElements(FixedArray* elements,
2181                                     ElementsKind kind,
2182                                     Object* object);
2183
2184   // Returns true if most of the elements backing storage is used.
2185   bool HasDenseElements();
2186
2187   // Gets the current elements capacity and the number of used elements.
2188   void GetElementsCapacityAndUsage(int* capacity, int* used);
2189
2190   bool CanSetCallback(String* name);
2191   MUST_USE_RESULT MaybeObject* SetElementCallback(
2192       uint32_t index,
2193       Object* structure,
2194       PropertyAttributes attributes);
2195   MUST_USE_RESULT MaybeObject* SetPropertyCallback(
2196       String* name,
2197       Object* structure,
2198       PropertyAttributes attributes);
2199   MUST_USE_RESULT MaybeObject* DefineElementAccessor(
2200       uint32_t index,
2201       Object* getter,
2202       Object* setter,
2203       PropertyAttributes attributes);
2204   MUST_USE_RESULT MaybeObject* CreateAccessorPairFor(String* name);
2205   MUST_USE_RESULT MaybeObject* DefinePropertyAccessor(
2206       String* name,
2207       Object* getter,
2208       Object* setter,
2209       PropertyAttributes attributes);
2210   void LookupInDescriptor(String* name, LookupResult* result);
2211
2212   // Returns the hidden properties backing store object, currently
2213   // a StringDictionary, stored on this object.
2214   // If no hidden properties object has been put on this object,
2215   // return undefined, unless create_if_absent is true, in which case
2216   // a new dictionary is created, added to this object, and returned.
2217   MUST_USE_RESULT MaybeObject* GetHiddenPropertiesDictionary(
2218       bool create_if_absent);
2219   // Updates the existing hidden properties dictionary.
2220   MUST_USE_RESULT MaybeObject* SetHiddenPropertiesDictionary(
2221       StringDictionary* dictionary);
2222
2223   DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2224 };
2225
2226
2227 // Common superclass for FixedArrays that allow implementations to share
2228 // common accessors and some code paths.
2229 class FixedArrayBase: public HeapObject {
2230  public:
2231   // [length]: length of the array.
2232   inline int length();
2233   inline void set_length(int value);
2234
2235   inline static FixedArrayBase* cast(Object* object);
2236
2237   // Layout description.
2238   // Length is smi tagged when it is stored.
2239   static const int kLengthOffset = HeapObject::kHeaderSize;
2240   static const int kHeaderSize = kLengthOffset + kPointerSize;
2241 };
2242
2243
2244 class FixedDoubleArray;
2245
2246 // FixedArray describes fixed-sized arrays with element type Object*.
2247 class FixedArray: public FixedArrayBase {
2248  public:
2249   // Setter and getter for elements.
2250   inline Object* get(int index);
2251   // Setter that uses write barrier.
2252   inline void set(int index, Object* value);
2253   inline bool is_the_hole(int index);
2254
2255   // Setter that doesn't need write barrier).
2256   inline void set(int index, Smi* value);
2257   // Setter with explicit barrier mode.
2258   inline void set(int index, Object* value, WriteBarrierMode mode);
2259
2260   // Setters for frequently used oddballs located in old space.
2261   inline void set_undefined(int index);
2262   // TODO(isolates): duplicate.
2263   inline void set_undefined(Heap* heap, int index);
2264   inline void set_null(int index);
2265   // TODO(isolates): duplicate.
2266   inline void set_null(Heap* heap, int index);
2267   inline void set_the_hole(int index);
2268
2269   // Setters with less debug checks for the GC to use.
2270   inline void set_unchecked(int index, Smi* value);
2271   inline void set_null_unchecked(Heap* heap, int index);
2272   inline void set_unchecked(Heap* heap, int index, Object* value,
2273                             WriteBarrierMode mode);
2274
2275   // Gives access to raw memory which stores the array's data.
2276   inline Object** data_start();
2277
2278   inline Object** GetFirstElementAddress();
2279   inline bool ContainsOnlySmisOrHoles();
2280
2281   // Copy operations.
2282   MUST_USE_RESULT inline MaybeObject* Copy();
2283   MUST_USE_RESULT MaybeObject* CopySize(int new_length);
2284
2285   // Add the elements of a JSArray to this FixedArray.
2286   MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
2287
2288   // Compute the union of this and other.
2289   MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
2290
2291   // Copy a sub array from the receiver to dest.
2292   void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2293
2294   // Garbage collection support.
2295   static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2296
2297   // Code Generation support.
2298   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2299
2300   // Casting.
2301   static inline FixedArray* cast(Object* obj);
2302
2303   // Maximal allowed size, in bytes, of a single FixedArray.
2304   // Prevents overflowing size computations, as well as extreme memory
2305   // consumption.
2306   static const int kMaxSize = 128 * MB * kPointerSize;
2307   // Maximally allowed length of a FixedArray.
2308   static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2309
2310   // Dispatched behavior.
2311 #ifdef OBJECT_PRINT
2312   inline void FixedArrayPrint() {
2313     FixedArrayPrint(stdout);
2314   }
2315   void FixedArrayPrint(FILE* out);
2316 #endif
2317 #ifdef DEBUG
2318   void FixedArrayVerify();
2319   // Checks if two FixedArrays have identical contents.
2320   bool IsEqualTo(FixedArray* other);
2321 #endif
2322
2323   // Swap two elements in a pair of arrays.  If this array and the
2324   // numbers array are the same object, the elements are only swapped
2325   // once.
2326   void SwapPairs(FixedArray* numbers, int i, int j);
2327
2328   // Sort prefix of this array and the numbers array as pairs wrt. the
2329   // numbers.  If the numbers array and the this array are the same
2330   // object, the prefix of this array is sorted.
2331   void SortPairs(FixedArray* numbers, uint32_t len);
2332
2333   class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2334    public:
2335     static inline int SizeOf(Map* map, HeapObject* object) {
2336       return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2337     }
2338   };
2339
2340  protected:
2341   // Set operation on FixedArray without using write barriers. Can
2342   // only be used for storing old space objects or smis.
2343   static inline void NoWriteBarrierSet(FixedArray* array,
2344                                        int index,
2345                                        Object* value);
2346
2347   // Set operation on FixedArray without incremental write barrier. Can
2348   // only be used if the object is guaranteed to be white (whiteness witness
2349   // is present).
2350   static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2351                                                   int index,
2352                                                   Object* value);
2353
2354  private:
2355   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2356 };
2357
2358
2359 // FixedDoubleArray describes fixed-sized arrays with element type double.
2360 class FixedDoubleArray: public FixedArrayBase {
2361  public:
2362   // Setter and getter for elements.
2363   inline double get_scalar(int index);
2364   inline int64_t get_representation(int index);
2365   MUST_USE_RESULT inline MaybeObject* get(int index);
2366   inline void set(int index, double value);
2367   inline void set_the_hole(int index);
2368
2369   // Checking for the hole.
2370   inline bool is_the_hole(int index);
2371
2372   // Copy operations
2373   MUST_USE_RESULT inline MaybeObject* Copy();
2374
2375   // Garbage collection support.
2376   inline static int SizeFor(int length) {
2377     return kHeaderSize + length * kDoubleSize;
2378   }
2379
2380   // Code Generation support.
2381   static int OffsetOfElementAt(int index) { return SizeFor(index); }
2382
2383   inline static bool is_the_hole_nan(double value);
2384   inline static double hole_nan_as_double();
2385   inline static double canonical_not_the_hole_nan_as_double();
2386
2387   // Casting.
2388   static inline FixedDoubleArray* cast(Object* obj);
2389
2390   // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2391   // Prevents overflowing size computations, as well as extreme memory
2392   // consumption.
2393   static const int kMaxSize = 512 * MB;
2394   // Maximally allowed length of a FixedArray.
2395   static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2396
2397   // Dispatched behavior.
2398 #ifdef OBJECT_PRINT
2399   inline void FixedDoubleArrayPrint() {
2400     FixedDoubleArrayPrint(stdout);
2401   }
2402   void FixedDoubleArrayPrint(FILE* out);
2403 #endif
2404
2405 #ifdef DEBUG
2406   void FixedDoubleArrayVerify();
2407 #endif
2408
2409  private:
2410   DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2411 };
2412
2413
2414 class IncrementalMarking;
2415
2416
2417 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2418 // The format of the these objects is:
2419 // TODO(1399): It should be possible to make room for bit_field3 in the map
2420 //             without overloading the instance descriptors field in the map
2421 //             (and storing it in the DescriptorArray when the map has one).
2422 //   [0]: storage for bit_field3 for Map owning this object (Smi)
2423 //   [1]: point to a fixed array with (value, detail) pairs.
2424 //   [2]: next enumeration index (Smi), or pointer to small fixed array:
2425 //          [0]: next enumeration index (Smi)
2426 //          [1]: pointer to fixed array with enum cache
2427 //   [3]: first key
2428 //   [length() - 1]: last key
2429 //
2430 class DescriptorArray: public FixedArray {
2431  public:
2432   // Returns true for both shared empty_descriptor_array and for smis, which the
2433   // map uses to encode additional bit fields when the descriptor array is not
2434   // yet used.
2435   inline bool IsEmpty();
2436
2437   // Returns the number of descriptors in the array.
2438   int number_of_descriptors() {
2439     ASSERT(length() > kFirstIndex || IsEmpty());
2440     int len = length();
2441     return len <= kFirstIndex ? 0 : len - kFirstIndex;
2442   }
2443
2444   int NextEnumerationIndex() {
2445     if (IsEmpty()) return PropertyDetails::kInitialIndex;
2446     Object* obj = get(kEnumerationIndexIndex);
2447     if (obj->IsSmi()) {
2448       return Smi::cast(obj)->value();
2449     } else {
2450       Object* index = FixedArray::cast(obj)->get(kEnumCacheBridgeEnumIndex);
2451       return Smi::cast(index)->value();
2452     }
2453   }
2454
2455   // Set next enumeration index and flush any enum cache.
2456   void SetNextEnumerationIndex(int value) {
2457     if (!IsEmpty()) {
2458       set(kEnumerationIndexIndex, Smi::FromInt(value));
2459     }
2460   }
2461   bool HasEnumCache() {
2462     return !IsEmpty() && !get(kEnumerationIndexIndex)->IsSmi();
2463   }
2464
2465   Object* GetEnumCache() {
2466     ASSERT(HasEnumCache());
2467     FixedArray* bridge = FixedArray::cast(get(kEnumerationIndexIndex));
2468     return bridge->get(kEnumCacheBridgeCacheIndex);
2469   }
2470
2471   // TODO(1399): It should be possible to make room for bit_field3 in the map
2472   //             without overloading the instance descriptors field in the map
2473   //             (and storing it in the DescriptorArray when the map has one).
2474   inline int bit_field3_storage();
2475   inline void set_bit_field3_storage(int value);
2476
2477   // Initialize or change the enum cache,
2478   // using the supplied storage for the small "bridge".
2479   void SetEnumCache(FixedArray* bridge_storage,
2480                     FixedArray* new_cache,
2481                     Object* new_index_cache);
2482
2483   // Accessors for fetching instance descriptor at descriptor number.
2484   inline String* GetKey(int descriptor_number);
2485   inline Object* GetValue(int descriptor_number);
2486   inline PropertyDetails GetDetails(int descriptor_number);
2487   inline PropertyType GetType(int descriptor_number);
2488   inline int GetFieldIndex(int descriptor_number);
2489   inline JSFunction* GetConstantFunction(int descriptor_number);
2490   inline Object* GetCallbacksObject(int descriptor_number);
2491   inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2492   inline bool IsProperty(int descriptor_number);
2493   inline bool IsTransitionOnly(int descriptor_number);
2494   inline bool IsNullDescriptor(int descriptor_number);
2495
2496   class WhitenessWitness {
2497    public:
2498     inline explicit WhitenessWitness(DescriptorArray* array);
2499     inline ~WhitenessWitness();
2500
2501    private:
2502     IncrementalMarking* marking_;
2503   };
2504
2505   // Accessor for complete descriptor.
2506   inline void Get(int descriptor_number, Descriptor* desc);
2507   inline void Set(int descriptor_number,
2508                   Descriptor* desc,
2509                   const WhitenessWitness&);
2510
2511   // Transfer a complete descriptor from the src descriptor array to the dst
2512   // one, dropping map transitions in CALLBACKS.
2513   static void CopyFrom(Handle<DescriptorArray> dst,
2514                        int dst_index,
2515                        Handle<DescriptorArray> src,
2516                        int src_index,
2517                        const WhitenessWitness& witness);
2518
2519   // Transfer a complete descriptor from the src descriptor array to this
2520   // descriptor array, dropping map transitions in CALLBACKS.
2521   MUST_USE_RESULT MaybeObject* CopyFrom(int dst_index,
2522                                         DescriptorArray* src,
2523                                         int src_index,
2524                                         const WhitenessWitness&);
2525
2526   // Copy the descriptor array, insert a new descriptor and optionally
2527   // remove map transitions.  If the descriptor is already present, it is
2528   // replaced.  If a replaced descriptor is a real property (not a transition
2529   // or null), its enumeration index is kept as is.
2530   // If adding a real property, map transitions must be removed.  If adding
2531   // a transition, they must not be removed.  All null descriptors are removed.
2532   MUST_USE_RESULT MaybeObject* CopyInsert(Descriptor* descriptor,
2533                                           TransitionFlag transition_flag);
2534
2535   // Return a copy of the array with all transitions and null descriptors
2536   // removed. Return a Failure object in case of an allocation failure.
2537   MUST_USE_RESULT MaybeObject* RemoveTransitions();
2538
2539   // Sort the instance descriptors by the hash codes of their keys.
2540   // Does not check for duplicates.
2541   void SortUnchecked(const WhitenessWitness&);
2542
2543   // Sort the instance descriptors by the hash codes of their keys.
2544   // Checks the result for duplicates.
2545   void Sort(const WhitenessWitness&);
2546
2547   // Search the instance descriptors for given name.
2548   inline int Search(String* name);
2549
2550   // As the above, but uses DescriptorLookupCache and updates it when
2551   // necessary.
2552   inline int SearchWithCache(String* name);
2553
2554   // Tells whether the name is present int the array.
2555   bool Contains(String* name) { return kNotFound != Search(name); }
2556
2557   // Perform a binary search in the instance descriptors represented
2558   // by this fixed array.  low and high are descriptor indices.  If there
2559   // are three instance descriptors in this array it should be called
2560   // with low=0 and high=2.
2561   int BinarySearch(String* name, int low, int high);
2562
2563   // Perform a linear search in the instance descriptors represented
2564   // by this fixed array.  len is the number of descriptor indices that are
2565   // valid.  Does not require the descriptors to be sorted.
2566   int LinearSearch(String* name, int len);
2567
2568   // Allocates a DescriptorArray, but returns the singleton
2569   // empty descriptor array object if number_of_descriptors is 0.
2570   MUST_USE_RESULT static MaybeObject* Allocate(int number_of_descriptors);
2571
2572   // Casting.
2573   static inline DescriptorArray* cast(Object* obj);
2574
2575   // Constant for denoting key was not found.
2576   static const int kNotFound = -1;
2577
2578   static const int kBitField3StorageIndex = 0;
2579   static const int kContentArrayIndex = 1;
2580   static const int kEnumerationIndexIndex = 2;
2581   static const int kFirstIndex = 3;
2582
2583   // The length of the "bridge" to the enum cache.
2584   static const int kEnumCacheBridgeLength = 3;
2585   static const int kEnumCacheBridgeEnumIndex = 0;
2586   static const int kEnumCacheBridgeCacheIndex = 1;
2587   static const int kEnumCacheBridgeIndicesCacheIndex = 2;
2588
2589   // Layout description.
2590   static const int kBitField3StorageOffset = FixedArray::kHeaderSize;
2591   static const int kContentArrayOffset = kBitField3StorageOffset + kPointerSize;
2592   static const int kEnumerationIndexOffset = kContentArrayOffset + kPointerSize;
2593   static const int kFirstOffset = kEnumerationIndexOffset + kPointerSize;
2594
2595   // Layout description for the bridge array.
2596   static const int kEnumCacheBridgeEnumOffset = FixedArray::kHeaderSize;
2597   static const int kEnumCacheBridgeCacheOffset =
2598     kEnumCacheBridgeEnumOffset + kPointerSize;
2599
2600 #ifdef OBJECT_PRINT
2601   // Print all the descriptors.
2602   inline void PrintDescriptors() {
2603     PrintDescriptors(stdout);
2604   }
2605   void PrintDescriptors(FILE* out);
2606 #endif
2607
2608 #ifdef DEBUG
2609   // Is the descriptor array sorted and without duplicates?
2610   bool IsSortedNoDuplicates();
2611
2612   // Is the descriptor array consistent with the back pointers in targets?
2613   bool IsConsistentWithBackPointers(Map* current_map);
2614
2615   // Are two DescriptorArrays equal?
2616   bool IsEqualTo(DescriptorArray* other);
2617 #endif
2618
2619   // The maximum number of descriptors we want in a descriptor array (should
2620   // fit in a page).
2621   static const int kMaxNumberOfDescriptors = 1024 + 512;
2622
2623  private:
2624   // An entry in a DescriptorArray, represented as an (array, index) pair.
2625   class Entry {
2626    public:
2627     inline explicit Entry(DescriptorArray* descs, int index) :
2628         descs_(descs), index_(index) { }
2629
2630     inline PropertyType type() { return descs_->GetType(index_); }
2631     inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2632
2633    private:
2634     DescriptorArray* descs_;
2635     int index_;
2636   };
2637
2638   // Conversion from descriptor number to array indices.
2639   static int ToKeyIndex(int descriptor_number) {
2640     return descriptor_number+kFirstIndex;
2641   }
2642
2643   static int ToDetailsIndex(int descriptor_number) {
2644     return (descriptor_number << 1) + 1;
2645   }
2646
2647   static int ToValueIndex(int descriptor_number) {
2648     return descriptor_number << 1;
2649   }
2650
2651   // Swap operation on FixedArray without using write barriers.
2652   static inline void NoIncrementalWriteBarrierSwap(
2653       FixedArray* array, int first, int second);
2654
2655   // Swap descriptor first and second.
2656   inline void NoIncrementalWriteBarrierSwapDescriptors(
2657       int first, int second);
2658
2659   FixedArray* GetContentArray() {
2660     return FixedArray::cast(get(kContentArrayIndex));
2661   }
2662   DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2663 };
2664
2665
2666 // HashTable is a subclass of FixedArray that implements a hash table
2667 // that uses open addressing and quadratic probing.
2668 //
2669 // In order for the quadratic probing to work, elements that have not
2670 // yet been used and elements that have been deleted are
2671 // distinguished.  Probing continues when deleted elements are
2672 // encountered and stops when unused elements are encountered.
2673 //
2674 // - Elements with key == undefined have not been used yet.
2675 // - Elements with key == the_hole have been deleted.
2676 //
2677 // The hash table class is parameterized with a Shape and a Key.
2678 // Shape must be a class with the following interface:
2679 //   class ExampleShape {
2680 //    public:
2681 //      // Tells whether key matches other.
2682 //     static bool IsMatch(Key key, Object* other);
2683 //     // Returns the hash value for key.
2684 //     static uint32_t Hash(Key key);
2685 //     // Returns the hash value for object.
2686 //     static uint32_t HashForObject(Key key, Object* object);
2687 //     // Convert key to an object.
2688 //     static inline Object* AsObject(Key key);
2689 //     // The prefix size indicates number of elements in the beginning
2690 //     // of the backing storage.
2691 //     static const int kPrefixSize = ..;
2692 //     // The Element size indicates number of elements per entry.
2693 //     static const int kEntrySize = ..;
2694 //   };
2695 // The prefix size indicates an amount of memory in the
2696 // beginning of the backing storage that can be used for non-element
2697 // information by subclasses.
2698
2699 template<typename Key>
2700 class BaseShape {
2701  public:
2702   static const bool UsesSeed = false;
2703   static uint32_t Hash(Key key) { return 0; }
2704   static uint32_t SeededHash(Key key, uint32_t seed) {
2705     ASSERT(UsesSeed);
2706     return Hash(key);
2707   }
2708   static uint32_t HashForObject(Key key, Object* object) { return 0; }
2709   static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2710     ASSERT(UsesSeed);
2711     return HashForObject(key, object);
2712   }
2713 };
2714
2715 template<typename Shape, typename Key>
2716 class HashTable: public FixedArray {
2717  public:
2718   // Wrapper methods
2719   inline uint32_t Hash(Key key) {
2720     if (Shape::UsesSeed) {
2721       return Shape::SeededHash(key,
2722           GetHeap()->HashSeed());
2723     } else {
2724       return Shape::Hash(key);
2725     }
2726   }
2727
2728   inline uint32_t HashForObject(Key key, Object* object) {
2729     if (Shape::UsesSeed) {
2730       return Shape::SeededHashForObject(key,
2731           GetHeap()->HashSeed(), object);
2732     } else {
2733       return Shape::HashForObject(key, object);
2734     }
2735   }
2736
2737   // Returns the number of elements in the hash table.
2738   int NumberOfElements() {
2739     return Smi::cast(get(kNumberOfElementsIndex))->value();
2740   }
2741
2742   // Returns the number of deleted elements in the hash table.
2743   int NumberOfDeletedElements() {
2744     return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2745   }
2746
2747   // Returns the capacity of the hash table.
2748   int Capacity() {
2749     return Smi::cast(get(kCapacityIndex))->value();
2750   }
2751
2752   // ElementAdded should be called whenever an element is added to a
2753   // hash table.
2754   void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2755
2756   // ElementRemoved should be called whenever an element is removed from
2757   // a hash table.
2758   void ElementRemoved() {
2759     SetNumberOfElements(NumberOfElements() - 1);
2760     SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2761   }
2762   void ElementsRemoved(int n) {
2763     SetNumberOfElements(NumberOfElements() - n);
2764     SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2765   }
2766
2767   // Returns a new HashTable object. Might return Failure.
2768   MUST_USE_RESULT static MaybeObject* Allocate(
2769       int at_least_space_for,
2770       PretenureFlag pretenure = NOT_TENURED);
2771
2772   // Computes the required capacity for a table holding the given
2773   // number of elements. May be more than HashTable::kMaxCapacity.
2774   static int ComputeCapacity(int at_least_space_for);
2775
2776   // Returns the key at entry.
2777   Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2778
2779   // Tells whether k is a real key.  The hole and undefined are not allowed
2780   // as keys and can be used to indicate missing or deleted elements.
2781   bool IsKey(Object* k) {
2782     return !k->IsTheHole() && !k->IsUndefined();
2783   }
2784
2785   // Garbage collection support.
2786   void IteratePrefix(ObjectVisitor* visitor);
2787   void IterateElements(ObjectVisitor* visitor);
2788
2789   // Casting.
2790   static inline HashTable* cast(Object* obj);
2791
2792   // Compute the probe offset (quadratic probing).
2793   INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2794     return (n + n * n) >> 1;
2795   }
2796
2797   static const int kNumberOfElementsIndex = 0;
2798   static const int kNumberOfDeletedElementsIndex = 1;
2799   static const int kCapacityIndex = 2;
2800   static const int kPrefixStartIndex = 3;
2801   static const int kElementsStartIndex =
2802       kPrefixStartIndex + Shape::kPrefixSize;
2803   static const int kEntrySize = Shape::kEntrySize;
2804   static const int kElementsStartOffset =
2805       kHeaderSize + kElementsStartIndex * kPointerSize;
2806   static const int kCapacityOffset =
2807       kHeaderSize + kCapacityIndex * kPointerSize;
2808
2809   // Constant used for denoting a absent entry.
2810   static const int kNotFound = -1;
2811
2812   // Maximal capacity of HashTable. Based on maximal length of underlying
2813   // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
2814   // cannot overflow.
2815   static const int kMaxCapacity =
2816       (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
2817
2818   // Find entry for key otherwise return kNotFound.
2819   inline int FindEntry(Key key);
2820   int FindEntry(Isolate* isolate, Key key);
2821
2822  protected:
2823   // Find the entry at which to insert element with the given key that
2824   // has the given hash value.
2825   uint32_t FindInsertionEntry(uint32_t hash);
2826
2827   // Returns the index for an entry (of the key)
2828   static inline int EntryToIndex(int entry) {
2829     return (entry * kEntrySize) + kElementsStartIndex;
2830   }
2831
2832   // Update the number of elements in the hash table.
2833   void SetNumberOfElements(int nof) {
2834     set(kNumberOfElementsIndex, Smi::FromInt(nof));
2835   }
2836
2837   // Update the number of deleted elements in the hash table.
2838   void SetNumberOfDeletedElements(int nod) {
2839     set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2840   }
2841
2842   // Sets the capacity of the hash table.
2843   void SetCapacity(int capacity) {
2844     // To scale a computed hash code to fit within the hash table, we
2845     // use bit-wise AND with a mask, so the capacity must be positive
2846     // and non-zero.
2847     ASSERT(capacity > 0);
2848     ASSERT(capacity <= kMaxCapacity);
2849     set(kCapacityIndex, Smi::FromInt(capacity));
2850   }
2851
2852
2853   // Returns probe entry.
2854   static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2855     ASSERT(IsPowerOf2(size));
2856     return (hash + GetProbeOffset(number)) & (size - 1);
2857   }
2858
2859   static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2860     return hash & (size - 1);
2861   }
2862
2863   static uint32_t NextProbe(uint32_t last, uint32_t number, uint32_t size) {
2864     return (last + number) & (size - 1);
2865   }
2866
2867   // Rehashes this hash-table into the new table.
2868   MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
2869
2870   // Attempt to shrink hash table after removal of key.
2871   MUST_USE_RESULT MaybeObject* Shrink(Key key);
2872
2873   // Ensure enough space for n additional elements.
2874   MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
2875 };
2876
2877
2878 // HashTableKey is an abstract superclass for virtual key behavior.
2879 class HashTableKey {
2880  public:
2881   // Returns whether the other object matches this key.
2882   virtual bool IsMatch(Object* other) = 0;
2883   // Returns the hash value for this key.
2884   virtual uint32_t Hash() = 0;
2885   // Returns the hash value for object.
2886   virtual uint32_t HashForObject(Object* key) = 0;
2887   // Returns the key object for storing into the hash table.
2888   // If allocations fails a failure object is returned.
2889   MUST_USE_RESULT virtual MaybeObject* AsObject() = 0;
2890   // Required.
2891   virtual ~HashTableKey() {}
2892 };
2893
2894
2895 class SymbolTableShape : public BaseShape<HashTableKey*> {
2896  public:
2897   static inline bool IsMatch(HashTableKey* key, Object* value) {
2898     return key->IsMatch(value);
2899   }
2900   static inline uint32_t Hash(HashTableKey* key) {
2901     return key->Hash();
2902   }
2903   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2904     return key->HashForObject(object);
2905   }
2906   MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2907     return key->AsObject();
2908   }
2909
2910   static const int kPrefixSize = 0;
2911   static const int kEntrySize = 1;
2912 };
2913
2914 class SeqAsciiString;
2915
2916 // SymbolTable.
2917 //
2918 // No special elements in the prefix and the element size is 1
2919 // because only the symbol itself (the key) needs to be stored.
2920 class SymbolTable: public HashTable<SymbolTableShape, HashTableKey*> {
2921  public:
2922   // Find symbol in the symbol table.  If it is not there yet, it is
2923   // added.  The return value is the symbol table which might have
2924   // been enlarged.  If the return value is not a failure, the symbol
2925   // pointer *s is set to the symbol found.
2926   MUST_USE_RESULT MaybeObject* LookupSymbol(Vector<const char> str, Object** s);
2927   MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Vector<const char> str,
2928                                                  Object** s);
2929   MUST_USE_RESULT MaybeObject* LookupSubStringAsciiSymbol(
2930       Handle<SeqAsciiString> str,
2931       int from,
2932       int length,
2933       Object** s);
2934   MUST_USE_RESULT MaybeObject* LookupTwoByteSymbol(Vector<const uc16> str,
2935                                                    Object** s);
2936   MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
2937
2938   // Looks up a symbol that is equal to the given string and returns
2939   // true if it is found, assigning the symbol to the given output
2940   // parameter.
2941   bool LookupSymbolIfExists(String* str, String** symbol);
2942   bool LookupTwoCharsSymbolIfExists(uint32_t c1, uint32_t c2, String** symbol);
2943
2944   // Casting.
2945   static inline SymbolTable* cast(Object* obj);
2946
2947  private:
2948   MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
2949
2950   DISALLOW_IMPLICIT_CONSTRUCTORS(SymbolTable);
2951 };
2952
2953
2954 class MapCacheShape : public BaseShape<HashTableKey*> {
2955  public:
2956   static inline bool IsMatch(HashTableKey* key, Object* value) {
2957     return key->IsMatch(value);
2958   }
2959   static inline uint32_t Hash(HashTableKey* key) {
2960     return key->Hash();
2961   }
2962
2963   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2964     return key->HashForObject(object);
2965   }
2966
2967   MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2968     return key->AsObject();
2969   }
2970
2971   static const int kPrefixSize = 0;
2972   static const int kEntrySize = 2;
2973 };
2974
2975
2976 // MapCache.
2977 //
2978 // Maps keys that are a fixed array of symbols to a map.
2979 // Used for canonicalize maps for object literals.
2980 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
2981  public:
2982   // Find cached value for a string key, otherwise return null.
2983   Object* Lookup(FixedArray* key);
2984   MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
2985   static inline MapCache* cast(Object* obj);
2986
2987  private:
2988   DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
2989 };
2990
2991
2992 template <typename Shape, typename Key>
2993 class Dictionary: public HashTable<Shape, Key> {
2994  public:
2995   static inline Dictionary<Shape, Key>* cast(Object* obj) {
2996     return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
2997   }
2998
2999   // Returns the value at entry.
3000   Object* ValueAt(int entry) {
3001     return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
3002   }
3003
3004   // Set the value for entry.
3005   void ValueAtPut(int entry, Object* value) {
3006     this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
3007   }
3008
3009   // Returns the property details for the property at entry.
3010   PropertyDetails DetailsAt(int entry) {
3011     ASSERT(entry >= 0);  // Not found is -1, which is not caught by get().
3012     return PropertyDetails(
3013         Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
3014   }
3015
3016   // Set the details for entry.
3017   void DetailsAtPut(int entry, PropertyDetails value) {
3018     this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
3019   }
3020
3021   // Sorting support
3022   void CopyValuesTo(FixedArray* elements);
3023
3024   // Delete a property from the dictionary.
3025   Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
3026
3027   // Attempt to shrink the dictionary after deletion of key.
3028   MUST_USE_RESULT MaybeObject* Shrink(Key key);
3029
3030   // Returns the number of elements in the dictionary filtering out properties
3031   // with the specified attributes.
3032   int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3033
3034   // Returns the number of enumerable elements in the dictionary.
3035   int NumberOfEnumElements();
3036
3037   enum SortMode { UNSORTED, SORTED };
3038   // Copies keys to preallocated fixed array.
3039   void CopyKeysTo(FixedArray* storage,
3040                   PropertyAttributes filter,
3041                   SortMode sort_mode);
3042   // Fill in details for properties into storage.
3043   void CopyKeysTo(FixedArray* storage, int index, SortMode sort_mode);
3044
3045   // Accessors for next enumeration index.
3046   void SetNextEnumerationIndex(int index) {
3047     this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3048   }
3049
3050   int NextEnumerationIndex() {
3051     return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
3052   }
3053
3054   // Returns a new array for dictionary usage. Might return Failure.
3055   MUST_USE_RESULT static MaybeObject* Allocate(int at_least_space_for);
3056
3057   // Ensure enough space for n additional elements.
3058   MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
3059
3060 #ifdef OBJECT_PRINT
3061   inline void Print() {
3062     Print(stdout);
3063   }
3064   void Print(FILE* out);
3065 #endif
3066   // Returns the key (slow).
3067   Object* SlowReverseLookup(Object* value);
3068
3069   // Sets the entry to (key, value) pair.
3070   inline void SetEntry(int entry,
3071                        Object* key,
3072                        Object* value);
3073   inline void SetEntry(int entry,
3074                        Object* key,
3075                        Object* value,
3076                        PropertyDetails details);
3077
3078   MUST_USE_RESULT MaybeObject* Add(Key key,
3079                                    Object* value,
3080                                    PropertyDetails details);
3081
3082  protected:
3083   // Generic at put operation.
3084   MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
3085
3086   // Add entry to dictionary.
3087   MUST_USE_RESULT MaybeObject* AddEntry(Key key,
3088                                         Object* value,
3089                                         PropertyDetails details,
3090                                         uint32_t hash);
3091
3092   // Generate new enumeration indices to avoid enumeration index overflow.
3093   MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
3094   static const int kMaxNumberKeyIndex =
3095       HashTable<Shape, Key>::kPrefixStartIndex;
3096   static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3097 };
3098
3099
3100 class StringDictionaryShape : public BaseShape<String*> {
3101  public:
3102   static inline bool IsMatch(String* key, Object* other);
3103   static inline uint32_t Hash(String* key);
3104   static inline uint32_t HashForObject(String* key, Object* object);
3105   MUST_USE_RESULT static inline MaybeObject* AsObject(String* key);
3106   static const int kPrefixSize = 2;
3107   static const int kEntrySize = 3;
3108   static const bool kIsEnumerable = true;
3109 };
3110
3111
3112 class StringDictionary: public Dictionary<StringDictionaryShape, String*> {
3113  public:
3114   static inline StringDictionary* cast(Object* obj) {
3115     ASSERT(obj->IsDictionary());
3116     return reinterpret_cast<StringDictionary*>(obj);
3117   }
3118
3119   // Copies enumerable keys to preallocated fixed array.
3120   void CopyEnumKeysTo(FixedArray* storage, FixedArray* sort_array);
3121
3122   // For transforming properties of a JSObject.
3123   MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
3124       JSObject* obj,
3125       int unused_property_fields);
3126
3127   // Find entry for key, otherwise return kNotFound. Optimized version of
3128   // HashTable::FindEntry.
3129   int FindEntry(String* key);
3130
3131   bool ContainsTransition(int entry);
3132 };
3133
3134
3135 class NumberDictionaryShape : public BaseShape<uint32_t> {
3136  public:
3137   static inline bool IsMatch(uint32_t key, Object* other);
3138   MUST_USE_RESULT static inline MaybeObject* AsObject(uint32_t key);
3139   static const int kEntrySize = 3;
3140   static const bool kIsEnumerable = false;
3141 };
3142
3143
3144 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3145  public:
3146   static const bool UsesSeed = true;
3147   static const int kPrefixSize = 2;
3148
3149   static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3150   static inline uint32_t SeededHashForObject(uint32_t key,
3151                                              uint32_t seed,
3152                                              Object* object);
3153 };
3154
3155
3156 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3157  public:
3158   static const int kPrefixSize = 0;
3159
3160   static inline uint32_t Hash(uint32_t key);
3161   static inline uint32_t HashForObject(uint32_t key, Object* object);
3162 };
3163
3164
3165 class SeededNumberDictionary
3166     : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
3167  public:
3168   static SeededNumberDictionary* cast(Object* obj) {
3169     ASSERT(obj->IsDictionary());
3170     return reinterpret_cast<SeededNumberDictionary*>(obj);
3171   }
3172
3173   // Type specific at put (default NONE attributes is used when adding).
3174   MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3175   MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
3176                                               Object* value,
3177                                               PropertyDetails details);
3178
3179   // Set an existing entry or add a new one if needed.
3180   // Return the updated dictionary.
3181   MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3182       Handle<SeededNumberDictionary> dictionary,
3183       uint32_t index,
3184       Handle<Object> value,
3185       PropertyDetails details);
3186
3187   MUST_USE_RESULT MaybeObject* Set(uint32_t key,
3188                                    Object* value,
3189                                    PropertyDetails details);
3190
3191   void UpdateMaxNumberKey(uint32_t key);
3192
3193   // If slow elements are required we will never go back to fast-case
3194   // for the elements kept in this dictionary.  We require slow
3195   // elements if an element has been added at an index larger than
3196   // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3197   // when defining a getter or setter with a number key.
3198   inline bool requires_slow_elements();
3199   inline void set_requires_slow_elements();
3200
3201   // Get the value of the max number key that has been added to this
3202   // dictionary.  max_number_key can only be called if
3203   // requires_slow_elements returns false.
3204   inline uint32_t max_number_key();
3205
3206   // Bit masks.
3207   static const int kRequiresSlowElementsMask = 1;
3208   static const int kRequiresSlowElementsTagSize = 1;
3209   static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3210 };
3211
3212
3213 class UnseededNumberDictionary
3214     : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
3215  public:
3216   static UnseededNumberDictionary* cast(Object* obj) {
3217     ASSERT(obj->IsDictionary());
3218     return reinterpret_cast<UnseededNumberDictionary*>(obj);
3219   }
3220
3221   // Type specific at put (default NONE attributes is used when adding).
3222   MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3223   MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
3224
3225   // Set an existing entry or add a new one if needed.
3226   // Return the updated dictionary.
3227   MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3228       Handle<UnseededNumberDictionary> dictionary,
3229       uint32_t index,
3230       Handle<Object> value);
3231
3232   MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
3233 };
3234
3235
3236 template <int entrysize>
3237 class ObjectHashTableShape : public BaseShape<Object*> {
3238  public:
3239   static inline bool IsMatch(Object* key, Object* other);
3240   static inline uint32_t Hash(Object* key);
3241   static inline uint32_t HashForObject(Object* key, Object* object);
3242   MUST_USE_RESULT static inline MaybeObject* AsObject(Object* key);
3243   static const int kPrefixSize = 0;
3244   static const int kEntrySize = entrysize;
3245 };
3246
3247
3248 // ObjectHashSet holds keys that are arbitrary objects by using the identity
3249 // hash of the key for hashing purposes.
3250 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
3251  public:
3252   static inline ObjectHashSet* cast(Object* obj) {
3253     ASSERT(obj->IsHashTable());
3254     return reinterpret_cast<ObjectHashSet*>(obj);
3255   }
3256
3257   // Looks up whether the given key is part of this hash set.
3258   bool Contains(Object* key);
3259
3260   // Adds the given key to this hash set.
3261   MUST_USE_RESULT MaybeObject* Add(Object* key);
3262
3263   // Removes the given key from this hash set.
3264   MUST_USE_RESULT MaybeObject* Remove(Object* key);
3265 };
3266
3267
3268 // ObjectHashTable maps keys that are arbitrary objects to object values by
3269 // using the identity hash of the key for hashing purposes.
3270 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
3271  public:
3272   static inline ObjectHashTable* cast(Object* obj) {
3273     ASSERT(obj->IsHashTable());
3274     return reinterpret_cast<ObjectHashTable*>(obj);
3275   }
3276
3277   // Looks up the value associated with the given key. The undefined value is
3278   // returned in case the key is not present.
3279   Object* Lookup(Object* key);
3280
3281   // Adds (or overwrites) the value associated with the given key. Mapping a
3282   // key to the undefined value causes removal of the whole entry.
3283   MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
3284
3285  private:
3286   friend class MarkCompactCollector;
3287
3288   void AddEntry(int entry, Object* key, Object* value);
3289   void RemoveEntry(int entry);
3290
3291   // Returns the index to the value of an entry.
3292   static inline int EntryToValueIndex(int entry) {
3293     return EntryToIndex(entry) + 1;
3294   }
3295 };
3296
3297
3298 // JSFunctionResultCache caches results of some JSFunction invocation.
3299 // It is a fixed array with fixed structure:
3300 //   [0]: factory function
3301 //   [1]: finger index
3302 //   [2]: current cache size
3303 //   [3]: dummy field.
3304 // The rest of array are key/value pairs.
3305 class JSFunctionResultCache: public FixedArray {
3306  public:
3307   static const int kFactoryIndex = 0;
3308   static const int kFingerIndex = kFactoryIndex + 1;
3309   static const int kCacheSizeIndex = kFingerIndex + 1;
3310   static const int kDummyIndex = kCacheSizeIndex + 1;
3311   static const int kEntriesIndex = kDummyIndex + 1;
3312
3313   static const int kEntrySize = 2;  // key + value
3314
3315   static const int kFactoryOffset = kHeaderSize;
3316   static const int kFingerOffset = kFactoryOffset + kPointerSize;
3317   static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3318
3319   inline void MakeZeroSize();
3320   inline void Clear();
3321
3322   inline int size();
3323   inline void set_size(int size);
3324   inline int finger_index();
3325   inline void set_finger_index(int finger_index);
3326
3327   // Casting
3328   static inline JSFunctionResultCache* cast(Object* obj);
3329
3330 #ifdef DEBUG
3331   void JSFunctionResultCacheVerify();
3332 #endif
3333 };
3334
3335
3336 // ScopeInfo represents information about different scopes of a source
3337 // program  and the allocation of the scope's variables. Scope information
3338 // is stored in a compressed form in ScopeInfo objects and is used
3339 // at runtime (stack dumps, deoptimization, etc.).
3340
3341 // This object provides quick access to scope info details for runtime
3342 // routines.
3343 class ScopeInfo : public FixedArray {
3344  public:
3345   static inline ScopeInfo* cast(Object* object);
3346
3347   // Return the type of this scope.
3348   ScopeType Type();
3349
3350   // Does this scope call eval?
3351   bool CallsEval();
3352
3353   // Return the language mode of this scope.
3354   LanguageMode language_mode();
3355
3356   // Does this scope make a non-strict eval call?
3357   bool CallsNonStrictEval() {
3358     return CallsEval() && (language_mode() == CLASSIC_MODE);
3359   }
3360
3361   // Return the total number of locals allocated on the stack and in the
3362   // context. This includes the parameters that are allocated in the context.
3363   int LocalCount();
3364
3365   // Return the number of stack slots for code. This number consists of two
3366   // parts:
3367   //  1. One stack slot per stack allocated local.
3368   //  2. One stack slot for the function name if it is stack allocated.
3369   int StackSlotCount();
3370
3371   // Return the number of context slots for code if a context is allocated. This
3372   // number consists of three parts:
3373   //  1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3374   //  2. One context slot per context allocated local.
3375   //  3. One context slot for the function name if it is context allocated.
3376   // Parameters allocated in the context count as context allocated locals. If
3377   // no contexts are allocated for this scope ContextLength returns 0.
3378   int ContextLength();
3379
3380   // Is this scope the scope of a named function expression?
3381   bool HasFunctionName();
3382
3383   // Return if this has context allocated locals.
3384   bool HasHeapAllocatedLocals();
3385
3386   // Return if contexts are allocated for this scope.
3387   bool HasContext();
3388
3389   // Return the function_name if present.
3390   String* FunctionName();
3391
3392   // Return the name of the given parameter.
3393   String* ParameterName(int var);
3394
3395   // Return the name of the given local.
3396   String* LocalName(int var);
3397
3398   // Return the name of the given stack local.
3399   String* StackLocalName(int var);
3400
3401   // Return the name of the given context local.
3402   String* ContextLocalName(int var);
3403
3404   // Return the mode of the given context local.
3405   VariableMode ContextLocalMode(int var);
3406
3407   // Return the initialization flag of the given context local.
3408   InitializationFlag ContextLocalInitFlag(int var);
3409
3410   // Lookup support for serialized scope info. Returns the
3411   // the stack slot index for a given slot name if the slot is
3412   // present; otherwise returns a value < 0. The name must be a symbol
3413   // (canonicalized).
3414   int StackSlotIndex(String* name);
3415
3416   // Lookup support for serialized scope info. Returns the
3417   // context slot index for a given slot name if the slot is present; otherwise
3418   // returns a value < 0. The name must be a symbol (canonicalized).
3419   // If the slot is present and mode != NULL, sets *mode to the corresponding
3420   // mode for that variable.
3421   int ContextSlotIndex(String* name,
3422                        VariableMode* mode,
3423                        InitializationFlag* init_flag);
3424
3425   // Lookup support for serialized scope info. Returns the
3426   // parameter index for a given parameter name if the parameter is present;
3427   // otherwise returns a value < 0. The name must be a symbol (canonicalized).
3428   int ParameterIndex(String* name);
3429
3430   // Lookup support for serialized scope info. Returns the function context
3431   // slot index if the function name is present and context-allocated (named
3432   // function expressions, only), otherwise returns a value < 0. The name
3433   // must be a symbol (canonicalized).
3434   int FunctionContextSlotIndex(String* name, VariableMode* mode);
3435
3436   static Handle<ScopeInfo> Create(Scope* scope);
3437
3438   // Serializes empty scope info.
3439   static ScopeInfo* Empty();
3440
3441 #ifdef DEBUG
3442   void Print();
3443 #endif
3444
3445   // The layout of the static part of a ScopeInfo is as follows. Each entry is
3446   // numeric and occupies one array slot.
3447   // 1. A set of properties of the scope
3448   // 2. The number of parameters. This only applies to function scopes. For
3449   //    non-function scopes this is 0.
3450   // 3. The number of non-parameter variables allocated on the stack.
3451   // 4. The number of non-parameter and parameter variables allocated in the
3452   //    context.
3453 #define FOR_EACH_NUMERIC_FIELD(V)          \
3454   V(Flags)                                 \
3455   V(ParameterCount)                        \
3456   V(StackLocalCount)                       \
3457   V(ContextLocalCount)
3458
3459 #define FIELD_ACCESSORS(name)                            \
3460   void Set##name(int value) {                            \
3461     set(k##name, Smi::FromInt(value));                   \
3462   }                                                      \
3463   int name() {                                           \
3464     if (length() > 0) {                                  \
3465       return Smi::cast(get(k##name))->value();           \
3466     } else {                                             \
3467       return 0;                                          \
3468     }                                                    \
3469   }
3470   FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3471 #undef FIELD_ACCESSORS
3472
3473  private:
3474   enum {
3475 #define DECL_INDEX(name) k##name,
3476   FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
3477 #undef DECL_INDEX
3478 #undef FOR_EACH_NUMERIC_FIELD
3479   kVariablePartIndex
3480   };
3481
3482   // The layout of the variable part of a ScopeInfo is as follows:
3483   // 1. ParameterEntries:
3484   //    This part stores the names of the parameters for function scopes. One
3485   //    slot is used per parameter, so in total this part occupies
3486   //    ParameterCount() slots in the array. For other scopes than function
3487   //    scopes ParameterCount() is 0.
3488   // 2. StackLocalEntries:
3489   //    Contains the names of local variables that are allocated on the stack,
3490   //    in increasing order of the stack slot index. One slot is used per stack
3491   //    local, so in total this part occupies StackLocalCount() slots in the
3492   //    array.
3493   // 3. ContextLocalNameEntries:
3494   //    Contains the names of local variables and parameters that are allocated
3495   //    in the context. They are stored in increasing order of the context slot
3496   //    index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3497   //    context local, so in total this part occupies ContextLocalCount() slots
3498   //    in the array.
3499   // 4. ContextLocalInfoEntries:
3500   //    Contains the variable modes and initialization flags corresponding to
3501   //    the context locals in ContextLocalNameEntries. One slot is used per
3502   //    context local, so in total this part occupies ContextLocalCount()
3503   //    slots in the array.
3504   // 5. FunctionNameEntryIndex:
3505   //    If the scope belongs to a named function expression this part contains
3506   //    information about the function variable. It always occupies two array
3507   //    slots:  a. The name of the function variable.
3508   //            b. The context or stack slot index for the variable.
3509   int ParameterEntriesIndex();
3510   int StackLocalEntriesIndex();
3511   int ContextLocalNameEntriesIndex();
3512   int ContextLocalInfoEntriesIndex();
3513   int FunctionNameEntryIndex();
3514
3515   // Location of the function variable for named function expressions.
3516   enum FunctionVariableInfo {
3517     NONE,     // No function name present.
3518     STACK,    // Function
3519     CONTEXT,
3520     UNUSED
3521   };
3522
3523   // Properties of scopes.
3524   class TypeField:             public BitField<ScopeType,            0, 3> {};
3525   class CallsEvalField:        public BitField<bool,                 3, 1> {};
3526   class LanguageModeField:     public BitField<LanguageMode,         4, 2> {};
3527   class FunctionVariableField: public BitField<FunctionVariableInfo, 6, 2> {};
3528   class FunctionVariableMode:  public BitField<VariableMode,         8, 3> {};
3529
3530   // BitFields representing the encoded information for context locals in the
3531   // ContextLocalInfoEntries part.
3532   class ContextLocalMode:      public BitField<VariableMode,         0, 3> {};
3533   class ContextLocalInitFlag:  public BitField<InitializationFlag,   3, 1> {};
3534 };
3535
3536
3537 // The cache for maps used by normalized (dictionary mode) objects.
3538 // Such maps do not have property descriptors, so a typical program
3539 // needs very limited number of distinct normalized maps.
3540 class NormalizedMapCache: public FixedArray {
3541  public:
3542   static const int kEntries = 64;
3543
3544   MUST_USE_RESULT MaybeObject* Get(JSObject* object,
3545                                    PropertyNormalizationMode mode);
3546
3547   void Clear();
3548
3549   // Casting
3550   static inline NormalizedMapCache* cast(Object* obj);
3551
3552 #ifdef DEBUG
3553   void NormalizedMapCacheVerify();
3554 #endif
3555 };
3556
3557
3558 // ByteArray represents fixed sized byte arrays.  Used for the relocation info
3559 // that is attached to code objects.
3560 class ByteArray: public FixedArrayBase {
3561  public:
3562   inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
3563
3564   // Setter and getter.
3565   inline byte get(int index);
3566   inline void set(int index, byte value);
3567
3568   // Treat contents as an int array.
3569   inline int get_int(int index);
3570
3571   static int SizeFor(int length) {
3572     return OBJECT_POINTER_ALIGN(kHeaderSize + length);
3573   }
3574   // We use byte arrays for free blocks in the heap.  Given a desired size in
3575   // bytes that is a multiple of the word size and big enough to hold a byte
3576   // array, this function returns the number of elements a byte array should
3577   // have.
3578   static int LengthFor(int size_in_bytes) {
3579     ASSERT(IsAligned(size_in_bytes, kPointerSize));
3580     ASSERT(size_in_bytes >= kHeaderSize);
3581     return size_in_bytes - kHeaderSize;
3582   }
3583
3584   // Returns data start address.
3585   inline Address GetDataStartAddress();
3586
3587   // Returns a pointer to the ByteArray object for a given data start address.
3588   static inline ByteArray* FromDataStartAddress(Address address);
3589
3590   // Casting.
3591   static inline ByteArray* cast(Object* obj);
3592
3593   // Dispatched behavior.
3594   inline int ByteArraySize() {
3595     return SizeFor(this->length());
3596   }
3597 #ifdef OBJECT_PRINT
3598   inline void ByteArrayPrint() {
3599     ByteArrayPrint(stdout);
3600   }
3601   void ByteArrayPrint(FILE* out);
3602 #endif
3603 #ifdef DEBUG
3604   void ByteArrayVerify();
3605 #endif
3606
3607   // Layout description.
3608   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3609
3610   // Maximal memory consumption for a single ByteArray.
3611   static const int kMaxSize = 512 * MB;
3612   // Maximal length of a single ByteArray.
3613   static const int kMaxLength = kMaxSize - kHeaderSize;
3614
3615  private:
3616   DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
3617 };
3618
3619
3620 // FreeSpace represents fixed sized areas of the heap that are not currently in
3621 // use.  Used by the heap and GC.
3622 class FreeSpace: public HeapObject {
3623  public:
3624   // [size]: size of the free space including the header.
3625   inline int size();
3626   inline void set_size(int value);
3627
3628   inline int Size() { return size(); }
3629
3630   // Casting.
3631   static inline FreeSpace* cast(Object* obj);
3632
3633 #ifdef OBJECT_PRINT
3634   inline void FreeSpacePrint() {
3635     FreeSpacePrint(stdout);
3636   }
3637   void FreeSpacePrint(FILE* out);
3638 #endif
3639 #ifdef DEBUG
3640   void FreeSpaceVerify();
3641 #endif
3642
3643   // Layout description.
3644   // Size is smi tagged when it is stored.
3645   static const int kSizeOffset = HeapObject::kHeaderSize;
3646   static const int kHeaderSize = kSizeOffset + kPointerSize;
3647
3648   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3649
3650  private:
3651   DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
3652 };
3653
3654
3655 // An ExternalArray represents a fixed-size array of primitive values
3656 // which live outside the JavaScript heap. Its subclasses are used to
3657 // implement the CanvasArray types being defined in the WebGL
3658 // specification. As of this writing the first public draft is not yet
3659 // available, but Khronos members can access the draft at:
3660 //   https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
3661 //
3662 // The semantics of these arrays differ from CanvasPixelArray.
3663 // Out-of-range values passed to the setter are converted via a C
3664 // cast, not clamping. Out-of-range indices cause exceptions to be
3665 // raised rather than being silently ignored.
3666 class ExternalArray: public FixedArrayBase {
3667  public:
3668   inline bool is_the_hole(int index) { return false; }
3669
3670   // [external_pointer]: The pointer to the external memory area backing this
3671   // external array.
3672   DECL_ACCESSORS(external_pointer, void)  // Pointer to the data store.
3673
3674   // Casting.
3675   static inline ExternalArray* cast(Object* obj);
3676
3677   // Maximal acceptable length for an external array.
3678   static const int kMaxLength = 0x3fffffff;
3679
3680   // ExternalArray headers are not quadword aligned.
3681   static const int kExternalPointerOffset =
3682       POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
3683   static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
3684   static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3685
3686  private:
3687   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
3688 };
3689
3690
3691 // A ExternalPixelArray represents a fixed-size byte array with special
3692 // semantics used for implementing the CanvasPixelArray object. Please see the
3693 // specification at:
3694
3695 // http://www.whatwg.org/specs/web-apps/current-work/
3696 //                      multipage/the-canvas-element.html#canvaspixelarray
3697 // In particular, write access clamps the value written to 0 or 255 if the
3698 // value written is outside this range.
3699 class ExternalPixelArray: public ExternalArray {
3700  public:
3701   inline uint8_t* external_pixel_pointer();
3702
3703   // Setter and getter.
3704   inline uint8_t get_scalar(int index);
3705   MUST_USE_RESULT inline MaybeObject* get(int index);
3706   inline void set(int index, uint8_t value);
3707
3708   // This accessor applies the correct conversion from Smi, HeapNumber and
3709   // undefined and clamps the converted value between 0 and 255.
3710   Object* SetValue(uint32_t index, Object* value);
3711
3712   // Casting.
3713   static inline ExternalPixelArray* cast(Object* obj);
3714
3715 #ifdef OBJECT_PRINT
3716   inline void ExternalPixelArrayPrint() {
3717     ExternalPixelArrayPrint(stdout);
3718   }
3719   void ExternalPixelArrayPrint(FILE* out);
3720 #endif
3721 #ifdef DEBUG
3722   void ExternalPixelArrayVerify();
3723 #endif  // DEBUG
3724
3725  private:
3726   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalPixelArray);
3727 };
3728
3729
3730 class ExternalByteArray: public ExternalArray {
3731  public:
3732   // Setter and getter.
3733   inline int8_t get_scalar(int index);
3734   MUST_USE_RESULT inline MaybeObject* get(int index);
3735   inline void set(int index, int8_t value);
3736
3737   // This accessor applies the correct conversion from Smi, HeapNumber
3738   // and undefined.
3739   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3740
3741   // Casting.
3742   static inline ExternalByteArray* cast(Object* obj);
3743
3744 #ifdef OBJECT_PRINT
3745   inline void ExternalByteArrayPrint() {
3746     ExternalByteArrayPrint(stdout);
3747   }
3748   void ExternalByteArrayPrint(FILE* out);
3749 #endif
3750 #ifdef DEBUG
3751   void ExternalByteArrayVerify();
3752 #endif  // DEBUG
3753
3754  private:
3755   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalByteArray);
3756 };
3757
3758
3759 class ExternalUnsignedByteArray: public ExternalArray {
3760  public:
3761   // Setter and getter.
3762   inline uint8_t get_scalar(int index);
3763   MUST_USE_RESULT inline MaybeObject* get(int index);
3764   inline void set(int index, uint8_t value);
3765
3766   // This accessor applies the correct conversion from Smi, HeapNumber
3767   // and undefined.
3768   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3769
3770   // Casting.
3771   static inline ExternalUnsignedByteArray* cast(Object* obj);
3772
3773 #ifdef OBJECT_PRINT
3774   inline void ExternalUnsignedByteArrayPrint() {
3775     ExternalUnsignedByteArrayPrint(stdout);
3776   }
3777   void ExternalUnsignedByteArrayPrint(FILE* out);
3778 #endif
3779 #ifdef DEBUG
3780   void ExternalUnsignedByteArrayVerify();
3781 #endif  // DEBUG
3782
3783  private:
3784   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedByteArray);
3785 };
3786
3787
3788 class ExternalShortArray: public ExternalArray {
3789  public:
3790   // Setter and getter.
3791   inline int16_t get_scalar(int index);
3792   MUST_USE_RESULT inline MaybeObject* get(int index);
3793   inline void set(int index, int16_t value);
3794
3795   // This accessor applies the correct conversion from Smi, HeapNumber
3796   // and undefined.
3797   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3798
3799   // Casting.
3800   static inline ExternalShortArray* cast(Object* obj);
3801
3802 #ifdef OBJECT_PRINT
3803   inline void ExternalShortArrayPrint() {
3804     ExternalShortArrayPrint(stdout);
3805   }
3806   void ExternalShortArrayPrint(FILE* out);
3807 #endif
3808 #ifdef DEBUG
3809   void ExternalShortArrayVerify();
3810 #endif  // DEBUG
3811
3812  private:
3813   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalShortArray);
3814 };
3815
3816
3817 class ExternalUnsignedShortArray: public ExternalArray {
3818  public:
3819   // Setter and getter.
3820   inline uint16_t get_scalar(int index);
3821   MUST_USE_RESULT inline MaybeObject* get(int index);
3822   inline void set(int index, uint16_t value);
3823
3824   // This accessor applies the correct conversion from Smi, HeapNumber
3825   // and undefined.
3826   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3827
3828   // Casting.
3829   static inline ExternalUnsignedShortArray* cast(Object* obj);
3830
3831 #ifdef OBJECT_PRINT
3832   inline void ExternalUnsignedShortArrayPrint() {
3833     ExternalUnsignedShortArrayPrint(stdout);
3834   }
3835   void ExternalUnsignedShortArrayPrint(FILE* out);
3836 #endif
3837 #ifdef DEBUG
3838   void ExternalUnsignedShortArrayVerify();
3839 #endif  // DEBUG
3840
3841  private:
3842   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedShortArray);
3843 };
3844
3845
3846 class ExternalIntArray: public ExternalArray {
3847  public:
3848   // Setter and getter.
3849   inline int32_t get_scalar(int index);
3850   MUST_USE_RESULT inline MaybeObject* get(int index);
3851   inline void set(int index, int32_t value);
3852
3853   // This accessor applies the correct conversion from Smi, HeapNumber
3854   // and undefined.
3855   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3856
3857   // Casting.
3858   static inline ExternalIntArray* cast(Object* obj);
3859
3860 #ifdef OBJECT_PRINT
3861   inline void ExternalIntArrayPrint() {
3862     ExternalIntArrayPrint(stdout);
3863   }
3864   void ExternalIntArrayPrint(FILE* out);
3865 #endif
3866 #ifdef DEBUG
3867   void ExternalIntArrayVerify();
3868 #endif  // DEBUG
3869
3870  private:
3871   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalIntArray);
3872 };
3873
3874
3875 class ExternalUnsignedIntArray: public ExternalArray {
3876  public:
3877   // Setter and getter.
3878   inline uint32_t get_scalar(int index);
3879   MUST_USE_RESULT inline MaybeObject* get(int index);
3880   inline void set(int index, uint32_t value);
3881
3882   // This accessor applies the correct conversion from Smi, HeapNumber
3883   // and undefined.
3884   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3885
3886   // Casting.
3887   static inline ExternalUnsignedIntArray* cast(Object* obj);
3888
3889 #ifdef OBJECT_PRINT
3890   inline void ExternalUnsignedIntArrayPrint() {
3891     ExternalUnsignedIntArrayPrint(stdout);
3892   }
3893   void ExternalUnsignedIntArrayPrint(FILE* out);
3894 #endif
3895 #ifdef DEBUG
3896   void ExternalUnsignedIntArrayVerify();
3897 #endif  // DEBUG
3898
3899  private:
3900   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedIntArray);
3901 };
3902
3903
3904 class ExternalFloatArray: public ExternalArray {
3905  public:
3906   // Setter and getter.
3907   inline float get_scalar(int index);
3908   MUST_USE_RESULT inline MaybeObject* get(int index);
3909   inline void set(int index, float value);
3910
3911   // This accessor applies the correct conversion from Smi, HeapNumber
3912   // and undefined.
3913   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3914
3915   // Casting.
3916   static inline ExternalFloatArray* cast(Object* obj);
3917
3918 #ifdef OBJECT_PRINT
3919   inline void ExternalFloatArrayPrint() {
3920     ExternalFloatArrayPrint(stdout);
3921   }
3922   void ExternalFloatArrayPrint(FILE* out);
3923 #endif
3924 #ifdef DEBUG
3925   void ExternalFloatArrayVerify();
3926 #endif  // DEBUG
3927
3928  private:
3929   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloatArray);
3930 };
3931
3932
3933 class ExternalDoubleArray: public ExternalArray {
3934  public:
3935   // Setter and getter.
3936   inline double get_scalar(int index);
3937   MUST_USE_RESULT inline MaybeObject* get(int index);
3938   inline void set(int index, double value);
3939
3940   // This accessor applies the correct conversion from Smi, HeapNumber
3941   // and undefined.
3942   MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3943
3944   // Casting.
3945   static inline ExternalDoubleArray* cast(Object* obj);
3946
3947 #ifdef OBJECT_PRINT
3948   inline void ExternalDoubleArrayPrint() {
3949     ExternalDoubleArrayPrint(stdout);
3950   }
3951   void ExternalDoubleArrayPrint(FILE* out);
3952 #endif  // OBJECT_PRINT
3953 #ifdef DEBUG
3954   void ExternalDoubleArrayVerify();
3955 #endif  // DEBUG
3956
3957  private:
3958   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalDoubleArray);
3959 };
3960
3961
3962 // DeoptimizationInputData is a fixed array used to hold the deoptimization
3963 // data for code generated by the Hydrogen/Lithium compiler.  It also
3964 // contains information about functions that were inlined.  If N different
3965 // functions were inlined then first N elements of the literal array will
3966 // contain these functions.
3967 //
3968 // It can be empty.
3969 class DeoptimizationInputData: public FixedArray {
3970  public:
3971   // Layout description.  Indices in the array.
3972   static const int kTranslationByteArrayIndex = 0;
3973   static const int kInlinedFunctionCountIndex = 1;
3974   static const int kLiteralArrayIndex = 2;
3975   static const int kOsrAstIdIndex = 3;
3976   static const int kOsrPcOffsetIndex = 4;
3977   static const int kFirstDeoptEntryIndex = 5;
3978
3979   // Offsets of deopt entry elements relative to the start of the entry.
3980   static const int kAstIdOffset = 0;
3981   static const int kTranslationIndexOffset = 1;
3982   static const int kArgumentsStackHeightOffset = 2;
3983   static const int kPcOffset = 3;
3984   static const int kDeoptEntrySize = 4;
3985
3986   // Simple element accessors.
3987 #define DEFINE_ELEMENT_ACCESSORS(name, type)      \
3988   type* name() {                                  \
3989     return type::cast(get(k##name##Index));       \
3990   }                                               \
3991   void Set##name(type* value) {                   \
3992     set(k##name##Index, value);                   \
3993   }
3994
3995   DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
3996   DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
3997   DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
3998   DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
3999   DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4000
4001 #undef DEFINE_ELEMENT_ACCESSORS
4002
4003   // Accessors for elements of the ith deoptimization entry.
4004 #define DEFINE_ENTRY_ACCESSORS(name, type)                       \
4005   type* name(int i) {                                            \
4006     return type::cast(get(IndexForEntry(i) + k##name##Offset));  \
4007   }                                                              \
4008   void Set##name(int i, type* value) {                           \
4009     set(IndexForEntry(i) + k##name##Offset, value);              \
4010   }
4011
4012   DEFINE_ENTRY_ACCESSORS(AstId, Smi)
4013   DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4014   DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4015   DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4016
4017 #undef DEFINE_ENTRY_ACCESSORS
4018
4019   int DeoptCount() {
4020     return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4021   }
4022
4023   // Allocates a DeoptimizationInputData.
4024   MUST_USE_RESULT static MaybeObject* Allocate(int deopt_entry_count,
4025                                                PretenureFlag pretenure);
4026
4027   // Casting.
4028   static inline DeoptimizationInputData* cast(Object* obj);
4029
4030 #ifdef ENABLE_DISASSEMBLER
4031   void DeoptimizationInputDataPrint(FILE* out);
4032 #endif
4033
4034  private:
4035   static int IndexForEntry(int i) {
4036     return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4037   }
4038
4039   static int LengthFor(int entry_count) {
4040     return IndexForEntry(entry_count);
4041   }
4042 };
4043
4044
4045 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4046 // data for code generated by the full compiler.
4047 // The format of the these objects is
4048 //   [i * 2]: Ast ID for ith deoptimization.
4049 //   [i * 2 + 1]: PC and state of ith deoptimization
4050 class DeoptimizationOutputData: public FixedArray {
4051  public:
4052   int DeoptPoints() { return length() / 2; }
4053   Smi* AstId(int index) { return Smi::cast(get(index * 2)); }
4054   void SetAstId(int index, Smi* id) { set(index * 2, id); }
4055   Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4056   void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4057
4058   static int LengthOfFixedArray(int deopt_points) {
4059     return deopt_points * 2;
4060   }
4061
4062   // Allocates a DeoptimizationOutputData.
4063   MUST_USE_RESULT static MaybeObject* Allocate(int number_of_deopt_points,
4064                                                PretenureFlag pretenure);
4065
4066   // Casting.
4067   static inline DeoptimizationOutputData* cast(Object* obj);
4068
4069 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4070   void DeoptimizationOutputDataPrint(FILE* out);
4071 #endif
4072 };
4073
4074
4075 // Forward declaration.
4076 class JSGlobalPropertyCell;
4077
4078 // TypeFeedbackCells is a fixed array used to hold the association between
4079 // cache cells and AST ids for code generated by the full compiler.
4080 // The format of the these objects is
4081 //   [i * 2]: Global property cell of ith cache cell.
4082 //   [i * 2 + 1]: Ast ID for ith cache cell.
4083 class TypeFeedbackCells: public FixedArray {
4084  public:
4085   int CellCount() { return length() / 2; }
4086   static int LengthOfFixedArray(int cell_count) { return cell_count * 2; }
4087
4088   // Accessors for AST ids associated with cache values.
4089   inline Smi* AstId(int index);
4090   inline void SetAstId(int index, Smi* id);
4091
4092   // Accessors for global property cells holding the cache values.
4093   inline JSGlobalPropertyCell* Cell(int index);
4094   inline void SetCell(int index, JSGlobalPropertyCell* cell);
4095
4096   // The object that indicates an uninitialized cache.
4097   static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
4098
4099   // The object that indicates a megamorphic state.
4100   static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
4101
4102   // A raw version of the uninitialized sentinel that's safe to read during
4103   // garbage collection (e.g., for patching the cache).
4104   static inline Object* RawUninitializedSentinel(Heap* heap);
4105
4106   // Casting.
4107   static inline TypeFeedbackCells* cast(Object* obj);
4108
4109   static const int kForInFastCaseMarker = 0;
4110   static const int kForInSlowCaseMarker = 1;
4111 };
4112
4113
4114 // Forward declaration.
4115 class SafepointEntry;
4116 class TypeFeedbackInfo;
4117
4118 // Code describes objects with on-the-fly generated machine code.
4119 class Code: public HeapObject {
4120  public:
4121   // Opaque data type for encapsulating code flags like kind, inline
4122   // cache state, and arguments count.
4123   // FLAGS_MIN_VALUE and FLAGS_MAX_VALUE are specified to ensure that
4124   // enumeration type has correct value range (see Issue 830 for more details).
4125   enum Flags {
4126     FLAGS_MIN_VALUE = kMinInt,
4127     FLAGS_MAX_VALUE = kMaxInt
4128   };
4129
4130   enum Kind {
4131     FUNCTION,
4132     OPTIMIZED_FUNCTION,
4133     STUB,
4134     BUILTIN,
4135     LOAD_IC,
4136     KEYED_LOAD_IC,
4137     CALL_IC,
4138     KEYED_CALL_IC,
4139     STORE_IC,
4140     KEYED_STORE_IC,
4141     UNARY_OP_IC,
4142     BINARY_OP_IC,
4143     COMPARE_IC,
4144     TO_BOOLEAN_IC,
4145     // No more than 16 kinds. The value currently encoded in four bits in
4146     // Flags.
4147
4148     // Pseudo-kinds.
4149     REGEXP = BUILTIN,
4150     FIRST_IC_KIND = LOAD_IC,
4151     LAST_IC_KIND = TO_BOOLEAN_IC
4152   };
4153
4154   enum {
4155     NUMBER_OF_KINDS = LAST_IC_KIND + 1
4156   };
4157
4158   typedef int ExtraICState;
4159
4160   static const ExtraICState kNoExtraICState = 0;
4161
4162 #ifdef ENABLE_DISASSEMBLER
4163   // Printing
4164   static const char* Kind2String(Kind kind);
4165   static const char* ICState2String(InlineCacheState state);
4166   static const char* PropertyType2String(PropertyType type);
4167   static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
4168   inline void Disassemble(const char* name) {
4169     Disassemble(name, stdout);
4170   }
4171   void Disassemble(const char* name, FILE* out);
4172 #endif  // ENABLE_DISASSEMBLER
4173
4174   // [instruction_size]: Size of the native instructions
4175   inline int instruction_size();
4176   inline void set_instruction_size(int value);
4177
4178   // [relocation_info]: Code relocation information
4179   DECL_ACCESSORS(relocation_info, ByteArray)
4180   void InvalidateRelocation();
4181
4182   // [handler_table]: Fixed array containing offsets of exception handlers.
4183   DECL_ACCESSORS(handler_table, FixedArray)
4184
4185   // [deoptimization_data]: Array containing data for deopt.
4186   DECL_ACCESSORS(deoptimization_data, FixedArray)
4187
4188   // [type_feedback_info]: Struct containing type feedback information.
4189   // Will contain either a TypeFeedbackInfo object, or undefined.
4190   DECL_ACCESSORS(type_feedback_info, Object)
4191
4192   // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4193   // field does not have to be traced during garbage collection since
4194   // it is only used by the garbage collector itself.
4195   DECL_ACCESSORS(gc_metadata, Object)
4196
4197   // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4198   // at the moment when this object was created.
4199   inline void set_ic_age(int count);
4200   inline int ic_age();
4201
4202   // Unchecked accessors to be used during GC.
4203   inline ByteArray* unchecked_relocation_info();
4204   inline FixedArray* unchecked_deoptimization_data();
4205
4206   inline int relocation_size();
4207
4208   // [flags]: Various code flags.
4209   inline Flags flags();
4210   inline void set_flags(Flags flags);
4211
4212   // [flags]: Access to specific code flags.
4213   inline Kind kind();
4214   inline InlineCacheState ic_state();  // Only valid for IC stubs.
4215   inline ExtraICState extra_ic_state();  // Only valid for IC stubs.
4216   inline PropertyType type();  // Only valid for monomorphic IC stubs.
4217   inline int arguments_count();  // Only valid for call IC stubs.
4218
4219   // Testers for IC stub kinds.
4220   inline bool is_inline_cache_stub();
4221   inline bool is_load_stub() { return kind() == LOAD_IC; }
4222   inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4223   inline bool is_store_stub() { return kind() == STORE_IC; }
4224   inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4225   inline bool is_call_stub() { return kind() == CALL_IC; }
4226   inline bool is_keyed_call_stub() { return kind() == KEYED_CALL_IC; }
4227   inline bool is_unary_op_stub() { return kind() == UNARY_OP_IC; }
4228   inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4229   inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4230   inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4231
4232   // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
4233   inline int major_key();
4234   inline void set_major_key(int value);
4235
4236   // For stubs, tells whether they should always exist, so that they can be
4237   // called from other stubs.
4238   inline bool is_pregenerated();
4239   inline void set_is_pregenerated(bool value);
4240
4241   // [optimizable]: For FUNCTION kind, tells if it is optimizable.
4242   inline bool optimizable();
4243   inline void set_optimizable(bool value);
4244
4245   // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4246   // deoptimization support.
4247   inline bool has_deoptimization_support();
4248   inline void set_has_deoptimization_support(bool value);
4249
4250   // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4251   // been compiled with debug break slots.
4252   inline bool has_debug_break_slots();
4253   inline void set_has_debug_break_slots(bool value);
4254
4255   // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
4256   // been compiled with IsOptimizing set to true.
4257   inline bool is_compiled_optimizable();
4258   inline void set_compiled_optimizable(bool value);
4259
4260   // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4261   // how long the function has been marked for OSR and therefore which
4262   // level of loop nesting we are willing to do on-stack replacement
4263   // for.
4264   inline void set_allow_osr_at_loop_nesting_level(int level);
4265   inline int allow_osr_at_loop_nesting_level();
4266
4267   // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4268   // the code object was seen on the stack with no IC patching going on.
4269   inline int profiler_ticks();
4270   inline void set_profiler_ticks(int ticks);
4271
4272   // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4273   // reserved in the code prologue.
4274   inline unsigned stack_slots();
4275   inline void set_stack_slots(unsigned slots);
4276
4277   // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
4278   // the instruction stream where the safepoint table starts.
4279   inline unsigned safepoint_table_offset();
4280   inline void set_safepoint_table_offset(unsigned offset);
4281
4282   // [stack_check_table_start]: For kind FUNCTION, the offset in the
4283   // instruction stream where the stack check table starts.
4284   inline unsigned stack_check_table_offset();
4285   inline void set_stack_check_table_offset(unsigned offset);
4286
4287   // [check type]: For kind CALL_IC, tells how to check if the
4288   // receiver is valid for the given call.
4289   inline CheckType check_type();
4290   inline void set_check_type(CheckType value);
4291
4292   // [type-recording unary op type]: For kind UNARY_OP_IC.
4293   inline byte unary_op_type();
4294   inline void set_unary_op_type(byte value);
4295
4296   // [type-recording binary op type]: For kind BINARY_OP_IC.
4297   inline byte binary_op_type();
4298   inline void set_binary_op_type(byte value);
4299   inline byte binary_op_result_type();
4300   inline void set_binary_op_result_type(byte value);
4301
4302   // [compare state]: For kind COMPARE_IC, tells what state the stub is in.
4303   inline byte compare_state();
4304   inline void set_compare_state(byte value);
4305
4306   // [compare_operation]: For kind COMPARE_IC tells what compare operation the
4307   // stub was generated for.
4308   inline byte compare_operation();
4309   inline void set_compare_operation(byte value);
4310
4311   // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4312   inline byte to_boolean_state();
4313   inline void set_to_boolean_state(byte value);
4314
4315   // [has_function_cache]: For kind STUB tells whether there is a function
4316   // cache is passed to the stub.
4317   inline bool has_function_cache();
4318   inline void set_has_function_cache(bool flag);
4319
4320   // Get the safepoint entry for the given pc.
4321   SafepointEntry GetSafepointEntry(Address pc);
4322
4323   // Mark this code object as not having a stack check table.  Assumes kind
4324   // is FUNCTION.
4325   void SetNoStackCheckTable();
4326
4327   // Find the first map in an IC stub.
4328   Map* FindFirstMap();
4329
4330   class ExtraICStateStrictMode: public BitField<StrictModeFlag, 0, 1> {};
4331   class ExtraICStateKeyedAccessGrowMode:
4332       public BitField<KeyedAccessGrowMode, 1, 1> {};  // NOLINT
4333
4334   static const int kExtraICStateGrowModeShift = 1;
4335
4336   static inline StrictModeFlag GetStrictMode(ExtraICState extra_ic_state) {
4337     return ExtraICStateStrictMode::decode(extra_ic_state);
4338   }
4339
4340   static inline KeyedAccessGrowMode GetKeyedAccessGrowMode(
4341       ExtraICState extra_ic_state) {
4342     return ExtraICStateKeyedAccessGrowMode::decode(extra_ic_state);
4343   }
4344
4345   static inline ExtraICState ComputeExtraICState(
4346       KeyedAccessGrowMode grow_mode,
4347       StrictModeFlag strict_mode) {
4348     return ExtraICStateKeyedAccessGrowMode::encode(grow_mode) |
4349         ExtraICStateStrictMode::encode(strict_mode);
4350   }
4351
4352   // Flags operations.
4353   static inline Flags ComputeFlags(
4354       Kind kind,
4355       InlineCacheState ic_state = UNINITIALIZED,
4356       ExtraICState extra_ic_state = kNoExtraICState,
4357       PropertyType type = NORMAL,
4358       int argc = -1,
4359       InlineCacheHolderFlag holder = OWN_MAP);
4360
4361   static inline Flags ComputeMonomorphicFlags(
4362       Kind kind,
4363       PropertyType type,
4364       ExtraICState extra_ic_state = kNoExtraICState,
4365       InlineCacheHolderFlag holder = OWN_MAP,
4366       int argc = -1);
4367
4368   static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4369   static inline PropertyType ExtractTypeFromFlags(Flags flags);
4370   static inline Kind ExtractKindFromFlags(Flags flags);
4371   static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4372   static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4373   static inline int ExtractArgumentsCountFromFlags(Flags flags);
4374
4375   static inline Flags RemoveTypeFromFlags(Flags flags);
4376
4377   // Convert a target address into a code object.
4378   static inline Code* GetCodeFromTargetAddress(Address address);
4379
4380   // Convert an entry address into an object.
4381   static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4382
4383   // Returns the address of the first instruction.
4384   inline byte* instruction_start();
4385
4386   // Returns the address right after the last instruction.
4387   inline byte* instruction_end();
4388
4389   // Returns the size of the instructions, padding, and relocation information.
4390   inline int body_size();
4391
4392   // Returns the address of the first relocation info (read backwards!).
4393   inline byte* relocation_start();
4394
4395   // Code entry point.
4396   inline byte* entry();
4397
4398   // Returns true if pc is inside this object's instructions.
4399   inline bool contains(byte* pc);
4400
4401   // Relocate the code by delta bytes. Called to signal that this code
4402   // object has been moved by delta bytes.
4403   void Relocate(intptr_t delta);
4404
4405   // Migrate code described by desc.
4406   void CopyFrom(const CodeDesc& desc);
4407
4408   // Returns the object size for a given body (used for allocation).
4409   static int SizeFor(int body_size) {
4410     ASSERT_SIZE_TAG_ALIGNED(body_size);
4411     return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4412   }
4413
4414   // Calculate the size of the code object to report for log events. This takes
4415   // the layout of the code object into account.
4416   int ExecutableSize() {
4417     // Check that the assumptions about the layout of the code object holds.
4418     ASSERT_EQ(static_cast<int>(instruction_start() - address()),
4419               Code::kHeaderSize);
4420     return instruction_size() + Code::kHeaderSize;
4421   }
4422
4423   // Locating source position.
4424   int SourcePosition(Address pc);
4425   int SourceStatementPosition(Address pc);
4426
4427   // Casting.
4428   static inline Code* cast(Object* obj);
4429
4430   // Dispatched behavior.
4431   int CodeSize() { return SizeFor(body_size()); }
4432   inline void CodeIterateBody(ObjectVisitor* v);
4433
4434   template<typename StaticVisitor>
4435   inline void CodeIterateBody(Heap* heap);
4436 #ifdef OBJECT_PRINT
4437   inline void CodePrint() {
4438     CodePrint(stdout);
4439   }
4440   void CodePrint(FILE* out);
4441 #endif
4442 #ifdef DEBUG
4443   void CodeVerify();
4444 #endif
4445   void ClearInlineCaches();
4446   void ClearTypeFeedbackCells(Heap* heap);
4447
4448   // Max loop nesting marker used to postpose OSR. We don't take loop
4449   // nesting that is deeper than 5 levels into account.
4450   static const int kMaxLoopNestingMarker = 6;
4451
4452   // Layout description.
4453   static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
4454   static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
4455   static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4456   static const int kDeoptimizationDataOffset =
4457       kHandlerTableOffset + kPointerSize;
4458   static const int kTypeFeedbackInfoOffset =
4459       kDeoptimizationDataOffset + kPointerSize;
4460   static const int kGCMetadataOffset = kTypeFeedbackInfoOffset + kPointerSize;
4461   static const int kICAgeOffset =
4462       kGCMetadataOffset + kPointerSize;
4463   static const int kFlagsOffset = kICAgeOffset + kIntSize;
4464   static const int kKindSpecificFlagsOffset = kFlagsOffset + kIntSize;
4465   static const int kKindSpecificFlagsSize = 2 * kIntSize;
4466
4467   static const int kHeaderPaddingStart = kKindSpecificFlagsOffset +
4468       kKindSpecificFlagsSize;
4469
4470   // Add padding to align the instruction start following right after
4471   // the Code object header.
4472   static const int kHeaderSize =
4473       (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4474
4475   // Byte offsets within kKindSpecificFlagsOffset.
4476   static const int kStubMajorKeyOffset = kKindSpecificFlagsOffset;
4477   static const int kOptimizableOffset = kKindSpecificFlagsOffset;
4478   static const int kStackSlotsOffset = kKindSpecificFlagsOffset;
4479   static const int kCheckTypeOffset = kKindSpecificFlagsOffset;
4480
4481   static const int kUnaryOpTypeOffset = kStubMajorKeyOffset + 1;
4482   static const int kBinaryOpTypeOffset = kStubMajorKeyOffset + 1;
4483   static const int kCompareStateOffset = kStubMajorKeyOffset + 1;
4484   static const int kToBooleanTypeOffset = kStubMajorKeyOffset + 1;
4485   static const int kHasFunctionCacheOffset = kStubMajorKeyOffset + 1;
4486
4487   static const int kFullCodeFlags = kOptimizableOffset + 1;
4488   class FullCodeFlagsHasDeoptimizationSupportField:
4489       public BitField<bool, 0, 1> {};  // NOLINT
4490   class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4491   class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
4492
4493   static const int kBinaryOpReturnTypeOffset = kBinaryOpTypeOffset + 1;
4494
4495   static const int kCompareOperationOffset = kCompareStateOffset + 1;
4496
4497   static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
4498   static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
4499
4500   static const int kSafepointTableOffsetOffset = kStackSlotsOffset + kIntSize;
4501   static const int kStackCheckTableOffsetOffset = kStackSlotsOffset + kIntSize;
4502
4503   // Flags layout.  BitField<type, shift, size>.
4504   class ICStateField: public BitField<InlineCacheState, 0, 3> {};
4505   class TypeField: public BitField<PropertyType, 3, 4> {};
4506   class CacheHolderField: public BitField<InlineCacheHolderFlag, 7, 1> {};
4507   class KindField: public BitField<Kind, 8, 4> {};
4508   class ExtraICStateField: public BitField<ExtraICState, 12, 2> {};
4509   class IsPregeneratedField: public BitField<bool, 14, 1> {};
4510
4511   // Signed field cannot be encoded using the BitField class.
4512   static const int kArgumentsCountShift = 15;
4513   static const int kArgumentsCountMask = ~((1 << kArgumentsCountShift) - 1);
4514
4515   // This constant should be encodable in an ARM instruction.
4516   static const int kFlagsNotUsedInLookup =
4517       TypeField::kMask | CacheHolderField::kMask;
4518
4519  private:
4520   DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
4521 };
4522
4523
4524 // All heap objects have a Map that describes their structure.
4525 //  A Map contains information about:
4526 //  - Size information about the object
4527 //  - How to iterate over an object (for garbage collection)
4528 class Map: public HeapObject {
4529  public:
4530   // Instance size.
4531   // Size in bytes or kVariableSizeSentinel if instances do not have
4532   // a fixed size.
4533   inline int instance_size();
4534   inline void set_instance_size(int value);
4535
4536   // Count of properties allocated in the object.
4537   inline int inobject_properties();
4538   inline void set_inobject_properties(int value);
4539
4540   // Count of property fields pre-allocated in the object when first allocated.
4541   inline int pre_allocated_property_fields();
4542   inline void set_pre_allocated_property_fields(int value);
4543
4544   // Instance type.
4545   inline InstanceType instance_type();
4546   inline void set_instance_type(InstanceType value);
4547
4548   // Tells how many unused property fields are available in the
4549   // instance (only used for JSObject in fast mode).
4550   inline int unused_property_fields();
4551   inline void set_unused_property_fields(int value);
4552
4553   // Bit field.
4554   inline byte bit_field();
4555   inline void set_bit_field(byte value);
4556
4557   // Bit field 2.
4558   inline byte bit_field2();
4559   inline void set_bit_field2(byte value);
4560
4561   // Bit field 3.
4562   // TODO(1399): It should be possible to make room for bit_field3 in the map
4563   // without overloading the instance descriptors field (and storing it in the
4564   // DescriptorArray when the map has one).
4565   inline int bit_field3();
4566   inline void set_bit_field3(int value);
4567
4568   // Tells whether the object in the prototype property will be used
4569   // for instances created from this function.  If the prototype
4570   // property is set to a value that is not a JSObject, the prototype
4571   // property will not be used to create instances of the function.
4572   // See ECMA-262, 13.2.2.
4573   inline void set_non_instance_prototype(bool value);
4574   inline bool has_non_instance_prototype();
4575
4576   // Tells whether function has special prototype property. If not, prototype
4577   // property will not be created when accessed (will return undefined),
4578   // and construction from this function will not be allowed.
4579   inline void set_function_with_prototype(bool value);
4580   inline bool function_with_prototype();
4581
4582   // Tells whether the instance with this map should be ignored by the
4583   // __proto__ accessor.
4584   inline void set_is_hidden_prototype() {
4585     set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
4586   }
4587
4588   inline bool is_hidden_prototype() {
4589     return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
4590   }
4591
4592   // Records and queries whether the instance has a named interceptor.
4593   inline void set_has_named_interceptor() {
4594     set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
4595   }
4596
4597   inline bool has_named_interceptor() {
4598     return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
4599   }
4600
4601   // Records and queries whether the instance has an indexed interceptor.
4602   inline void set_has_indexed_interceptor() {
4603     set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
4604   }
4605
4606   inline bool has_indexed_interceptor() {
4607     return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
4608   }
4609
4610   // Tells whether the instance is undetectable.
4611   // An undetectable object is a special class of JSObject: 'typeof' operator
4612   // returns undefined, ToBoolean returns false. Otherwise it behaves like
4613   // a normal JS object.  It is useful for implementing undetectable
4614   // document.all in Firefox & Safari.
4615   // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
4616   inline void set_is_undetectable() {
4617     set_bit_field(bit_field() | (1 << kIsUndetectable));
4618   }
4619
4620   inline bool is_undetectable() {
4621     return ((1 << kIsUndetectable) & bit_field()) != 0;
4622   }
4623
4624   // Tells whether the instance has a call-as-function handler.
4625   inline void set_has_instance_call_handler() {
4626     set_bit_field3(bit_field3() | (1 << kHasInstanceCallHandler));
4627   }
4628
4629   inline bool has_instance_call_handler() {
4630     return ((1 << kHasInstanceCallHandler) & bit_field3()) != 0;
4631   }
4632
4633   inline void set_is_extensible(bool value);
4634   inline bool is_extensible();
4635
4636   inline void set_elements_kind(ElementsKind elements_kind) {
4637     ASSERT(elements_kind < kElementsKindCount);
4638     ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
4639     set_bit_field2((bit_field2() & ~kElementsKindMask) |
4640         (elements_kind << kElementsKindShift));
4641     ASSERT(this->elements_kind() == elements_kind);
4642   }
4643
4644   inline ElementsKind elements_kind() {
4645     return static_cast<ElementsKind>(
4646         (bit_field2() & kElementsKindMask) >> kElementsKindShift);
4647   }
4648
4649   // Tells whether the instance has fast elements that are only Smis.
4650   inline bool has_fast_smi_only_elements() {
4651     return elements_kind() == FAST_SMI_ONLY_ELEMENTS;
4652   }
4653
4654   // Tells whether the instance has fast elements.
4655   inline bool has_fast_elements() {
4656     return elements_kind() == FAST_ELEMENTS;
4657   }
4658
4659   inline bool has_fast_double_elements() {
4660     return elements_kind() == FAST_DOUBLE_ELEMENTS;
4661   }
4662
4663   inline bool has_non_strict_arguments_elements() {
4664     return elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4665   }
4666
4667   inline bool has_external_array_elements() {
4668     ElementsKind kind(elements_kind());
4669     return kind >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
4670         kind <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND;
4671   }
4672
4673   inline bool has_dictionary_elements() {
4674     return elements_kind() == DICTIONARY_ELEMENTS;
4675   }
4676
4677   inline bool has_slow_elements_kind() {
4678     return elements_kind() == DICTIONARY_ELEMENTS
4679         || elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4680   }
4681
4682   static bool IsValidElementsTransition(ElementsKind from_kind,
4683                                         ElementsKind to_kind);
4684
4685   // Tells whether the map is attached to SharedFunctionInfo
4686   // (for inobject slack tracking).
4687   inline void set_attached_to_shared_function_info(bool value);
4688
4689   inline bool attached_to_shared_function_info();
4690
4691   // Tells whether the map is shared between objects that may have different
4692   // behavior. If true, the map should never be modified, instead a clone
4693   // should be created and modified.
4694   inline void set_is_shared(bool value);
4695
4696   inline bool is_shared();
4697
4698   // Tells whether the instance needs security checks when accessing its
4699   // properties.
4700   inline void set_is_access_check_needed(bool access_check_needed);
4701   inline bool is_access_check_needed();
4702
4703   // Whether the named interceptor is a fallback interceptor or not
4704   inline void set_named_interceptor_is_fallback(bool value);
4705   inline bool named_interceptor_is_fallback();
4706
4707   // Tells whether the instance has the space for an external resource
4708   // object
4709   inline void set_has_external_resource(bool value);
4710   inline bool has_external_resource();
4711
4712   // [prototype]: implicit prototype object.
4713   DECL_ACCESSORS(prototype, Object)
4714
4715   // [constructor]: points back to the function responsible for this map.
4716   DECL_ACCESSORS(constructor, Object)
4717
4718   inline JSFunction* unchecked_constructor();
4719
4720   // Should only be called by the code that initializes map to set initial valid
4721   // value of the instance descriptor member.
4722   inline void init_instance_descriptors();
4723
4724   // [instance descriptors]: describes the object.
4725   DECL_ACCESSORS(instance_descriptors, DescriptorArray)
4726
4727   // Sets the instance descriptor array for the map to be an empty descriptor
4728   // array.
4729   inline void clear_instance_descriptors();
4730
4731   // [stub cache]: contains stubs compiled for this map.
4732   DECL_ACCESSORS(code_cache, Object)
4733
4734   // [back pointer]: points back to the parent map from which a transition
4735   // leads to this map. The field overlaps with prototype transitions and the
4736   // back pointer will be moved into the prototype transitions array if
4737   // required.
4738   inline Object* GetBackPointer();
4739   inline void SetBackPointer(Object* value,
4740                              WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4741
4742   // [prototype transitions]: cache of prototype transitions.
4743   // Prototype transition is a transition that happens
4744   // when we change object's prototype to a new one.
4745   // Cache format:
4746   //    0: finger - index of the first free cell in the cache
4747   //    1: back pointer that overlaps with prototype transitions field.
4748   //    2 + 2 * i: prototype
4749   //    3 + 2 * i: target map
4750   DECL_ACCESSORS(prototype_transitions, FixedArray)
4751
4752   inline void init_prototype_transitions(Object* undefined);
4753   inline HeapObject* unchecked_prototype_transitions();
4754
4755   static const int kProtoTransitionHeaderSize = 2;
4756   static const int kProtoTransitionNumberOfEntriesOffset = 0;
4757   static const int kProtoTransitionBackPointerOffset = 1;
4758   static const int kProtoTransitionElementsPerEntry = 2;
4759   static const int kProtoTransitionPrototypeOffset = 0;
4760   static const int kProtoTransitionMapOffset = 1;
4761
4762   inline int NumberOfProtoTransitions() {
4763     FixedArray* cache = prototype_transitions();
4764     if (cache->length() == 0) return 0;
4765     return
4766         Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
4767   }
4768
4769   inline void SetNumberOfProtoTransitions(int value) {
4770     FixedArray* cache = prototype_transitions();
4771     ASSERT(cache->length() != 0);
4772     cache->set_unchecked(kProtoTransitionNumberOfEntriesOffset,
4773                          Smi::FromInt(value));
4774   }
4775
4776   // Lookup in the map's instance descriptors and fill out the result
4777   // with the given holder if the name is found. The holder may be
4778   // NULL when this function is used from the compiler.
4779   void LookupInDescriptors(JSObject* holder,
4780                            String* name,
4781                            LookupResult* result);
4782
4783   MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
4784
4785   MUST_USE_RESULT MaybeObject* CopyNormalized(PropertyNormalizationMode mode,
4786                                               NormalizedMapSharingMode sharing);
4787
4788   // Returns a copy of the map, with all transitions dropped from the
4789   // instance descriptors.
4790   MUST_USE_RESULT MaybeObject* CopyDropTransitions();
4791
4792   // Returns the property index for name (only valid for FAST MODE).
4793   int PropertyIndexFor(String* name);
4794
4795   // Returns the next free property index (only valid for FAST MODE).
4796   int NextFreePropertyIndex();
4797
4798   // Returns the number of properties described in instance_descriptors
4799   // filtering out properties with the specified attributes.
4800   int NumberOfDescribedProperties(PropertyAttributes filter = NONE);
4801
4802   // Casting.
4803   static inline Map* cast(Object* obj);
4804
4805   // Locate an accessor in the instance descriptor.
4806   AccessorDescriptor* FindAccessor(String* name);
4807
4808   // Code cache operations.
4809
4810   // Clears the code cache.
4811   inline void ClearCodeCache(Heap* heap);
4812
4813   // Update code cache.
4814   static void UpdateCodeCache(Handle<Map> map,
4815                               Handle<String> name,
4816                               Handle<Code> code);
4817   MUST_USE_RESULT MaybeObject* UpdateCodeCache(String* name, Code* code);
4818
4819   // Returns the found code or undefined if absent.
4820   Object* FindInCodeCache(String* name, Code::Flags flags);
4821
4822   // Returns the non-negative index of the code object if it is in the
4823   // cache and -1 otherwise.
4824   int IndexInCodeCache(Object* name, Code* code);
4825
4826   // Removes a code object from the code cache at the given index.
4827   void RemoveFromCodeCache(String* name, Code* code, int index);
4828
4829   // Set all map transitions from this map to dead maps to null.  Also clear
4830   // back pointers in transition targets so that we do not process this map
4831   // again while following back pointers.
4832   void ClearNonLiveTransitions(Heap* heap);
4833
4834   // Computes a hash value for this map, to be used in HashTables and such.
4835   int Hash();
4836
4837   // Compares this map to another to see if they describe equivalent objects.
4838   // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
4839   // it had exactly zero inobject properties.
4840   // The "shared" flags of both this map and |other| are ignored.
4841   bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
4842
4843   // Returns the contents of this map's descriptor array for the given string.
4844   // May return NULL. |safe_to_add_transition| is set to false and NULL
4845   // is returned if adding transitions is not allowed.
4846   Object* GetDescriptorContents(String* sentinel_name,
4847                                 bool* safe_to_add_transitions);
4848
4849   // Returns the map that this map transitions to if its elements_kind
4850   // is changed to |elements_kind|, or NULL if no such map is cached yet.
4851   // |safe_to_add_transitions| is set to false if adding transitions is not
4852   // allowed.
4853   Map* LookupElementsTransitionMap(ElementsKind elements_kind,
4854                                    bool* safe_to_add_transition);
4855
4856   // Adds an entry to this map's descriptor array for a transition to
4857   // |transitioned_map| when its elements_kind is changed to |elements_kind|.
4858   MUST_USE_RESULT MaybeObject* AddElementsTransition(
4859       ElementsKind elements_kind, Map* transitioned_map);
4860
4861   // Returns the transitioned map for this map with the most generic
4862   // elements_kind that's found in |candidates|, or null handle if no match is
4863   // found at all.
4864   Handle<Map> FindTransitionedMap(MapHandleList* candidates);
4865   Map* FindTransitionedMap(MapList* candidates);
4866
4867   // Zaps the contents of backing data structures in debug mode. Note that the
4868   // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
4869   // holding weak references when incremental marking is used, because it also
4870   // iterates over objects that are otherwise unreachable.
4871 #ifdef DEBUG
4872   void ZapInstanceDescriptors();
4873   void ZapPrototypeTransitions();
4874 #endif
4875
4876   // Dispatched behavior.
4877 #ifdef OBJECT_PRINT
4878   inline void MapPrint() {
4879     MapPrint(stdout);
4880   }
4881   void MapPrint(FILE* out);
4882 #endif
4883 #ifdef DEBUG
4884   void MapVerify();
4885   void SharedMapVerify();
4886 #endif
4887
4888   inline int visitor_id();
4889   inline void set_visitor_id(int visitor_id);
4890
4891   typedef void (*TraverseCallback)(Map* map, void* data);
4892
4893   void TraverseTransitionTree(TraverseCallback callback, void* data);
4894
4895   static const int kMaxCachedPrototypeTransitions = 256;
4896
4897   Object* GetPrototypeTransition(Object* prototype);
4898
4899   MUST_USE_RESULT MaybeObject* PutPrototypeTransition(Object* prototype,
4900                                                       Map* map);
4901
4902   static const int kMaxPreAllocatedPropertyFields = 255;
4903
4904   // Layout description.
4905   static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
4906   static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
4907   static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
4908   static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
4909   // Storage for instance descriptors is overloaded to also contain additional
4910   // map flags when unused (bit_field3). When the map has instance descriptors,
4911   // the flags are transferred to the instance descriptor array and accessed
4912   // through an extra indirection.
4913   // TODO(1399): It should be possible to make room for bit_field3 in the map
4914   // without overloading the instance descriptors field, but the map is
4915   // currently perfectly aligned to 32 bytes and extending it at all would
4916   // double its size.  After the increment GC work lands, this size restriction
4917   // could be loosened and bit_field3 moved directly back in the map.
4918   static const int kInstanceDescriptorsOrBitField3Offset =
4919       kConstructorOffset + kPointerSize;
4920   static const int kCodeCacheOffset =
4921       kInstanceDescriptorsOrBitField3Offset + kPointerSize;
4922   static const int kPrototypeTransitionsOrBackPointerOffset =
4923       kCodeCacheOffset + kPointerSize;
4924   static const int kPadStart =
4925       kPrototypeTransitionsOrBackPointerOffset + kPointerSize;
4926   static const int kSize = MAP_POINTER_ALIGN(kPadStart);
4927
4928   // Layout of pointer fields. Heap iteration code relies on them
4929   // being continuously allocated.
4930   static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
4931   static const int kPointerFieldsEndOffset =
4932       kPrototypeTransitionsOrBackPointerOffset + kPointerSize;
4933
4934   // Byte offsets within kInstanceSizesOffset.
4935   static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
4936   static const int kInObjectPropertiesByte = 1;
4937   static const int kInObjectPropertiesOffset =
4938       kInstanceSizesOffset + kInObjectPropertiesByte;
4939   static const int kPreAllocatedPropertyFieldsByte = 2;
4940   static const int kPreAllocatedPropertyFieldsOffset =
4941       kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
4942   static const int kVisitorIdByte = 3;
4943   static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
4944
4945   // Byte offsets within kInstanceAttributesOffset attributes.
4946   static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
4947   static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
4948   static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
4949   static const int kBitField2Offset = kInstanceAttributesOffset + 3;
4950
4951   STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
4952
4953   // Bit positions for bit field.
4954   static const int kUnused = 0;  // To be used for marking recently used maps.
4955   static const int kHasNonInstancePrototype = 1;
4956   static const int kIsHiddenPrototype = 2;
4957   static const int kHasNamedInterceptor = 3;
4958   static const int kHasIndexedInterceptor = 4;
4959   static const int kIsUndetectable = 5;
4960   static const int kHasExternalResource = 6;
4961   static const int kIsAccessCheckNeeded = 7;
4962
4963   // Bit positions for bit field 2
4964   static const int kIsExtensible = 0;
4965   static const int kFunctionWithPrototype = 1;
4966   static const int kStringWrapperSafeForDefaultValueOf = 2;
4967   static const int kAttachedToSharedFunctionInfo = 3;
4968   // No bits can be used after kElementsKindFirstBit, they are all reserved for
4969   // storing ElementKind.
4970   static const int kElementsKindShift = 4;
4971   static const int kElementsKindBitCount = 4;
4972
4973   // Derived values from bit field 2
4974   static const int kElementsKindMask = (-1 << kElementsKindShift) &
4975       ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
4976   static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
4977       (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
4978   static const int8_t kMaximumBitField2FastSmiOnlyElementValue =
4979       static_cast<int8_t>((FAST_SMI_ONLY_ELEMENTS + 1) <<
4980                           Map::kElementsKindShift) - 1;
4981
4982   // Bit positions for bit field 3
4983   static const int kIsShared = 0;
4984   static const int kNamedInterceptorIsFallback = 1;
4985   static const int kHasInstanceCallHandler = 2;
4986
4987   // Layout of the default cache. It holds alternating name and code objects.
4988   static const int kCodeCacheEntrySize = 2;
4989   static const int kCodeCacheEntryNameOffset = 0;
4990   static const int kCodeCacheEntryCodeOffset = 1;
4991
4992   typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
4993                               kPointerFieldsEndOffset,
4994                               kSize> BodyDescriptor;
4995
4996  private:
4997   String* elements_transition_sentinel_name();
4998   DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
4999 };
5000
5001
5002 // An abstract superclass, a marker class really, for simple structure classes.
5003 // It doesn't carry much functionality but allows struct classes to be
5004 // identified in the type system.
5005 class Struct: public HeapObject {
5006  public:
5007   inline void InitializeBody(int object_size);
5008   static inline Struct* cast(Object* that);
5009 };
5010
5011
5012 // Script describes a script which has been added to the VM.
5013 class Script: public Struct {
5014  public:
5015   // Script types.
5016   enum Type {
5017     TYPE_NATIVE = 0,
5018     TYPE_EXTENSION = 1,
5019     TYPE_NORMAL = 2
5020   };
5021
5022   // Script compilation types.
5023   enum CompilationType {
5024     COMPILATION_TYPE_HOST = 0,
5025     COMPILATION_TYPE_EVAL = 1
5026   };
5027
5028   // Script compilation state.
5029   enum CompilationState {
5030     COMPILATION_STATE_INITIAL = 0,
5031     COMPILATION_STATE_COMPILED = 1
5032   };
5033
5034   // [source]: the script source.
5035   DECL_ACCESSORS(source, Object)
5036
5037   // [name]: the script name.
5038   DECL_ACCESSORS(name, Object)
5039
5040   // [id]: the script id.
5041   DECL_ACCESSORS(id, Object)
5042
5043   // [line_offset]: script line offset in resource from where it was extracted.
5044   DECL_ACCESSORS(line_offset, Smi)
5045
5046   // [column_offset]: script column offset in resource from where it was
5047   // extracted.
5048   DECL_ACCESSORS(column_offset, Smi)
5049
5050   // [data]: additional data associated with this script.
5051   DECL_ACCESSORS(data, Object)
5052
5053   // [context_data]: context data for the context this script was compiled in.
5054   DECL_ACCESSORS(context_data, Object)
5055
5056   // [wrapper]: the wrapper cache.
5057   DECL_ACCESSORS(wrapper, Foreign)
5058
5059   // [type]: the script type.
5060   DECL_ACCESSORS(type, Smi)
5061
5062   // [compilation]: how the the script was compiled.
5063   DECL_ACCESSORS(compilation_type, Smi)
5064
5065   // [is_compiled]: determines whether the script has already been compiled.
5066   DECL_ACCESSORS(compilation_state, Smi)
5067
5068   // [line_ends]: FixedArray of line ends positions.
5069   DECL_ACCESSORS(line_ends, Object)
5070
5071   // [eval_from_shared]: for eval scripts the shared funcion info for the
5072   // function from which eval was called.
5073   DECL_ACCESSORS(eval_from_shared, Object)
5074
5075   // [eval_from_instructions_offset]: the instruction offset in the code for the
5076   // function from which eval was called where eval was called.
5077   DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5078
5079   static inline Script* cast(Object* obj);
5080
5081   // If script source is an external string, check that the underlying
5082   // resource is accessible. Otherwise, always return true.
5083   inline bool HasValidSource();
5084
5085 #ifdef OBJECT_PRINT
5086   inline void ScriptPrint() {
5087     ScriptPrint(stdout);
5088   }
5089   void ScriptPrint(FILE* out);
5090 #endif
5091 #ifdef DEBUG
5092   void ScriptVerify();
5093 #endif
5094
5095   static const int kSourceOffset = HeapObject::kHeaderSize;
5096   static const int kNameOffset = kSourceOffset + kPointerSize;
5097   static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5098   static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5099   static const int kDataOffset = kColumnOffsetOffset + kPointerSize;
5100   static const int kContextOffset = kDataOffset + kPointerSize;
5101   static const int kWrapperOffset = kContextOffset + kPointerSize;
5102   static const int kTypeOffset = kWrapperOffset + kPointerSize;
5103   static const int kCompilationTypeOffset = kTypeOffset + kPointerSize;
5104   static const int kCompilationStateOffset =
5105       kCompilationTypeOffset + kPointerSize;
5106   static const int kLineEndsOffset = kCompilationStateOffset + kPointerSize;
5107   static const int kIdOffset = kLineEndsOffset + kPointerSize;
5108   static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5109   static const int kEvalFrominstructionsOffsetOffset =
5110       kEvalFromSharedOffset + kPointerSize;
5111   static const int kSize = kEvalFrominstructionsOffsetOffset + kPointerSize;
5112
5113  private:
5114   DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
5115 };
5116
5117
5118 // List of builtin functions we want to identify to improve code
5119 // generation.
5120 //
5121 // Each entry has a name of a global object property holding an object
5122 // optionally followed by ".prototype", a name of a builtin function
5123 // on the object (the one the id is set for), and a label.
5124 //
5125 // Installation of ids for the selected builtin functions is handled
5126 // by the bootstrapper.
5127 //
5128 // NOTE: Order is important: math functions should be at the end of
5129 // the list and MathFloor should be the first math function.
5130 #define FUNCTIONS_WITH_ID_LIST(V)                   \
5131   V(Array.prototype, push, ArrayPush)               \
5132   V(Array.prototype, pop, ArrayPop)                 \
5133   V(Function.prototype, apply, FunctionApply)       \
5134   V(String.prototype, charCodeAt, StringCharCodeAt) \
5135   V(String.prototype, charAt, StringCharAt)         \
5136   V(String, fromCharCode, StringFromCharCode)       \
5137   V(Math, floor, MathFloor)                         \
5138   V(Math, round, MathRound)                         \
5139   V(Math, ceil, MathCeil)                           \
5140   V(Math, abs, MathAbs)                             \
5141   V(Math, log, MathLog)                             \
5142   V(Math, sin, MathSin)                             \
5143   V(Math, cos, MathCos)                             \
5144   V(Math, tan, MathTan)                             \
5145   V(Math, asin, MathASin)                           \
5146   V(Math, acos, MathACos)                           \
5147   V(Math, atan, MathATan)                           \
5148   V(Math, exp, MathExp)                             \
5149   V(Math, sqrt, MathSqrt)                           \
5150   V(Math, pow, MathPow)                             \
5151   V(Math, random, MathRandom)                       \
5152   V(Math, max, MathMax)                             \
5153   V(Math, min, MathMin)
5154
5155
5156 enum BuiltinFunctionId {
5157 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name)    \
5158   k##name,
5159   FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
5160 #undef DECLARE_FUNCTION_ID
5161   // Fake id for a special case of Math.pow. Note, it continues the
5162   // list of math functions.
5163   kMathPowHalf,
5164   kFirstMathFunctionId = kMathFloor
5165 };
5166
5167
5168 // SharedFunctionInfo describes the JSFunction information that can be
5169 // shared by multiple instances of the function.
5170 class SharedFunctionInfo: public HeapObject {
5171  public:
5172   // [name]: Function name.
5173   DECL_ACCESSORS(name, Object)
5174
5175   // [code]: Function code.
5176   DECL_ACCESSORS(code, Code)
5177
5178   // [scope_info]: Scope info.
5179   DECL_ACCESSORS(scope_info, ScopeInfo)
5180
5181   // [construct stub]: Code stub for constructing instances of this function.
5182   DECL_ACCESSORS(construct_stub, Code)
5183
5184   inline Code* unchecked_code();
5185
5186   // Returns if this function has been compiled to native code yet.
5187   inline bool is_compiled();
5188
5189   // [length]: The function length - usually the number of declared parameters.
5190   // Use up to 2^30 parameters.
5191   inline int length();
5192   inline void set_length(int value);
5193
5194   // [formal parameter count]: The declared number of parameters.
5195   inline int formal_parameter_count();
5196   inline void set_formal_parameter_count(int value);
5197
5198   // Set the formal parameter count so the function code will be
5199   // called without using argument adaptor frames.
5200   inline void DontAdaptArguments();
5201
5202   // [expected_nof_properties]: Expected number of properties for the function.
5203   inline int expected_nof_properties();
5204   inline void set_expected_nof_properties(int value);
5205
5206   // Inobject slack tracking is the way to reclaim unused inobject space.
5207   //
5208   // The instance size is initially determined by adding some slack to
5209   // expected_nof_properties (to allow for a few extra properties added
5210   // after the constructor). There is no guarantee that the extra space
5211   // will not be wasted.
5212   //
5213   // Here is the algorithm to reclaim the unused inobject space:
5214   // - Detect the first constructor call for this SharedFunctionInfo.
5215   //   When it happens enter the "in progress" state: remember the
5216   //   constructor's initial_map and install a special construct stub that
5217   //   counts constructor calls.
5218   // - While the tracking is in progress create objects filled with
5219   //   one_pointer_filler_map instead of undefined_value. This way they can be
5220   //   resized quickly and safely.
5221   // - Once enough (kGenerousAllocationCount) objects have been created
5222   //   compute the 'slack' (traverse the map transition tree starting from the
5223   //   initial_map and find the lowest value of unused_property_fields).
5224   // - Traverse the transition tree again and decrease the instance size
5225   //   of every map. Existing objects will resize automatically (they are
5226   //   filled with one_pointer_filler_map). All further allocations will
5227   //   use the adjusted instance size.
5228   // - Decrease expected_nof_properties so that an allocations made from
5229   //   another context will use the adjusted instance size too.
5230   // - Exit "in progress" state by clearing the reference to the initial_map
5231   //   and setting the regular construct stub (generic or inline).
5232   //
5233   //  The above is the main event sequence. Some special cases are possible
5234   //  while the tracking is in progress:
5235   //
5236   // - GC occurs.
5237   //   Check if the initial_map is referenced by any live objects (except this
5238   //   SharedFunctionInfo). If it is, continue tracking as usual.
5239   //   If it is not, clear the reference and reset the tracking state. The
5240   //   tracking will be initiated again on the next constructor call.
5241   //
5242   // - The constructor is called from another context.
5243   //   Immediately complete the tracking, perform all the necessary changes
5244   //   to maps. This is  necessary because there is no efficient way to track
5245   //   multiple initial_maps.
5246   //   Proceed to create an object in the current context (with the adjusted
5247   //   size).
5248   //
5249   // - A different constructor function sharing the same SharedFunctionInfo is
5250   //   called in the same context. This could be another closure in the same
5251   //   context, or the first function could have been disposed.
5252   //   This is handled the same way as the previous case.
5253   //
5254   //  Important: inobject slack tracking is not attempted during the snapshot
5255   //  creation.
5256
5257   static const int kGenerousAllocationCount = 8;
5258
5259   // [construction_count]: Counter for constructor calls made during
5260   // the tracking phase.
5261   inline int construction_count();
5262   inline void set_construction_count(int value);
5263
5264   // [initial_map]: initial map of the first function called as a constructor.
5265   // Saved for the duration of the tracking phase.
5266   // This is a weak link (GC resets it to undefined_value if no other live
5267   // object reference this map).
5268   DECL_ACCESSORS(initial_map, Object)
5269
5270   // True if the initial_map is not undefined and the countdown stub is
5271   // installed.
5272   inline bool IsInobjectSlackTrackingInProgress();
5273
5274   // Starts the tracking.
5275   // Stores the initial map and installs the countdown stub.
5276   // IsInobjectSlackTrackingInProgress is normally true after this call,
5277   // except when tracking have not been started (e.g. the map has no unused
5278   // properties or the snapshot is being built).
5279   void StartInobjectSlackTracking(Map* map);
5280
5281   // Completes the tracking.
5282   // IsInobjectSlackTrackingInProgress is false after this call.
5283   void CompleteInobjectSlackTracking();
5284
5285   // Clears the initial_map before the GC marking phase to ensure the reference
5286   // is weak. IsInobjectSlackTrackingInProgress is false after this call.
5287   void DetachInitialMap();
5288
5289   // Restores the link to the initial map after the GC marking phase.
5290   // IsInobjectSlackTrackingInProgress is true after this call.
5291   void AttachInitialMap(Map* map);
5292
5293   // False if there are definitely no live objects created from this function.
5294   // True if live objects _may_ exist (existence not guaranteed).
5295   // May go back from true to false after GC.
5296   DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
5297
5298   // [instance class name]: class name for instances.
5299   DECL_ACCESSORS(instance_class_name, Object)
5300
5301   // [function data]: This field holds some additional data for function.
5302   // Currently it either has FunctionTemplateInfo to make benefit the API
5303   // or Smi identifying a builtin function.
5304   // In the long run we don't want all functions to have this field but
5305   // we can fix that when we have a better model for storing hidden data
5306   // on objects.
5307   DECL_ACCESSORS(function_data, Object)
5308
5309   inline bool IsApiFunction();
5310   inline FunctionTemplateInfo* get_api_func_data();
5311   inline bool HasBuiltinFunctionId();
5312   inline BuiltinFunctionId builtin_function_id();
5313
5314   // [script info]: Script from which the function originates.
5315   DECL_ACCESSORS(script, Object)
5316
5317   // [num_literals]: Number of literals used by this function.
5318   inline int num_literals();
5319   inline void set_num_literals(int value);
5320
5321   // [start_position_and_type]: Field used to store both the source code
5322   // position, whether or not the function is a function expression,
5323   // and whether or not the function is a toplevel function. The two
5324   // least significants bit indicates whether the function is an
5325   // expression and the rest contains the source code position.
5326   inline int start_position_and_type();
5327   inline void set_start_position_and_type(int value);
5328
5329   // [debug info]: Debug information.
5330   DECL_ACCESSORS(debug_info, Object)
5331
5332   // [inferred name]: Name inferred from variable or property
5333   // assignment of this function. Used to facilitate debugging and
5334   // profiling of JavaScript code written in OO style, where almost
5335   // all functions are anonymous but are assigned to object
5336   // properties.
5337   DECL_ACCESSORS(inferred_name, String)
5338
5339   // The function's name if it is non-empty, otherwise the inferred name.
5340   String* DebugName();
5341
5342   // Position of the 'function' token in the script source.
5343   inline int function_token_position();
5344   inline void set_function_token_position(int function_token_position);
5345
5346   // Position of this function in the script source.
5347   inline int start_position();
5348   inline void set_start_position(int start_position);
5349
5350   // End position of this function in the script source.
5351   inline int end_position();
5352   inline void set_end_position(int end_position);
5353
5354   // Is this function a function expression in the source code.
5355   DECL_BOOLEAN_ACCESSORS(is_expression)
5356
5357   // Is this function a top-level function (scripts, evals).
5358   DECL_BOOLEAN_ACCESSORS(is_toplevel)
5359
5360   // Bit field containing various information collected by the compiler to
5361   // drive optimization.
5362   inline int compiler_hints();
5363   inline void set_compiler_hints(int value);
5364
5365   inline int ast_node_count();
5366   inline void set_ast_node_count(int count);
5367
5368   // A counter used to determine when to stress the deoptimizer with a
5369   // deopt.
5370   inline int deopt_counter();
5371   inline void set_deopt_counter(int counter);
5372
5373   inline int profiler_ticks();
5374
5375   // Inline cache age is used to infer whether the function survived a context
5376   // disposal or not. In the former case we reset the opt_count.
5377   inline int ic_age();
5378   inline void set_ic_age(int age);
5379
5380   // Add information on assignments of the form this.x = ...;
5381   void SetThisPropertyAssignmentsInfo(
5382       bool has_only_simple_this_property_assignments,
5383       FixedArray* this_property_assignments);
5384
5385   // Clear information on assignments of the form this.x = ...;
5386   void ClearThisPropertyAssignmentsInfo();
5387
5388   // Indicate that this function only consists of assignments of the form
5389   // this.x = y; where y is either a constant or refers to an argument.
5390   inline bool has_only_simple_this_property_assignments();
5391
5392   // Indicates if this function can be lazy compiled.
5393   // This is used to determine if we can safely flush code from a function
5394   // when doing GC if we expect that the function will no longer be used.
5395   DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
5396
5397   // Indicates how many full GCs this function has survived with assigned
5398   // code object. Used to determine when it is relatively safe to flush
5399   // this code object and replace it with lazy compilation stub.
5400   // Age is reset when GC notices that the code object is referenced
5401   // from the stack or compilation cache.
5402   inline int code_age();
5403   inline void set_code_age(int age);
5404
5405   // Indicates whether optimizations have been disabled for this
5406   // shared function info. If a function is repeatedly optimized or if
5407   // we cannot optimize the function we disable optimization to avoid
5408   // spending time attempting to optimize it again.
5409   DECL_BOOLEAN_ACCESSORS(optimization_disabled)
5410
5411   // Indicates the language mode of the function's code as defined by the
5412   // current harmony drafts for the next ES language standard. Possible
5413   // values are:
5414   // 1. CLASSIC_MODE - Unrestricted syntax and semantics, same as in ES5.
5415   // 2. STRICT_MODE - Restricted syntax and semantics, same as in ES5.
5416   // 3. EXTENDED_MODE - Only available under the harmony flag, not part of ES5.
5417   inline LanguageMode language_mode();
5418   inline void set_language_mode(LanguageMode language_mode);
5419
5420   // Indicates whether the language mode of this function is CLASSIC_MODE.
5421   inline bool is_classic_mode();
5422
5423   // Indicates whether the language mode of this function is EXTENDED_MODE.
5424   inline bool is_extended_mode();
5425
5426   // False if the function definitely does not allocate an arguments object.
5427   DECL_BOOLEAN_ACCESSORS(uses_arguments)
5428
5429   // True if the function has any duplicated parameter names.
5430   DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
5431
5432   // Indicates whether the function is a native function.
5433   // These needs special treatment in .call and .apply since
5434   // null passed as the receiver should not be translated to the
5435   // global object.
5436   DECL_BOOLEAN_ACCESSORS(native)
5437
5438   // Indicates that the function was created by the Function function.
5439   // Though it's anonymous, toString should treat it as if it had the name
5440   // "anonymous".  We don't set the name itself so that the system does not
5441   // see a binding for it.
5442   DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
5443
5444   // Indicates whether the function is a bound function created using
5445   // the bind function.
5446   DECL_BOOLEAN_ACCESSORS(bound)
5447
5448   // Indicates that the function is anonymous (the name field can be set
5449   // through the API, which does not change this flag).
5450   DECL_BOOLEAN_ACCESSORS(is_anonymous)
5451
5452   // Is this a function or top-level/eval code.
5453   DECL_BOOLEAN_ACCESSORS(is_function)
5454
5455   // Indicates that the function cannot be optimized.
5456   DECL_BOOLEAN_ACCESSORS(dont_optimize)
5457
5458   // Indicates that the function cannot be inlined.
5459   DECL_BOOLEAN_ACCESSORS(dont_inline)
5460
5461   // Indicates whether or not the code in the shared function support
5462   // deoptimization.
5463   inline bool has_deoptimization_support();
5464
5465   // Enable deoptimization support through recompiled code.
5466   void EnableDeoptimizationSupport(Code* recompiled);
5467
5468   // Disable (further) attempted optimization of all functions sharing this
5469   // shared function info.
5470   void DisableOptimization();
5471
5472   // Lookup the bailout ID and ASSERT that it exists in the non-optimized
5473   // code, returns whether it asserted (i.e., always true if assertions are
5474   // disabled).
5475   bool VerifyBailoutId(int id);
5476
5477   // Check whether a inlined constructor can be generated with the given
5478   // prototype.
5479   bool CanGenerateInlineConstructor(Object* prototype);
5480
5481   // Prevents further attempts to generate inline constructors.
5482   // To be called if generation failed for any reason.
5483   void ForbidInlineConstructor();
5484
5485   // For functions which only contains this property assignments this provides
5486   // access to the names for the properties assigned.
5487   DECL_ACCESSORS(this_property_assignments, Object)
5488   inline int this_property_assignments_count();
5489   inline void set_this_property_assignments_count(int value);
5490   String* GetThisPropertyAssignmentName(int index);
5491   bool IsThisPropertyAssignmentArgument(int index);
5492   int GetThisPropertyAssignmentArgument(int index);
5493   Object* GetThisPropertyAssignmentConstant(int index);
5494
5495   // [source code]: Source code for the function.
5496   bool HasSourceCode();
5497   Handle<Object> GetSourceCode();
5498
5499   inline int opt_count();
5500   inline void set_opt_count(int opt_count);
5501
5502   // Source size of this function.
5503   int SourceSize();
5504
5505   // Calculate the instance size.
5506   int CalculateInstanceSize();
5507
5508   // Calculate the number of in-object properties.
5509   int CalculateInObjectProperties();
5510
5511   // Dispatched behavior.
5512   // Set max_length to -1 for unlimited length.
5513   void SourceCodePrint(StringStream* accumulator, int max_length);
5514 #ifdef OBJECT_PRINT
5515   inline void SharedFunctionInfoPrint() {
5516     SharedFunctionInfoPrint(stdout);
5517   }
5518   void SharedFunctionInfoPrint(FILE* out);
5519 #endif
5520 #ifdef DEBUG
5521   void SharedFunctionInfoVerify();
5522 #endif
5523
5524   void ResetForNewContext(int new_ic_age);
5525
5526   // Helpers to compile the shared code.  Returns true on success, false on
5527   // failure (e.g., stack overflow during compilation).
5528   static bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
5529                              ClearExceptionFlag flag);
5530   static bool CompileLazy(Handle<SharedFunctionInfo> shared,
5531                           ClearExceptionFlag flag);
5532
5533   void SharedFunctionInfoIterateBody(ObjectVisitor* v);
5534
5535   // Casting.
5536   static inline SharedFunctionInfo* cast(Object* obj);
5537
5538   // Constants.
5539   static const int kDontAdaptArgumentsSentinel = -1;
5540
5541   // Layout description.
5542   // Pointer fields.
5543   static const int kNameOffset = HeapObject::kHeaderSize;
5544   static const int kCodeOffset = kNameOffset + kPointerSize;
5545   static const int kScopeInfoOffset = kCodeOffset + kPointerSize;
5546   static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
5547   static const int kInstanceClassNameOffset =
5548       kConstructStubOffset + kPointerSize;
5549   static const int kFunctionDataOffset =
5550       kInstanceClassNameOffset + kPointerSize;
5551   static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
5552   static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
5553   static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
5554   static const int kInitialMapOffset =
5555       kInferredNameOffset + kPointerSize;
5556   static const int kThisPropertyAssignmentsOffset =
5557       kInitialMapOffset + kPointerSize;
5558   // ic_age is a Smi field. It could be grouped with another Smi field into a
5559   // PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
5560   static const int kICAgeOffset = kThisPropertyAssignmentsOffset + kPointerSize;
5561 #if V8_HOST_ARCH_32_BIT
5562   // Smi fields.
5563   static const int kLengthOffset =
5564       kICAgeOffset + kPointerSize;
5565   static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
5566   static const int kExpectedNofPropertiesOffset =
5567       kFormalParameterCountOffset + kPointerSize;
5568   static const int kNumLiteralsOffset =
5569       kExpectedNofPropertiesOffset + kPointerSize;
5570   static const int kStartPositionAndTypeOffset =
5571       kNumLiteralsOffset + kPointerSize;
5572   static const int kEndPositionOffset =
5573       kStartPositionAndTypeOffset + kPointerSize;
5574   static const int kFunctionTokenPositionOffset =
5575       kEndPositionOffset + kPointerSize;
5576   static const int kCompilerHintsOffset =
5577       kFunctionTokenPositionOffset + kPointerSize;
5578   static const int kThisPropertyAssignmentsCountOffset =
5579       kCompilerHintsOffset + kPointerSize;
5580   static const int kOptCountOffset =
5581       kThisPropertyAssignmentsCountOffset + kPointerSize;
5582   static const int kAstNodeCountOffset = kOptCountOffset + kPointerSize;
5583   static const int kDeoptCounterOffset = kAstNodeCountOffset + kPointerSize;
5584
5585
5586   // Total size.
5587   static const int kSize = kDeoptCounterOffset + kPointerSize;
5588 #else
5589   // The only reason to use smi fields instead of int fields
5590   // is to allow iteration without maps decoding during
5591   // garbage collections.
5592   // To avoid wasting space on 64-bit architectures we use
5593   // the following trick: we group integer fields into pairs
5594   // First integer in each pair is shifted left by 1.
5595   // By doing this we guarantee that LSB of each kPointerSize aligned
5596   // word is not set and thus this word cannot be treated as pointer
5597   // to HeapObject during old space traversal.
5598   static const int kLengthOffset =
5599       kICAgeOffset + kPointerSize;
5600   static const int kFormalParameterCountOffset =
5601       kLengthOffset + kIntSize;
5602
5603   static const int kExpectedNofPropertiesOffset =
5604       kFormalParameterCountOffset + kIntSize;
5605   static const int kNumLiteralsOffset =
5606       kExpectedNofPropertiesOffset + kIntSize;
5607
5608   static const int kEndPositionOffset =
5609       kNumLiteralsOffset + kIntSize;
5610   static const int kStartPositionAndTypeOffset =
5611       kEndPositionOffset + kIntSize;
5612
5613   static const int kFunctionTokenPositionOffset =
5614       kStartPositionAndTypeOffset + kIntSize;
5615   static const int kCompilerHintsOffset =
5616       kFunctionTokenPositionOffset + kIntSize;
5617
5618   static const int kThisPropertyAssignmentsCountOffset =
5619       kCompilerHintsOffset + kIntSize;
5620   static const int kOptCountOffset =
5621       kThisPropertyAssignmentsCountOffset + kIntSize;
5622
5623   static const int kAstNodeCountOffset = kOptCountOffset + kIntSize;
5624   static const int kDeoptCounterOffset = kAstNodeCountOffset + kIntSize;
5625
5626   // Total size.
5627   static const int kSize = kDeoptCounterOffset + kIntSize;
5628
5629 #endif
5630
5631   // The construction counter for inobject slack tracking is stored in the
5632   // most significant byte of compiler_hints which is otherwise unused.
5633   // Its offset depends on the endian-ness of the architecture.
5634 #if __BYTE_ORDER == __LITTLE_ENDIAN
5635   static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
5636 #elif __BYTE_ORDER == __BIG_ENDIAN
5637   static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
5638 #else
5639 #error Unknown byte ordering
5640 #endif
5641
5642   static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
5643
5644   typedef FixedBodyDescriptor<kNameOffset,
5645                               kThisPropertyAssignmentsOffset + kPointerSize,
5646                               kSize> BodyDescriptor;
5647
5648   // Bit positions in start_position_and_type.
5649   // The source code start position is in the 30 most significant bits of
5650   // the start_position_and_type field.
5651   static const int kIsExpressionBit = 0;
5652   static const int kIsTopLevelBit   = 1;
5653   static const int kStartPositionShift = 2;
5654   static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
5655
5656   // Bit positions in compiler_hints.
5657   static const int kCodeAgeSize = 3;
5658   static const int kCodeAgeMask = (1 << kCodeAgeSize) - 1;
5659
5660   enum CompilerHints {
5661     kHasOnlySimpleThisPropertyAssignments,
5662     kAllowLazyCompilation,
5663     kLiveObjectsMayExist,
5664     kCodeAgeShift,
5665     kOptimizationDisabled = kCodeAgeShift + kCodeAgeSize,
5666     kStrictModeFunction,
5667     kExtendedModeFunction,
5668     kUsesArguments,
5669     kHasDuplicateParameters,
5670     kNative,
5671     kBoundFunction,
5672     kIsAnonymous,
5673     kNameShouldPrintAsAnonymous,
5674     kIsFunction,
5675     kDontOptimize,
5676     kDontInline,
5677     kCompilerHintsCount  // Pseudo entry
5678   };
5679
5680  private:
5681 #if V8_HOST_ARCH_32_BIT
5682   // On 32 bit platforms, compiler hints is a smi.
5683   static const int kCompilerHintsSmiTagSize = kSmiTagSize;
5684   static const int kCompilerHintsSize = kPointerSize;
5685 #else
5686   // On 64 bit platforms, compiler hints is not a smi, see comment above.
5687   static const int kCompilerHintsSmiTagSize = 0;
5688   static const int kCompilerHintsSize = kIntSize;
5689 #endif
5690
5691   STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
5692                 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
5693
5694  public:
5695   // Constants for optimizing codegen for strict mode function and
5696   // native tests.
5697   // Allows to use byte-width instructions.
5698   static const int kStrictModeBitWithinByte =
5699       (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5700
5701   static const int kExtendedModeBitWithinByte =
5702       (kExtendedModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5703
5704   static const int kNativeBitWithinByte =
5705       (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
5706
5707 #if __BYTE_ORDER == __LITTLE_ENDIAN
5708   static const int kStrictModeByteOffset = kCompilerHintsOffset +
5709       (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5710   static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5711       (kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5712   static const int kNativeByteOffset = kCompilerHintsOffset +
5713       (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
5714 #elif __BYTE_ORDER == __BIG_ENDIAN
5715   static const int kStrictModeByteOffset = kCompilerHintsOffset +
5716       (kCompilerHintsSize - 1) -
5717       ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5718   static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5719       (kCompilerHintsSize - 1) -
5720       ((kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5721   static const int kNativeByteOffset = kCompilerHintsOffset +
5722       (kCompilerHintsSize - 1) -
5723       ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
5724 #else
5725 #error Unknown byte ordering
5726 #endif
5727
5728  private:
5729   DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
5730 };
5731
5732
5733 // Representation for module instance objects.
5734 class JSModule: public JSObject {
5735  public:
5736   // [context]: the context holding the module's locals, or undefined if none.
5737   DECL_ACCESSORS(context, Object)
5738
5739   // Casting.
5740   static inline JSModule* cast(Object* obj);
5741
5742   // Dispatched behavior.
5743 #ifdef OBJECT_PRINT
5744   inline void JSModulePrint() {
5745     JSModulePrint(stdout);
5746   }
5747   void JSModulePrint(FILE* out);
5748 #endif
5749 #ifdef DEBUG
5750   void JSModuleVerify();
5751 #endif
5752
5753   // Layout description.
5754   static const int kContextOffset = JSObject::kHeaderSize;
5755   static const int kSize = kContextOffset + kPointerSize;
5756
5757  private:
5758   DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
5759 };
5760
5761
5762 // JSFunction describes JavaScript functions.
5763 class JSFunction: public JSObject {
5764  public:
5765   // [prototype_or_initial_map]:
5766   DECL_ACCESSORS(prototype_or_initial_map, Object)
5767
5768   // [shared]: The information about the function that
5769   // can be shared by instances.
5770   DECL_ACCESSORS(shared, SharedFunctionInfo)
5771
5772   inline SharedFunctionInfo* unchecked_shared();
5773
5774   // [context]: The context for this function.
5775   inline Context* context();
5776   inline Object* unchecked_context();
5777   inline void set_context(Object* context);
5778
5779   // [code]: The generated code object for this function.  Executed
5780   // when the function is invoked, e.g. foo() or new foo(). See
5781   // [[Call]] and [[Construct]] description in ECMA-262, section
5782   // 8.6.2, page 27.
5783   inline Code* code();
5784   inline void set_code(Code* code);
5785   inline void ReplaceCode(Code* code);
5786
5787   inline Code* unchecked_code();
5788
5789   // Tells whether this function is builtin.
5790   inline bool IsBuiltin();
5791
5792   // Tells whether or not the function needs arguments adaption.
5793   inline bool NeedsArgumentsAdaption();
5794
5795   // Tells whether or not this function has been optimized.
5796   inline bool IsOptimized();
5797
5798   // Tells whether or not this function can be optimized.
5799   inline bool IsOptimizable();
5800
5801   // Mark this function for lazy recompilation. The function will be
5802   // recompiled the next time it is executed.
5803   void MarkForLazyRecompilation();
5804
5805   // Helpers to compile this function.  Returns true on success, false on
5806   // failure (e.g., stack overflow during compilation).
5807   static bool CompileLazy(Handle<JSFunction> function,
5808                           ClearExceptionFlag flag);
5809   static bool CompileOptimized(Handle<JSFunction> function,
5810                                int osr_ast_id,
5811                                ClearExceptionFlag flag);
5812
5813   // Tells whether or not the function is already marked for lazy
5814   // recompilation.
5815   inline bool IsMarkedForLazyRecompilation();
5816
5817   // Check whether or not this function is inlineable.
5818   bool IsInlineable();
5819
5820   // [literals_or_bindings]: Fixed array holding either
5821   // the materialized literals or the bindings of a bound function.
5822   //
5823   // If the function contains object, regexp or array literals, the
5824   // literals array prefix contains the object, regexp, and array
5825   // function to be used when creating these literals.  This is
5826   // necessary so that we do not dynamically lookup the object, regexp
5827   // or array functions.  Performing a dynamic lookup, we might end up
5828   // using the functions from a new context that we should not have
5829   // access to.
5830   //
5831   // On bound functions, the array is a (copy-on-write) fixed-array containing
5832   // the function that was bound, bound this-value and any bound
5833   // arguments. Bound functions never contain literals.
5834   DECL_ACCESSORS(literals_or_bindings, FixedArray)
5835
5836   inline FixedArray* literals();
5837   inline void set_literals(FixedArray* literals);
5838
5839   inline FixedArray* function_bindings();
5840   inline void set_function_bindings(FixedArray* bindings);
5841
5842   // The initial map for an object created by this constructor.
5843   inline Map* initial_map();
5844   inline void set_initial_map(Map* value);
5845   MUST_USE_RESULT inline MaybeObject* set_initial_map_and_cache_transitions(
5846       Map* value);
5847   inline bool has_initial_map();
5848
5849   // Get and set the prototype property on a JSFunction. If the
5850   // function has an initial map the prototype is set on the initial
5851   // map. Otherwise, the prototype is put in the initial map field
5852   // until an initial map is needed.
5853   inline bool has_prototype();
5854   inline bool has_instance_prototype();
5855   inline Object* prototype();
5856   inline Object* instance_prototype();
5857   MUST_USE_RESULT MaybeObject* SetInstancePrototype(Object* value);
5858   MUST_USE_RESULT MaybeObject* SetPrototype(Object* value);
5859
5860   // After prototype is removed, it will not be created when accessed, and
5861   // [[Construct]] from this function will not be allowed.
5862   Object* RemovePrototype();
5863   inline bool should_have_prototype();
5864
5865   // Accessor for this function's initial map's [[class]]
5866   // property. This is primarily used by ECMA native functions.  This
5867   // method sets the class_name field of this function's initial map
5868   // to a given value. It creates an initial map if this function does
5869   // not have one. Note that this method does not copy the initial map
5870   // if it has one already, but simply replaces it with the new value.
5871   // Instances created afterwards will have a map whose [[class]] is
5872   // set to 'value', but there is no guarantees on instances created
5873   // before.
5874   Object* SetInstanceClassName(String* name);
5875
5876   // Returns if this function has been compiled to native code yet.
5877   inline bool is_compiled();
5878
5879   // [next_function_link]: Field for linking functions. This list is treated as
5880   // a weak list by the GC.
5881   DECL_ACCESSORS(next_function_link, Object)
5882
5883   // Prints the name of the function using PrintF.
5884   inline void PrintName() {
5885     PrintName(stdout);
5886   }
5887   void PrintName(FILE* out);
5888
5889   // Casting.
5890   static inline JSFunction* cast(Object* obj);
5891
5892   // Iterates the objects, including code objects indirectly referenced
5893   // through pointers to the first instruction in the code object.
5894   void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
5895
5896   // Dispatched behavior.
5897 #ifdef OBJECT_PRINT
5898   inline void JSFunctionPrint() {
5899     JSFunctionPrint(stdout);
5900   }
5901   void JSFunctionPrint(FILE* out);
5902 #endif
5903 #ifdef DEBUG
5904   void JSFunctionVerify();
5905 #endif
5906
5907   // Returns the number of allocated literals.
5908   inline int NumberOfLiterals();
5909
5910   // Retrieve the global context from a function's literal array.
5911   static Context* GlobalContextFromLiterals(FixedArray* literals);
5912
5913   // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
5914   // kSize) is weak and has special handling during garbage collection.
5915   static const int kCodeEntryOffset = JSObject::kHeaderSize;
5916   static const int kPrototypeOrInitialMapOffset =
5917       kCodeEntryOffset + kPointerSize;
5918   static const int kSharedFunctionInfoOffset =
5919       kPrototypeOrInitialMapOffset + kPointerSize;
5920   static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
5921   static const int kLiteralsOffset = kContextOffset + kPointerSize;
5922   static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
5923   static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
5924   static const int kSize = kNextFunctionLinkOffset + kPointerSize;
5925
5926   // Layout of the literals array.
5927   static const int kLiteralsPrefixSize = 1;
5928   static const int kLiteralGlobalContextIndex = 0;
5929
5930   // Layout of the bound-function binding array.
5931   static const int kBoundFunctionIndex = 0;
5932   static const int kBoundThisIndex = 1;
5933   static const int kBoundArgumentsStartIndex = 2;
5934
5935  private:
5936   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
5937 };
5938
5939
5940 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
5941 // and the prototype is hidden. JSGlobalProxy always delegates
5942 // property accesses to its prototype if the prototype is not null.
5943 //
5944 // A JSGlobalProxy can be reinitialized which will preserve its identity.
5945 //
5946 // Accessing a JSGlobalProxy requires security check.
5947
5948 class JSGlobalProxy : public JSObject {
5949  public:
5950   // [context]: the owner global context of this global proxy object.
5951   // It is null value if this object is not used by any context.
5952   DECL_ACCESSORS(context, Object)
5953
5954   // Casting.
5955   static inline JSGlobalProxy* cast(Object* obj);
5956
5957   // Dispatched behavior.
5958 #ifdef OBJECT_PRINT
5959   inline void JSGlobalProxyPrint() {
5960     JSGlobalProxyPrint(stdout);
5961   }
5962   void JSGlobalProxyPrint(FILE* out);
5963 #endif
5964 #ifdef DEBUG
5965   void JSGlobalProxyVerify();
5966 #endif
5967
5968   // Layout description.
5969   static const int kContextOffset = JSObject::kHeaderSize;
5970   static const int kSize = kContextOffset + kPointerSize;
5971
5972  private:
5973   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
5974 };
5975
5976
5977 // Forward declaration.
5978 class JSBuiltinsObject;
5979
5980 // Common super class for JavaScript global objects and the special
5981 // builtins global objects.
5982 class GlobalObject: public JSObject {
5983  public:
5984   // [builtins]: the object holding the runtime routines written in JS.
5985   DECL_ACCESSORS(builtins, JSBuiltinsObject)
5986
5987   // [global context]: the global context corresponding to this global object.
5988   DECL_ACCESSORS(global_context, Context)
5989
5990   // [global receiver]: the global receiver object of the context
5991   DECL_ACCESSORS(global_receiver, JSObject)
5992
5993   // Retrieve the property cell used to store a property.
5994   JSGlobalPropertyCell* GetPropertyCell(LookupResult* result);
5995
5996   // This is like GetProperty, but is used when you know the lookup won't fail
5997   // by throwing an exception.  This is for the debug and builtins global
5998   // objects, where it is known which properties can be expected to be present
5999   // on the object.
6000   Object* GetPropertyNoExceptionThrown(String* key) {
6001     Object* answer = GetProperty(key)->ToObjectUnchecked();
6002     return answer;
6003   }
6004
6005   // Ensure that the global object has a cell for the given property name.
6006   static Handle<JSGlobalPropertyCell> EnsurePropertyCell(
6007       Handle<GlobalObject> global,
6008       Handle<String> name);
6009   // TODO(kmillikin): This function can be eliminated once the stub cache is
6010   // full handlified (and the static helper can be written directly).
6011   MUST_USE_RESULT MaybeObject* EnsurePropertyCell(String* name);
6012
6013   // Casting.
6014   static inline GlobalObject* cast(Object* obj);
6015
6016   // Layout description.
6017   static const int kBuiltinsOffset = JSObject::kHeaderSize;
6018   static const int kGlobalContextOffset = kBuiltinsOffset + kPointerSize;
6019   static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
6020   static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
6021
6022  private:
6023   DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
6024 };
6025
6026
6027 // JavaScript global object.
6028 class JSGlobalObject: public GlobalObject {
6029  public:
6030   // Casting.
6031   static inline JSGlobalObject* cast(Object* obj);
6032
6033   // Dispatched behavior.
6034 #ifdef OBJECT_PRINT
6035   inline void JSGlobalObjectPrint() {
6036     JSGlobalObjectPrint(stdout);
6037   }
6038   void JSGlobalObjectPrint(FILE* out);
6039 #endif
6040 #ifdef DEBUG
6041   void JSGlobalObjectVerify();
6042 #endif
6043
6044   // Layout description.
6045   static const int kSize = GlobalObject::kHeaderSize;
6046
6047  private:
6048   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
6049 };
6050
6051
6052 // Builtins global object which holds the runtime routines written in
6053 // JavaScript.
6054 class JSBuiltinsObject: public GlobalObject {
6055  public:
6056   // Accessors for the runtime routines written in JavaScript.
6057   inline Object* javascript_builtin(Builtins::JavaScript id);
6058   inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
6059
6060   // Accessors for code of the runtime routines written in JavaScript.
6061   inline Code* javascript_builtin_code(Builtins::JavaScript id);
6062   inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
6063
6064   // Casting.
6065   static inline JSBuiltinsObject* cast(Object* obj);
6066
6067   // Dispatched behavior.
6068 #ifdef OBJECT_PRINT
6069   inline void JSBuiltinsObjectPrint() {
6070     JSBuiltinsObjectPrint(stdout);
6071   }
6072   void JSBuiltinsObjectPrint(FILE* out);
6073 #endif
6074 #ifdef DEBUG
6075   void JSBuiltinsObjectVerify();
6076 #endif
6077
6078   // Layout description.  The size of the builtins object includes
6079   // room for two pointers per runtime routine written in javascript
6080   // (function and code object).
6081   static const int kJSBuiltinsCount = Builtins::id_count;
6082   static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
6083   static const int kJSBuiltinsCodeOffset =
6084       GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
6085   static const int kSize =
6086       kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
6087
6088   static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
6089     return kJSBuiltinsOffset + id * kPointerSize;
6090   }
6091
6092   static int OffsetOfCodeWithId(Builtins::JavaScript id) {
6093     return kJSBuiltinsCodeOffset + id * kPointerSize;
6094   }
6095
6096  private:
6097   DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
6098 };
6099
6100
6101 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
6102 class JSValue: public JSObject {
6103  public:
6104   // [value]: the object being wrapped.
6105   DECL_ACCESSORS(value, Object)
6106
6107   // Casting.
6108   static inline JSValue* cast(Object* obj);
6109
6110   // Dispatched behavior.
6111 #ifdef OBJECT_PRINT
6112   inline void JSValuePrint() {
6113     JSValuePrint(stdout);
6114   }
6115   void JSValuePrint(FILE* out);
6116 #endif
6117 #ifdef DEBUG
6118   void JSValueVerify();
6119 #endif
6120
6121   // Layout description.
6122   static const int kValueOffset = JSObject::kHeaderSize;
6123   static const int kSize = kValueOffset + kPointerSize;
6124
6125  private:
6126   DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
6127 };
6128
6129
6130 class DateCache;
6131
6132 // Representation for JS date objects.
6133 class JSDate: public JSObject {
6134  public:
6135   // If one component is NaN, all of them are, indicating a NaN time value.
6136   // [value]: the time value.
6137   DECL_ACCESSORS(value, Object)
6138   // [year]: caches year. Either undefined, smi, or NaN.
6139   DECL_ACCESSORS(year, Object)
6140   // [month]: caches month. Either undefined, smi, or NaN.
6141   DECL_ACCESSORS(month, Object)
6142   // [day]: caches day. Either undefined, smi, or NaN.
6143   DECL_ACCESSORS(day, Object)
6144   // [weekday]: caches day of week. Either undefined, smi, or NaN.
6145   DECL_ACCESSORS(weekday, Object)
6146   // [hour]: caches hours. Either undefined, smi, or NaN.
6147   DECL_ACCESSORS(hour, Object)
6148   // [min]: caches minutes. Either undefined, smi, or NaN.
6149   DECL_ACCESSORS(min, Object)
6150   // [sec]: caches seconds. Either undefined, smi, or NaN.
6151   DECL_ACCESSORS(sec, Object)
6152   // [cache stamp]: sample of the date cache stamp at the
6153   // moment when local fields were cached.
6154   DECL_ACCESSORS(cache_stamp, Object)
6155
6156   // Casting.
6157   static inline JSDate* cast(Object* obj);
6158
6159   // Returns the date field with the specified index.
6160   // See FieldIndex for the list of date fields.
6161   static Object* GetField(Object* date, Smi* index);
6162
6163   void SetValue(Object* value, bool is_value_nan);
6164
6165
6166   // Dispatched behavior.
6167 #ifdef OBJECT_PRINT
6168   inline void JSDatePrint() {
6169     JSDatePrint(stdout);
6170   }
6171   void JSDatePrint(FILE* out);
6172 #endif
6173 #ifdef DEBUG
6174   void JSDateVerify();
6175 #endif
6176   // The order is important. It must be kept in sync with date macros
6177   // in macros.py.
6178   enum FieldIndex {
6179     kDateValue,
6180     kYear,
6181     kMonth,
6182     kDay,
6183     kWeekday,
6184     kHour,
6185     kMinute,
6186     kSecond,
6187     kFirstUncachedField,
6188     kMillisecond = kFirstUncachedField,
6189     kDays,
6190     kTimeInDay,
6191     kFirstUTCField,
6192     kYearUTC = kFirstUTCField,
6193     kMonthUTC,
6194     kDayUTC,
6195     kWeekdayUTC,
6196     kHourUTC,
6197     kMinuteUTC,
6198     kSecondUTC,
6199     kMillisecondUTC,
6200     kDaysUTC,
6201     kTimeInDayUTC,
6202     kTimezoneOffset
6203   };
6204
6205   // Layout description.
6206   static const int kValueOffset = JSObject::kHeaderSize;
6207   static const int kYearOffset = kValueOffset + kPointerSize;
6208   static const int kMonthOffset = kYearOffset + kPointerSize;
6209   static const int kDayOffset = kMonthOffset + kPointerSize;
6210   static const int kWeekdayOffset = kDayOffset + kPointerSize;
6211   static const int kHourOffset = kWeekdayOffset  + kPointerSize;
6212   static const int kMinOffset = kHourOffset + kPointerSize;
6213   static const int kSecOffset = kMinOffset + kPointerSize;
6214   static const int kCacheStampOffset = kSecOffset + kPointerSize;
6215   static const int kSize = kCacheStampOffset + kPointerSize;
6216
6217  private:
6218   inline Object* DoGetField(FieldIndex index);
6219
6220   Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
6221
6222   // Computes and caches the cacheable fields of the date.
6223   inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
6224
6225
6226   DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
6227 };
6228
6229
6230 // Representation of message objects used for error reporting through
6231 // the API. The messages are formatted in JavaScript so this object is
6232 // a real JavaScript object. The information used for formatting the
6233 // error messages are not directly accessible from JavaScript to
6234 // prevent leaking information to user code called during error
6235 // formatting.
6236 class JSMessageObject: public JSObject {
6237  public:
6238   // [type]: the type of error message.
6239   DECL_ACCESSORS(type, String)
6240
6241   // [arguments]: the arguments for formatting the error message.
6242   DECL_ACCESSORS(arguments, JSArray)
6243
6244   // [script]: the script from which the error message originated.
6245   DECL_ACCESSORS(script, Object)
6246
6247   // [stack_trace]: the stack trace for this error message.
6248   DECL_ACCESSORS(stack_trace, Object)
6249
6250   // [stack_frames]: an array of stack frames for this error object.
6251   DECL_ACCESSORS(stack_frames, Object)
6252
6253   // [start_position]: the start position in the script for the error message.
6254   inline int start_position();
6255   inline void set_start_position(int value);
6256
6257   // [end_position]: the end position in the script for the error message.
6258   inline int end_position();
6259   inline void set_end_position(int value);
6260
6261   // Casting.
6262   static inline JSMessageObject* cast(Object* obj);
6263
6264   // Dispatched behavior.
6265 #ifdef OBJECT_PRINT
6266   inline void JSMessageObjectPrint() {
6267     JSMessageObjectPrint(stdout);
6268   }
6269   void JSMessageObjectPrint(FILE* out);
6270 #endif
6271 #ifdef DEBUG
6272   void JSMessageObjectVerify();
6273 #endif
6274
6275   // Layout description.
6276   static const int kTypeOffset = JSObject::kHeaderSize;
6277   static const int kArgumentsOffset = kTypeOffset + kPointerSize;
6278   static const int kScriptOffset = kArgumentsOffset + kPointerSize;
6279   static const int kStackTraceOffset = kScriptOffset + kPointerSize;
6280   static const int kStackFramesOffset = kStackTraceOffset + kPointerSize;
6281   static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
6282   static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
6283   static const int kSize = kEndPositionOffset + kPointerSize;
6284
6285   typedef FixedBodyDescriptor<HeapObject::kMapOffset,
6286                               kStackFramesOffset + kPointerSize,
6287                               kSize> BodyDescriptor;
6288 };
6289
6290
6291 // Regular expressions
6292 // The regular expression holds a single reference to a FixedArray in
6293 // the kDataOffset field.
6294 // The FixedArray contains the following data:
6295 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
6296 // - reference to the original source string
6297 // - reference to the original flag string
6298 // If it is an atom regexp
6299 // - a reference to a literal string to search for
6300 // If it is an irregexp regexp:
6301 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
6302 // used for tracking the last usage (used for code flushing).
6303 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
6304 // used for tracking the last usage (used for code flushing)..
6305 // - max number of registers used by irregexp implementations.
6306 // - number of capture registers (output values) of the regexp.
6307 class JSRegExp: public JSObject {
6308  public:
6309   // Meaning of Type:
6310   // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
6311   // ATOM: A simple string to match against using an indexOf operation.
6312   // IRREGEXP: Compiled with Irregexp.
6313   // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
6314   enum Type { NOT_COMPILED, ATOM, IRREGEXP };
6315   enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
6316
6317   class Flags {
6318    public:
6319     explicit Flags(uint32_t value) : value_(value) { }
6320     bool is_global() { return (value_ & GLOBAL) != 0; }
6321     bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
6322     bool is_multiline() { return (value_ & MULTILINE) != 0; }
6323     uint32_t value() { return value_; }
6324    private:
6325     uint32_t value_;
6326   };
6327
6328   DECL_ACCESSORS(data, Object)
6329
6330   inline Type TypeTag();
6331   inline int CaptureCount();
6332   inline Flags GetFlags();
6333   inline String* Pattern();
6334   inline Object* DataAt(int index);
6335   // Set implementation data after the object has been prepared.
6336   inline void SetDataAt(int index, Object* value);
6337
6338   // Used during GC when flushing code or setting age.
6339   inline Object* DataAtUnchecked(int index);
6340   inline void SetDataAtUnchecked(int index, Object* value, Heap* heap);
6341   inline Type TypeTagUnchecked();
6342
6343   static int code_index(bool is_ascii) {
6344     if (is_ascii) {
6345       return kIrregexpASCIICodeIndex;
6346     } else {
6347       return kIrregexpUC16CodeIndex;
6348     }
6349   }
6350
6351   static int saved_code_index(bool is_ascii) {
6352     if (is_ascii) {
6353       return kIrregexpASCIICodeSavedIndex;
6354     } else {
6355       return kIrregexpUC16CodeSavedIndex;
6356     }
6357   }
6358
6359   static inline JSRegExp* cast(Object* obj);
6360
6361   // Dispatched behavior.
6362 #ifdef DEBUG
6363   void JSRegExpVerify();
6364 #endif
6365
6366   static const int kDataOffset = JSObject::kHeaderSize;
6367   static const int kSize = kDataOffset + kPointerSize;
6368
6369   // Indices in the data array.
6370   static const int kTagIndex = 0;
6371   static const int kSourceIndex = kTagIndex + 1;
6372   static const int kFlagsIndex = kSourceIndex + 1;
6373   static const int kDataIndex = kFlagsIndex + 1;
6374   // The data fields are used in different ways depending on the
6375   // value of the tag.
6376   // Atom regexps (literal strings).
6377   static const int kAtomPatternIndex = kDataIndex;
6378
6379   static const int kAtomDataSize = kAtomPatternIndex + 1;
6380
6381   // Irregexp compiled code or bytecode for ASCII. If compilation
6382   // fails, this fields hold an exception object that should be
6383   // thrown if the regexp is used again.
6384   static const int kIrregexpASCIICodeIndex = kDataIndex;
6385   // Irregexp compiled code or bytecode for UC16.  If compilation
6386   // fails, this fields hold an exception object that should be
6387   // thrown if the regexp is used again.
6388   static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
6389
6390   // Saved instance of Irregexp compiled code or bytecode for ASCII that
6391   // is a potential candidate for flushing.
6392   static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
6393   // Saved instance of Irregexp compiled code or bytecode for UC16 that is
6394   // a potential candidate for flushing.
6395   static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
6396
6397   // Maximal number of registers used by either ASCII or UC16.
6398   // Only used to check that there is enough stack space
6399   static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
6400   // Number of captures in the compiled regexp.
6401   static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
6402
6403   static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
6404
6405   // Offsets directly into the data fixed array.
6406   static const int kDataTagOffset =
6407       FixedArray::kHeaderSize + kTagIndex * kPointerSize;
6408   static const int kDataAsciiCodeOffset =
6409       FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
6410   static const int kDataUC16CodeOffset =
6411       FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
6412   static const int kIrregexpCaptureCountOffset =
6413       FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
6414
6415   // In-object fields.
6416   static const int kSourceFieldIndex = 0;
6417   static const int kGlobalFieldIndex = 1;
6418   static const int kIgnoreCaseFieldIndex = 2;
6419   static const int kMultilineFieldIndex = 3;
6420   static const int kLastIndexFieldIndex = 4;
6421   static const int kInObjectFieldCount = 5;
6422
6423   // The uninitialized value for a regexp code object.
6424   static const int kUninitializedValue = -1;
6425
6426   // The compilation error value for the regexp code object. The real error
6427   // object is in the saved code field.
6428   static const int kCompilationErrorValue = -2;
6429
6430   // When we store the sweep generation at which we moved the code from the
6431   // code index to the saved code index we mask it of to be in the [0:255]
6432   // range.
6433   static const int kCodeAgeMask = 0xff;
6434 };
6435
6436
6437 class CompilationCacheShape : public BaseShape<HashTableKey*> {
6438  public:
6439   static inline bool IsMatch(HashTableKey* key, Object* value) {
6440     return key->IsMatch(value);
6441   }
6442
6443   static inline uint32_t Hash(HashTableKey* key) {
6444     return key->Hash();
6445   }
6446
6447   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6448     return key->HashForObject(object);
6449   }
6450
6451   MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6452     return key->AsObject();
6453   }
6454
6455   static const int kPrefixSize = 0;
6456   static const int kEntrySize = 2;
6457 };
6458
6459
6460 class CompilationCacheTable: public HashTable<CompilationCacheShape,
6461                                               HashTableKey*> {
6462  public:
6463   // Find cached value for a string key, otherwise return null.
6464   Object* Lookup(String* src);
6465   Object* LookupEval(String* src,
6466                      Context* context,
6467                      LanguageMode language_mode,
6468                      int scope_position);
6469   Object* LookupRegExp(String* source, JSRegExp::Flags flags);
6470   MUST_USE_RESULT MaybeObject* Put(String* src, Object* value);
6471   MUST_USE_RESULT MaybeObject* PutEval(String* src,
6472                                        Context* context,
6473                                        SharedFunctionInfo* value,
6474                                        int scope_position);
6475   MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
6476                                          JSRegExp::Flags flags,
6477                                          FixedArray* value);
6478
6479   // Remove given value from cache.
6480   void Remove(Object* value);
6481
6482   static inline CompilationCacheTable* cast(Object* obj);
6483
6484  private:
6485   DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
6486 };
6487
6488
6489 class CodeCache: public Struct {
6490  public:
6491   DECL_ACCESSORS(default_cache, FixedArray)
6492   DECL_ACCESSORS(normal_type_cache, Object)
6493
6494   // Add the code object to the cache.
6495   MUST_USE_RESULT MaybeObject* Update(String* name, Code* code);
6496
6497   // Lookup code object in the cache. Returns code object if found and undefined
6498   // if not.
6499   Object* Lookup(String* name, Code::Flags flags);
6500
6501   // Get the internal index of a code object in the cache. Returns -1 if the
6502   // code object is not in that cache. This index can be used to later call
6503   // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
6504   // RemoveByIndex.
6505   int GetIndex(Object* name, Code* code);
6506
6507   // Remove an object from the cache with the provided internal index.
6508   void RemoveByIndex(Object* name, Code* code, int index);
6509
6510   static inline CodeCache* cast(Object* obj);
6511
6512 #ifdef OBJECT_PRINT
6513   inline void CodeCachePrint() {
6514     CodeCachePrint(stdout);
6515   }
6516   void CodeCachePrint(FILE* out);
6517 #endif
6518 #ifdef DEBUG
6519   void CodeCacheVerify();
6520 #endif
6521
6522   static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
6523   static const int kNormalTypeCacheOffset =
6524       kDefaultCacheOffset + kPointerSize;
6525   static const int kSize = kNormalTypeCacheOffset + kPointerSize;
6526
6527  private:
6528   MUST_USE_RESULT MaybeObject* UpdateDefaultCache(String* name, Code* code);
6529   MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(String* name, Code* code);
6530   Object* LookupDefaultCache(String* name, Code::Flags flags);
6531   Object* LookupNormalTypeCache(String* name, Code::Flags flags);
6532
6533   // Code cache layout of the default cache. Elements are alternating name and
6534   // code objects for non normal load/store/call IC's.
6535   static const int kCodeCacheEntrySize = 2;
6536   static const int kCodeCacheEntryNameOffset = 0;
6537   static const int kCodeCacheEntryCodeOffset = 1;
6538
6539   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
6540 };
6541
6542
6543 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
6544  public:
6545   static inline bool IsMatch(HashTableKey* key, Object* value) {
6546     return key->IsMatch(value);
6547   }
6548
6549   static inline uint32_t Hash(HashTableKey* key) {
6550     return key->Hash();
6551   }
6552
6553   static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6554     return key->HashForObject(object);
6555   }
6556
6557   MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6558     return key->AsObject();
6559   }
6560
6561   static const int kPrefixSize = 0;
6562   static const int kEntrySize = 2;
6563 };
6564
6565
6566 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
6567                                            HashTableKey*> {
6568  public:
6569   Object* Lookup(String* name, Code::Flags flags);
6570   MUST_USE_RESULT MaybeObject* Put(String* name, Code* code);
6571
6572   int GetIndex(String* name, Code::Flags flags);
6573   void RemoveByIndex(int index);
6574
6575   static inline CodeCacheHashTable* cast(Object* obj);
6576
6577   // Initial size of the fixed array backing the hash table.
6578   static const int kInitialSize = 64;
6579
6580  private:
6581   DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
6582 };
6583
6584
6585 class PolymorphicCodeCache: public Struct {
6586  public:
6587   DECL_ACCESSORS(cache, Object)
6588
6589   static void Update(Handle<PolymorphicCodeCache> cache,
6590                      MapHandleList* maps,
6591                      Code::Flags flags,
6592                      Handle<Code> code);
6593
6594   MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
6595                                       Code::Flags flags,
6596                                       Code* code);
6597
6598   // Returns an undefined value if the entry is not found.
6599   Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
6600
6601   static inline PolymorphicCodeCache* cast(Object* obj);
6602
6603 #ifdef OBJECT_PRINT
6604   inline void PolymorphicCodeCachePrint() {
6605     PolymorphicCodeCachePrint(stdout);
6606   }
6607   void PolymorphicCodeCachePrint(FILE* out);
6608 #endif
6609 #ifdef DEBUG
6610   void PolymorphicCodeCacheVerify();
6611 #endif
6612
6613   static const int kCacheOffset = HeapObject::kHeaderSize;
6614   static const int kSize = kCacheOffset + kPointerSize;
6615
6616  private:
6617   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
6618 };
6619
6620
6621 class PolymorphicCodeCacheHashTable
6622     : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
6623  public:
6624   Object* Lookup(MapHandleList* maps, int code_kind);
6625
6626   MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
6627                                    int code_kind,
6628                                    Code* code);
6629
6630   static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
6631
6632   static const int kInitialSize = 64;
6633  private:
6634   DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
6635 };
6636
6637
6638 class TypeFeedbackInfo: public Struct {
6639  public:
6640   inline int ic_total_count();
6641   inline void set_ic_total_count(int count);
6642
6643   inline int ic_with_type_info_count();
6644   inline void set_ic_with_type_info_count(int count);
6645
6646   DECL_ACCESSORS(type_feedback_cells, TypeFeedbackCells)
6647
6648   static inline TypeFeedbackInfo* cast(Object* obj);
6649
6650 #ifdef OBJECT_PRINT
6651   inline void TypeFeedbackInfoPrint() {
6652     TypeFeedbackInfoPrint(stdout);
6653   }
6654   void TypeFeedbackInfoPrint(FILE* out);
6655 #endif
6656 #ifdef DEBUG
6657   void TypeFeedbackInfoVerify();
6658 #endif
6659
6660   static const int kIcTotalCountOffset = HeapObject::kHeaderSize;
6661   static const int kIcWithTypeinfoCountOffset =
6662       kIcTotalCountOffset + kPointerSize;
6663   static const int kTypeFeedbackCellsOffset =
6664       kIcWithTypeinfoCountOffset + kPointerSize;
6665   static const int kSize = kTypeFeedbackCellsOffset + kPointerSize;
6666
6667  private:
6668   DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
6669 };
6670
6671
6672 // Representation of a slow alias as part of a non-strict arguments objects.
6673 // For fast aliases (if HasNonStrictArgumentsElements()):
6674 // - the parameter map contains an index into the context
6675 // - all attributes of the element have default values
6676 // For slow aliases (if HasDictionaryArgumentsElements()):
6677 // - the parameter map contains no fast alias mapping (i.e. the hole)
6678 // - this struct (in the slow backing store) contains an index into the context
6679 // - all attributes are available as part if the property details
6680 class AliasedArgumentsEntry: public Struct {
6681  public:
6682   inline int aliased_context_slot();
6683   inline void set_aliased_context_slot(int count);
6684
6685   static inline AliasedArgumentsEntry* cast(Object* obj);
6686
6687 #ifdef OBJECT_PRINT
6688   inline void AliasedArgumentsEntryPrint() {
6689     AliasedArgumentsEntryPrint(stdout);
6690   }
6691   void AliasedArgumentsEntryPrint(FILE* out);
6692 #endif
6693 #ifdef DEBUG
6694   void AliasedArgumentsEntryVerify();
6695 #endif
6696
6697   static const int kAliasedContextSlot = HeapObject::kHeaderSize;
6698   static const int kSize = kAliasedContextSlot + kPointerSize;
6699
6700  private:
6701   DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
6702 };
6703
6704
6705 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
6706 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
6707
6708
6709 class StringHasher {
6710  public:
6711   explicit inline StringHasher(int length, uint32_t seed);
6712
6713   // Returns true if the hash of this string can be computed without
6714   // looking at the contents.
6715   inline bool has_trivial_hash();
6716
6717   // Add a character to the hash and update the array index calculation.
6718   inline void AddCharacter(uint32_t c);
6719
6720   // Adds a character to the hash but does not update the array index
6721   // calculation.  This can only be called when it has been verified
6722   // that the input is not an array index.
6723   inline void AddCharacterNoIndex(uint32_t c);
6724
6725   // Add a character above 0xffff as a surrogate pair.  These can get into
6726   // the hasher through the routines that take a UTF-8 string and make a symbol.
6727   void AddSurrogatePair(uc32 c);
6728   void AddSurrogatePairNoIndex(uc32 c);
6729
6730   // Returns the value to store in the hash field of a string with
6731   // the given length and contents.
6732   uint32_t GetHashField();
6733
6734   // Returns true if the characters seen so far make up a legal array
6735   // index.
6736   bool is_array_index() { return is_array_index_; }
6737
6738   bool is_valid() { return is_valid_; }
6739
6740   void invalidate() { is_valid_ = false; }
6741
6742   // Calculated hash value for a string consisting of 1 to
6743   // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
6744   // value is represented decimal value.
6745   static uint32_t MakeArrayIndexHash(uint32_t value, int length);
6746
6747   // No string is allowed to have a hash of zero.  That value is reserved
6748   // for internal properties.  If the hash calculation yields zero then we
6749   // use 27 instead.
6750   static const int kZeroHash = 27;
6751
6752  private:
6753   uint32_t array_index() {
6754     ASSERT(is_array_index());
6755     return array_index_;
6756   }
6757
6758   inline uint32_t GetHash();
6759
6760   int length_;
6761   uint32_t raw_running_hash_;
6762   uint32_t array_index_;
6763   bool is_array_index_;
6764   bool is_first_char_;
6765   bool is_valid_;
6766   friend class TwoCharHashTableKey;
6767 };
6768
6769
6770 // Calculates string hash.
6771 template <typename schar>
6772 inline uint32_t HashSequentialString(const schar* chars,
6773                                      int length,
6774                                      uint32_t seed);
6775
6776
6777 // The characteristics of a string are stored in its map.  Retrieving these
6778 // few bits of information is moderately expensive, involving two memory
6779 // loads where the second is dependent on the first.  To improve efficiency
6780 // the shape of the string is given its own class so that it can be retrieved
6781 // once and used for several string operations.  A StringShape is small enough
6782 // to be passed by value and is immutable, but be aware that flattening a
6783 // string can potentially alter its shape.  Also be aware that a GC caused by
6784 // something else can alter the shape of a string due to ConsString
6785 // shortcutting.  Keeping these restrictions in mind has proven to be error-
6786 // prone and so we no longer put StringShapes in variables unless there is a
6787 // concrete performance benefit at that particular point in the code.
6788 class StringShape BASE_EMBEDDED {
6789  public:
6790   inline explicit StringShape(String* s);
6791   inline explicit StringShape(Map* s);
6792   inline explicit StringShape(InstanceType t);
6793   inline bool IsSequential();
6794   inline bool IsExternal();
6795   inline bool IsCons();
6796   inline bool IsSliced();
6797   inline bool IsIndirect();
6798   inline bool IsExternalAscii();
6799   inline bool IsExternalTwoByte();
6800   inline bool IsSequentialAscii();
6801   inline bool IsSequentialTwoByte();
6802   inline bool IsSymbol();
6803   inline StringRepresentationTag representation_tag();
6804   inline uint32_t encoding_tag();
6805   inline uint32_t full_representation_tag();
6806   inline uint32_t size_tag();
6807 #ifdef DEBUG
6808   inline uint32_t type() { return type_; }
6809   inline void invalidate() { valid_ = false; }
6810   inline bool valid() { return valid_; }
6811 #else
6812   inline void invalidate() { }
6813 #endif
6814
6815  private:
6816   uint32_t type_;
6817 #ifdef DEBUG
6818   inline void set_valid() { valid_ = true; }
6819   bool valid_;
6820 #else
6821   inline void set_valid() { }
6822 #endif
6823 };
6824
6825
6826 // The String abstract class captures JavaScript string values:
6827 //
6828 // Ecma-262:
6829 //  4.3.16 String Value
6830 //    A string value is a member of the type String and is a finite
6831 //    ordered sequence of zero or more 16-bit unsigned integer values.
6832 //
6833 // All string values have a length field.
6834 class String: public HeapObject {
6835  public:
6836   // Representation of the flat content of a String.
6837   // A non-flat string doesn't have flat content.
6838   // A flat string has content that's encoded as a sequence of either
6839   // ASCII chars or two-byte UC16.
6840   // Returned by String::GetFlatContent().
6841   class FlatContent {
6842    public:
6843     // Returns true if the string is flat and this structure contains content.
6844     bool IsFlat() { return state_ != NON_FLAT; }
6845     // Returns true if the structure contains ASCII content.
6846     bool IsAscii() { return state_ == ASCII; }
6847     // Returns true if the structure contains two-byte content.
6848     bool IsTwoByte() { return state_ == TWO_BYTE; }
6849
6850     // Return the ASCII content of the string. Only use if IsAscii() returns
6851     // true.
6852     Vector<const char> ToAsciiVector() {
6853       ASSERT_EQ(ASCII, state_);
6854       return Vector<const char>::cast(buffer_);
6855     }
6856     // Return the two-byte content of the string. Only use if IsTwoByte()
6857     // returns true.
6858     Vector<const uc16> ToUC16Vector() {
6859       ASSERT_EQ(TWO_BYTE, state_);
6860       return Vector<const uc16>::cast(buffer_);
6861     }
6862
6863    private:
6864     enum State { NON_FLAT, ASCII, TWO_BYTE };
6865
6866     // Constructors only used by String::GetFlatContent().
6867     explicit FlatContent(Vector<const char> chars)
6868         : buffer_(Vector<const byte>::cast(chars)),
6869           state_(ASCII) { }
6870     explicit FlatContent(Vector<const uc16> chars)
6871         : buffer_(Vector<const byte>::cast(chars)),
6872           state_(TWO_BYTE) { }
6873     FlatContent() : buffer_(), state_(NON_FLAT) { }
6874
6875     Vector<const byte> buffer_;
6876     State state_;
6877
6878     friend class String;
6879   };
6880
6881   // Get and set the length of the string.
6882   inline int length();
6883   inline void set_length(int value);
6884
6885   // Get and set the hash field of the string.
6886   inline uint32_t hash_field();
6887   inline void set_hash_field(uint32_t value);
6888
6889   // Returns whether this string has only ASCII chars, i.e. all of them can
6890   // be ASCII encoded.  This might be the case even if the string is
6891   // two-byte.  Such strings may appear when the embedder prefers
6892   // two-byte external representations even for ASCII data.
6893   inline bool IsAsciiRepresentation();
6894   inline bool IsTwoByteRepresentation();
6895
6896   // Cons and slices have an encoding flag that may not represent the actual
6897   // encoding of the underlying string.  This is taken into account here.
6898   // Requires: this->IsFlat()
6899   inline bool IsAsciiRepresentationUnderneath();
6900   inline bool IsTwoByteRepresentationUnderneath();
6901
6902   // NOTE: this should be considered only a hint.  False negatives are
6903   // possible.
6904   inline bool HasOnlyAsciiChars();
6905
6906   // Get and set individual two byte chars in the string.
6907   inline void Set(int index, uint16_t value);
6908   // Get individual two byte char in the string.  Repeated calls
6909   // to this method are not efficient unless the string is flat.
6910   INLINE(uint16_t Get(int index));
6911
6912   // Try to flatten the string.  Checks first inline to see if it is
6913   // necessary.  Does nothing if the string is not a cons string.
6914   // Flattening allocates a sequential string with the same data as
6915   // the given string and mutates the cons string to a degenerate
6916   // form, where the first component is the new sequential string and
6917   // the second component is the empty string.  If allocation fails,
6918   // this function returns a failure.  If flattening succeeds, this
6919   // function returns the sequential string that is now the first
6920   // component of the cons string.
6921   //
6922   // Degenerate cons strings are handled specially by the garbage
6923   // collector (see IsShortcutCandidate).
6924   //
6925   // Use FlattenString from Handles.cc to flatten even in case an
6926   // allocation failure happens.
6927   inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
6928
6929   // Convenience function.  Has exactly the same behavior as
6930   // TryFlatten(), except in the case of failure returns the original
6931   // string.
6932   inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
6933
6934   // Tries to return the content of a flat string as a structure holding either
6935   // a flat vector of char or of uc16.
6936   // If the string isn't flat, and therefore doesn't have flat content, the
6937   // returned structure will report so, and can't provide a vector of either
6938   // kind.
6939   FlatContent GetFlatContent();
6940
6941   // Returns the parent of a sliced string or first part of a flat cons string.
6942   // Requires: StringShape(this).IsIndirect() && this->IsFlat()
6943   inline String* GetUnderlying();
6944
6945   // Mark the string as an undetectable object. It only applies to
6946   // ASCII and two byte string types.
6947   bool MarkAsUndetectable();
6948
6949   // Return a substring.
6950   MUST_USE_RESULT MaybeObject* SubString(int from,
6951                                          int to,
6952                                          PretenureFlag pretenure = NOT_TENURED);
6953
6954   // String equality operations.
6955   inline bool Equals(String* other);
6956   bool IsEqualTo(Vector<const char> str);
6957   bool IsAsciiEqualTo(Vector<const char> str);
6958   bool IsTwoByteEqualTo(Vector<const uc16> str);
6959
6960   bool SlowEqualsExternal(uc16 *string, int length);
6961   bool SlowEqualsExternal(char *string, int length);
6962
6963   // Return a UTF8 representation of the string.  The string is null
6964   // terminated but may optionally contain nulls.  Length is returned
6965   // in length_output if length_output is not a null pointer  The string
6966   // should be nearly flat, otherwise the performance of this method may
6967   // be very slow (quadratic in the length).  Setting robustness_flag to
6968   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
6969   // handles unexpected data without causing assert failures and it does not
6970   // do any heap allocations.  This is useful when printing stack traces.
6971   SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
6972                                     RobustnessFlag robustness_flag,
6973                                     int offset,
6974                                     int length,
6975                                     int* length_output = 0);
6976   SmartArrayPointer<char> ToCString(
6977       AllowNullsFlag allow_nulls = DISALLOW_NULLS,
6978       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
6979       int* length_output = 0);
6980
6981   // Return a 16 bit Unicode representation of the string.
6982   // The string should be nearly flat, otherwise the performance of
6983   // of this method may be very bad.  Setting robustness_flag to
6984   // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust  This means it
6985   // handles unexpected data without causing assert failures and it does not
6986   // do any heap allocations.  This is useful when printing stack traces.
6987   SmartArrayPointer<uc16> ToWideCString(
6988       RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
6989
6990   // Tells whether the hash code has been computed.
6991   inline bool HasHashCode();
6992
6993   // Returns a hash value used for the property table
6994   inline uint32_t Hash();
6995
6996   static uint32_t ComputeHashField(unibrow::CharacterStream* buffer,
6997                                    int length,
6998                                    uint32_t seed);
6999
7000   static bool ComputeArrayIndex(unibrow::CharacterStream* buffer,
7001                                 uint32_t* index,
7002                                 int length);
7003
7004   // Externalization.
7005   bool MakeExternal(v8::String::ExternalStringResource* resource);
7006   bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
7007
7008   // Conversion.
7009   inline bool AsArrayIndex(uint32_t* index);
7010
7011   // Casting.
7012   static inline String* cast(Object* obj);
7013
7014   void PrintOn(FILE* out);
7015
7016   // For use during stack traces.  Performs rudimentary sanity check.
7017   bool LooksValid();
7018
7019   // Dispatched behavior.
7020   void StringShortPrint(StringStream* accumulator);
7021 #ifdef OBJECT_PRINT
7022   inline void StringPrint() {
7023     StringPrint(stdout);
7024   }
7025   void StringPrint(FILE* out);
7026
7027   char* ToAsciiArray();
7028 #endif
7029 #ifdef DEBUG
7030   void StringVerify();
7031 #endif
7032   inline bool IsFlat();
7033
7034   // Layout description.
7035   static const int kLengthOffset = HeapObject::kHeaderSize;
7036   static const int kHashFieldOffset = kLengthOffset + kPointerSize;
7037   static const int kSize = kHashFieldOffset + kPointerSize;
7038
7039   // Maximum number of characters to consider when trying to convert a string
7040   // value into an array index.
7041   static const int kMaxArrayIndexSize = 10;
7042
7043   // Max ASCII char code.
7044   static const int kMaxAsciiCharCode = unibrow::Utf8::kMaxOneByteChar;
7045   static const unsigned kMaxAsciiCharCodeU = unibrow::Utf8::kMaxOneByteChar;
7046   static const int kMaxUtf16CodeUnit = 0xffff;
7047
7048   // Mask constant for checking if a string has a computed hash code
7049   // and if it is an array index.  The least significant bit indicates
7050   // whether a hash code has been computed.  If the hash code has been
7051   // computed the 2nd bit tells whether the string can be used as an
7052   // array index.
7053   static const int kHashNotComputedMask = 1;
7054   static const int kIsNotArrayIndexMask = 1 << 1;
7055   static const int kNofHashBitFields = 2;
7056
7057   // Shift constant retrieving hash code from hash field.
7058   static const int kHashShift = kNofHashBitFields;
7059
7060   // Only these bits are relevant in the hash, since the top two are shifted
7061   // out.
7062   static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
7063
7064   // Array index strings this short can keep their index in the hash
7065   // field.
7066   static const int kMaxCachedArrayIndexLength = 7;
7067
7068   // For strings which are array indexes the hash value has the string length
7069   // mixed into the hash, mainly to avoid a hash value of zero which would be
7070   // the case for the string '0'. 24 bits are used for the array index value.
7071   static const int kArrayIndexValueBits = 24;
7072   static const int kArrayIndexLengthBits =
7073       kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
7074
7075   STATIC_CHECK((kArrayIndexLengthBits > 0));
7076   STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
7077
7078   static const int kArrayIndexHashLengthShift =
7079       kArrayIndexValueBits + kNofHashBitFields;
7080
7081   static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
7082
7083   static const int kArrayIndexValueMask =
7084       ((1 << kArrayIndexValueBits) - 1) << kHashShift;
7085
7086   // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
7087   // could use a mask to test if the length of string is less than or equal to
7088   // kMaxCachedArrayIndexLength.
7089   STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
7090
7091   static const int kContainsCachedArrayIndexMask =
7092       (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
7093       kIsNotArrayIndexMask;
7094
7095   // Value of empty hash field indicating that the hash is not computed.
7096   static const int kEmptyHashField =
7097       kIsNotArrayIndexMask | kHashNotComputedMask;
7098
7099   // Value of hash field containing computed hash equal to zero.
7100   static const int kZeroHash = kIsNotArrayIndexMask;
7101
7102   // Maximal string length.
7103   static const int kMaxLength = (1 << (32 - 2)) - 1;
7104
7105   // Max length for computing hash. For strings longer than this limit the
7106   // string length is used as the hash value.
7107   static const int kMaxHashCalcLength = 16383;
7108
7109   // Limit for truncation in short printing.
7110   static const int kMaxShortPrintLength = 1024;
7111
7112   // Support for regular expressions.
7113   const uc16* GetTwoByteData();
7114   const uc16* GetTwoByteData(unsigned start);
7115
7116   // Support for StringInputBuffer
7117   static const unibrow::byte* ReadBlock(String* input,
7118                                         unibrow::byte* util_buffer,
7119                                         unsigned capacity,
7120                                         unsigned* remaining,
7121                                         unsigned* offset);
7122   static const unibrow::byte* ReadBlock(String** input,
7123                                         unibrow::byte* util_buffer,
7124                                         unsigned capacity,
7125                                         unsigned* remaining,
7126                                         unsigned* offset);
7127
7128   // Helper function for flattening strings.
7129   template <typename sinkchar>
7130   static void WriteToFlat(String* source,
7131                           sinkchar* sink,
7132                           int from,
7133                           int to);
7134
7135   static inline bool IsAscii(const char* chars, int length) {
7136     const char* limit = chars + length;
7137 #ifdef V8_HOST_CAN_READ_UNALIGNED
7138     ASSERT(kMaxAsciiCharCode == 0x7F);
7139     const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
7140     while (chars <= limit - sizeof(uintptr_t)) {
7141       if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
7142         return false;
7143       }
7144       chars += sizeof(uintptr_t);
7145     }
7146 #endif
7147     while (chars < limit) {
7148       if (static_cast<uint8_t>(*chars) > kMaxAsciiCharCodeU) return false;
7149       ++chars;
7150     }
7151     return true;
7152   }
7153
7154   static inline bool IsAscii(const uc16* chars, int length) {
7155     const uc16* limit = chars + length;
7156     while (chars < limit) {
7157       if (*chars > kMaxAsciiCharCodeU) return false;
7158       ++chars;
7159     }
7160     return true;
7161   }
7162
7163  protected:
7164   class ReadBlockBuffer {
7165    public:
7166     ReadBlockBuffer(unibrow::byte* util_buffer_,
7167                     unsigned cursor_,
7168                     unsigned capacity_,
7169                     unsigned remaining_) :
7170       util_buffer(util_buffer_),
7171       cursor(cursor_),
7172       capacity(capacity_),
7173       remaining(remaining_) {
7174     }
7175     unibrow::byte* util_buffer;
7176     unsigned       cursor;
7177     unsigned       capacity;
7178     unsigned       remaining;
7179   };
7180
7181   static inline const unibrow::byte* ReadBlock(String* input,
7182                                                ReadBlockBuffer* buffer,
7183                                                unsigned* offset,
7184                                                unsigned max_chars);
7185   static void ReadBlockIntoBuffer(String* input,
7186                                   ReadBlockBuffer* buffer,
7187                                   unsigned* offset_ptr,
7188                                   unsigned max_chars);
7189
7190  private:
7191   // Try to flatten the top level ConsString that is hiding behind this
7192   // string.  This is a no-op unless the string is a ConsString.  Flatten
7193   // mutates the ConsString and might return a failure.
7194   MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
7195
7196   static inline bool IsHashFieldComputed(uint32_t field);
7197
7198   // Slow case of String::Equals.  This implementation works on any strings
7199   // but it is most efficient on strings that are almost flat.
7200   bool SlowEquals(String* other);
7201
7202   // Slow case of AsArrayIndex.
7203   bool SlowAsArrayIndex(uint32_t* index);
7204
7205   // Compute and set the hash code.
7206   uint32_t ComputeAndSetHash();
7207
7208   DISALLOW_IMPLICIT_CONSTRUCTORS(String);
7209 };
7210
7211
7212 // The SeqString abstract class captures sequential string values.
7213 class SeqString: public String {
7214  public:
7215   // Casting.
7216   static inline SeqString* cast(Object* obj);
7217
7218   // Get and set the symbol id of the string
7219   inline int symbol_id();
7220   inline void set_symbol_id(int value);
7221
7222   // Layout description.
7223   static const int kSymbolIdOffset = String::kSize;
7224   static const int kHeaderSize = kSymbolIdOffset + kPointerSize;
7225
7226  private:
7227   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
7228 };
7229
7230
7231 // The AsciiString class captures sequential ASCII string objects.
7232 // Each character in the AsciiString is an ASCII character.
7233 class SeqAsciiString: public SeqString {
7234  public:
7235   static const bool kHasAsciiEncoding = true;
7236
7237   // Dispatched behavior.
7238   inline uint16_t SeqAsciiStringGet(int index);
7239   inline void SeqAsciiStringSet(int index, uint16_t value);
7240
7241   // Get the address of the characters in this string.
7242   inline Address GetCharsAddress();
7243
7244   inline char* GetChars();
7245
7246   // Casting
7247   static inline SeqAsciiString* cast(Object* obj);
7248
7249   // Garbage collection support.  This method is called by the
7250   // garbage collector to compute the actual size of an AsciiString
7251   // instance.
7252   inline int SeqAsciiStringSize(InstanceType instance_type);
7253
7254   // Computes the size for an AsciiString instance of a given length.
7255   static int SizeFor(int length) {
7256     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
7257   }
7258
7259   // Maximal memory usage for a single sequential ASCII string.
7260   static const int kMaxSize = 512 * MB - 1;
7261   // Maximal length of a single sequential ASCII string.
7262   // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7263   static const int kMaxLength = (kMaxSize - kHeaderSize);
7264
7265   // Support for StringInputBuffer.
7266   inline void SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7267                                                 unsigned* offset,
7268                                                 unsigned chars);
7269   inline const unibrow::byte* SeqAsciiStringReadBlock(unsigned* remaining,
7270                                                       unsigned* offset,
7271                                                       unsigned chars);
7272
7273  private:
7274   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqAsciiString);
7275 };
7276
7277
7278 // The TwoByteString class captures sequential unicode string objects.
7279 // Each character in the TwoByteString is a two-byte uint16_t.
7280 class SeqTwoByteString: public SeqString {
7281  public:
7282   static const bool kHasAsciiEncoding = false;
7283
7284   // Dispatched behavior.
7285   inline uint16_t SeqTwoByteStringGet(int index);
7286   inline void SeqTwoByteStringSet(int index, uint16_t value);
7287
7288   // Get the address of the characters in this string.
7289   inline Address GetCharsAddress();
7290
7291   inline uc16* GetChars();
7292
7293   // For regexp code.
7294   const uint16_t* SeqTwoByteStringGetData(unsigned start);
7295
7296   // Casting
7297   static inline SeqTwoByteString* cast(Object* obj);
7298
7299   // Garbage collection support.  This method is called by the
7300   // garbage collector to compute the actual size of a TwoByteString
7301   // instance.
7302   inline int SeqTwoByteStringSize(InstanceType instance_type);
7303
7304   // Computes the size for a TwoByteString instance of a given length.
7305   static int SizeFor(int length) {
7306     return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
7307   }
7308
7309   // Maximal memory usage for a single sequential two-byte string.
7310   static const int kMaxSize = 512 * MB - 1;
7311   // Maximal length of a single sequential two-byte string.
7312   // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7313   static const int kMaxLength = (kMaxSize - kHeaderSize) / sizeof(uint16_t);
7314
7315   // Support for StringInputBuffer.
7316   inline void SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7317                                                   unsigned* offset_ptr,
7318                                                   unsigned chars);
7319
7320  private:
7321   DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
7322 };
7323
7324
7325 // The ConsString class describes string values built by using the
7326 // addition operator on strings.  A ConsString is a pair where the
7327 // first and second components are pointers to other string values.
7328 // One or both components of a ConsString can be pointers to other
7329 // ConsStrings, creating a binary tree of ConsStrings where the leaves
7330 // are non-ConsString string values.  The string value represented by
7331 // a ConsString can be obtained by concatenating the leaf string
7332 // values in a left-to-right depth-first traversal of the tree.
7333 class ConsString: public String {
7334  public:
7335   // First string of the cons cell.
7336   inline String* first();
7337   // Doesn't check that the result is a string, even in debug mode.  This is
7338   // useful during GC where the mark bits confuse the checks.
7339   inline Object* unchecked_first();
7340   inline void set_first(String* first,
7341                         WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7342
7343   // Second string of the cons cell.
7344   inline String* second();
7345   // Doesn't check that the result is a string, even in debug mode.  This is
7346   // useful during GC where the mark bits confuse the checks.
7347   inline Object* unchecked_second();
7348   inline void set_second(String* second,
7349                          WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7350
7351   // Dispatched behavior.
7352   uint16_t ConsStringGet(int index);
7353
7354   // Casting.
7355   static inline ConsString* cast(Object* obj);
7356
7357   // Layout description.
7358   static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
7359   static const int kSecondOffset = kFirstOffset + kPointerSize;
7360   static const int kSize = kSecondOffset + kPointerSize;
7361
7362   // Support for StringInputBuffer.
7363   inline const unibrow::byte* ConsStringReadBlock(ReadBlockBuffer* buffer,
7364                                                   unsigned* offset_ptr,
7365                                                   unsigned chars);
7366   inline void ConsStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7367                                             unsigned* offset_ptr,
7368                                             unsigned chars);
7369
7370   // Minimum length for a cons string.
7371   static const int kMinLength = 13;
7372
7373   typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
7374           BodyDescriptor;
7375
7376 #ifdef DEBUG
7377   void ConsStringVerify();
7378 #endif
7379
7380  private:
7381   DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
7382 };
7383
7384
7385 // The Sliced String class describes strings that are substrings of another
7386 // sequential string.  The motivation is to save time and memory when creating
7387 // a substring.  A Sliced String is described as a pointer to the parent,
7388 // the offset from the start of the parent string and the length.  Using
7389 // a Sliced String therefore requires unpacking of the parent string and
7390 // adding the offset to the start address.  A substring of a Sliced String
7391 // are not nested since the double indirection is simplified when creating
7392 // such a substring.
7393 // Currently missing features are:
7394 //  - handling externalized parent strings
7395 //  - external strings as parent
7396 //  - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
7397 class SlicedString: public String {
7398  public:
7399   inline String* parent();
7400   inline void set_parent(String* parent);
7401   inline int offset();
7402   inline void set_offset(int offset);
7403
7404   // Dispatched behavior.
7405   uint16_t SlicedStringGet(int index);
7406
7407   // Casting.
7408   static inline SlicedString* cast(Object* obj);
7409
7410   // Layout description.
7411   static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
7412   static const int kOffsetOffset = kParentOffset + kPointerSize;
7413   static const int kSize = kOffsetOffset + kPointerSize;
7414
7415   // Support for StringInputBuffer
7416   inline const unibrow::byte* SlicedStringReadBlock(ReadBlockBuffer* buffer,
7417                                                     unsigned* offset_ptr,
7418                                                     unsigned chars);
7419   inline void SlicedStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7420                                               unsigned* offset_ptr,
7421                                               unsigned chars);
7422   // Minimum length for a sliced string.
7423   static const int kMinLength = 13;
7424
7425   typedef FixedBodyDescriptor<kParentOffset,
7426                               kOffsetOffset + kPointerSize, kSize>
7427           BodyDescriptor;
7428
7429 #ifdef DEBUG
7430   void SlicedStringVerify();
7431 #endif
7432
7433  private:
7434   DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
7435 };
7436
7437
7438 // The ExternalString class describes string values that are backed by
7439 // a string resource that lies outside the V8 heap.  ExternalStrings
7440 // consist of the length field common to all strings, a pointer to the
7441 // external resource.  It is important to ensure (externally) that the
7442 // resource is not deallocated while the ExternalString is live in the
7443 // V8 heap.
7444 //
7445 // The API expects that all ExternalStrings are created through the
7446 // API.  Therefore, ExternalStrings should not be used internally.
7447 class ExternalString: public String {
7448  public:
7449   // Casting
7450   static inline ExternalString* cast(Object* obj);
7451
7452   // Layout description.
7453   static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
7454   static const int kShortSize = kResourceOffset + kPointerSize;
7455   static const int kResourceDataOffset = kResourceOffset + kPointerSize;
7456   static const int kSize = kResourceDataOffset + kPointerSize;
7457
7458   // Return whether external string is short (data pointer is not cached).
7459   inline bool is_short();
7460
7461   STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
7462
7463  private:
7464   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
7465 };
7466
7467
7468 // The ExternalAsciiString class is an external string backed by an
7469 // ASCII string.
7470 class ExternalAsciiString: public ExternalString {
7471  public:
7472   static const bool kHasAsciiEncoding = true;
7473
7474   typedef v8::String::ExternalAsciiStringResource Resource;
7475
7476   // The underlying resource.
7477   inline const Resource* resource();
7478   inline void set_resource(const Resource* buffer);
7479
7480   // Update the pointer cache to the external character array.
7481   // The cached pointer is always valid, as the external character array does =
7482   // not move during lifetime.  Deserialization is the only exception, after
7483   // which the pointer cache has to be refreshed.
7484   inline void update_data_cache();
7485
7486   inline const char* GetChars();
7487
7488   // Dispatched behavior.
7489   inline uint16_t ExternalAsciiStringGet(int index);
7490
7491   // Casting.
7492   static inline ExternalAsciiString* cast(Object* obj);
7493
7494   // Garbage collection support.
7495   inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
7496
7497   template<typename StaticVisitor>
7498   inline void ExternalAsciiStringIterateBody();
7499
7500   // Support for StringInputBuffer.
7501   const unibrow::byte* ExternalAsciiStringReadBlock(unsigned* remaining,
7502                                                     unsigned* offset,
7503                                                     unsigned chars);
7504   inline void ExternalAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7505                                                      unsigned* offset,
7506                                                      unsigned chars);
7507
7508  private:
7509   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
7510 };
7511
7512
7513 // The ExternalTwoByteString class is an external string backed by a UTF-16
7514 // encoded string.
7515 class ExternalTwoByteString: public ExternalString {
7516  public:
7517   static const bool kHasAsciiEncoding = false;
7518
7519   typedef v8::String::ExternalStringResource Resource;
7520
7521   // The underlying string resource.
7522   inline const Resource* resource();
7523   inline void set_resource(const Resource* buffer);
7524
7525   // Update the pointer cache to the external character array.
7526   // The cached pointer is always valid, as the external character array does =
7527   // not move during lifetime.  Deserialization is the only exception, after
7528   // which the pointer cache has to be refreshed.
7529   inline void update_data_cache();
7530
7531   inline const uint16_t* GetChars();
7532
7533   // Dispatched behavior.
7534   inline uint16_t ExternalTwoByteStringGet(int index);
7535
7536   // For regexp code.
7537   inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
7538
7539   // Casting.
7540   static inline ExternalTwoByteString* cast(Object* obj);
7541
7542   // Garbage collection support.
7543   inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
7544
7545   template<typename StaticVisitor>
7546   inline void ExternalTwoByteStringIterateBody();
7547
7548
7549   // Support for StringInputBuffer.
7550   void ExternalTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7551                                                 unsigned* offset_ptr,
7552                                                 unsigned chars);
7553
7554  private:
7555   DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
7556 };
7557
7558
7559 // Utility superclass for stack-allocated objects that must be updated
7560 // on gc.  It provides two ways for the gc to update instances, either
7561 // iterating or updating after gc.
7562 class Relocatable BASE_EMBEDDED {
7563  public:
7564   explicit inline Relocatable(Isolate* isolate);
7565   inline virtual ~Relocatable();
7566   virtual void IterateInstance(ObjectVisitor* v) { }
7567   virtual void PostGarbageCollection() { }
7568
7569   static void PostGarbageCollectionProcessing();
7570   static int ArchiveSpacePerThread();
7571   static char* ArchiveState(Isolate* isolate, char* to);
7572   static char* RestoreState(Isolate* isolate, char* from);
7573   static void Iterate(ObjectVisitor* v);
7574   static void Iterate(ObjectVisitor* v, Relocatable* top);
7575   static char* Iterate(ObjectVisitor* v, char* t);
7576  private:
7577   Isolate* isolate_;
7578   Relocatable* prev_;
7579 };
7580
7581
7582 // A flat string reader provides random access to the contents of a
7583 // string independent of the character width of the string.  The handle
7584 // must be valid as long as the reader is being used.
7585 class FlatStringReader : public Relocatable {
7586  public:
7587   FlatStringReader(Isolate* isolate, Handle<String> str);
7588   FlatStringReader(Isolate* isolate, Vector<const char> input);
7589   void PostGarbageCollection();
7590   inline uc32 Get(int index);
7591   int length() { return length_; }
7592  private:
7593   String** str_;
7594   bool is_ascii_;
7595   int length_;
7596   const void* start_;
7597 };
7598
7599
7600 // Note that StringInputBuffers are not valid across a GC!  To fix this
7601 // it would have to store a String Handle instead of a String* and
7602 // AsciiStringReadBlock would have to be modified to use memcpy.
7603 //
7604 // StringInputBuffer is able to traverse any string regardless of how
7605 // deeply nested a sequence of ConsStrings it is made of.  However,
7606 // performance will be better if deep strings are flattened before they
7607 // are traversed.  Since flattening requires memory allocation this is
7608 // not always desirable, however (esp. in debugging situations).
7609 class StringInputBuffer: public unibrow::InputBuffer<String, String*, 1024> {
7610  public:
7611   virtual void Seek(unsigned pos);
7612   inline StringInputBuffer(): unibrow::InputBuffer<String, String*, 1024>() {}
7613   explicit inline StringInputBuffer(String* backing):
7614       unibrow::InputBuffer<String, String*, 1024>(backing) {}
7615 };
7616
7617
7618 class SafeStringInputBuffer
7619   : public unibrow::InputBuffer<String, String**, 256> {
7620  public:
7621   virtual void Seek(unsigned pos);
7622   inline SafeStringInputBuffer()
7623       : unibrow::InputBuffer<String, String**, 256>() {}
7624   explicit inline SafeStringInputBuffer(String** backing)
7625       : unibrow::InputBuffer<String, String**, 256>(backing) {}
7626 };
7627
7628
7629 template <typename T>
7630 class VectorIterator {
7631  public:
7632   VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
7633   explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
7634   T GetNext() { return data_[index_++]; }
7635   bool has_more() { return index_ < data_.length(); }
7636  private:
7637   Vector<const T> data_;
7638   int index_;
7639 };
7640
7641
7642 // The Oddball describes objects null, undefined, true, and false.
7643 class Oddball: public HeapObject {
7644  public:
7645   // [to_string]: Cached to_string computed at startup.
7646   DECL_ACCESSORS(to_string, String)
7647
7648   // [to_number]: Cached to_number computed at startup.
7649   DECL_ACCESSORS(to_number, Object)
7650
7651   inline byte kind();
7652   inline void set_kind(byte kind);
7653
7654   // Casting.
7655   static inline Oddball* cast(Object* obj);
7656
7657   // Dispatched behavior.
7658 #ifdef DEBUG
7659   void OddballVerify();
7660 #endif
7661
7662   // Initialize the fields.
7663   MUST_USE_RESULT MaybeObject* Initialize(const char* to_string,
7664                                           Object* to_number,
7665                                           byte kind);
7666
7667   // Layout description.
7668   static const int kToStringOffset = HeapObject::kHeaderSize;
7669   static const int kToNumberOffset = kToStringOffset + kPointerSize;
7670   static const int kKindOffset = kToNumberOffset + kPointerSize;
7671   static const int kSize = kKindOffset + kPointerSize;
7672
7673   static const byte kFalse = 0;
7674   static const byte kTrue = 1;
7675   static const byte kNotBooleanMask = ~1;
7676   static const byte kTheHole = 2;
7677   static const byte kNull = 3;
7678   static const byte kArgumentMarker = 4;
7679   static const byte kUndefined = 5;
7680   static const byte kOther = 6;
7681
7682   typedef FixedBodyDescriptor<kToStringOffset,
7683                               kToNumberOffset + kPointerSize,
7684                               kSize> BodyDescriptor;
7685
7686   STATIC_CHECK(kKindOffset == Internals::kOddballKindOffset);
7687   STATIC_CHECK(kNull == Internals::kNullOddballKind);
7688   STATIC_CHECK(kUndefined == Internals::kUndefinedOddballKind);
7689
7690  private:
7691   DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
7692 };
7693
7694
7695 class JSGlobalPropertyCell: public HeapObject {
7696  public:
7697   // [value]: value of the global property.
7698   DECL_ACCESSORS(value, Object)
7699
7700   // Casting.
7701   static inline JSGlobalPropertyCell* cast(Object* obj);
7702
7703 #ifdef DEBUG
7704   void JSGlobalPropertyCellVerify();
7705 #endif
7706 #ifdef OBJECT_PRINT
7707   inline void JSGlobalPropertyCellPrint() {
7708     JSGlobalPropertyCellPrint(stdout);
7709   }
7710   void JSGlobalPropertyCellPrint(FILE* out);
7711 #endif
7712
7713   // Layout description.
7714   static const int kValueOffset = HeapObject::kHeaderSize;
7715   static const int kSize = kValueOffset + kPointerSize;
7716
7717   typedef FixedBodyDescriptor<kValueOffset,
7718                               kValueOffset + kPointerSize,
7719                               kSize> BodyDescriptor;
7720
7721  private:
7722   DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalPropertyCell);
7723 };
7724
7725
7726 // The JSProxy describes EcmaScript Harmony proxies
7727 class JSProxy: public JSReceiver {
7728  public:
7729   // [handler]: The handler property.
7730   DECL_ACCESSORS(handler, Object)
7731
7732   // [hash]: The hash code property (undefined if not initialized yet).
7733   DECL_ACCESSORS(hash, Object)
7734
7735   // Casting.
7736   static inline JSProxy* cast(Object* obj);
7737
7738   bool HasPropertyWithHandler(String* name);
7739   bool HasElementWithHandler(uint32_t index);
7740
7741   MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
7742       Object* receiver,
7743       String* name);
7744   MUST_USE_RESULT MaybeObject* GetElementWithHandler(
7745       Object* receiver,
7746       uint32_t index);
7747
7748   MUST_USE_RESULT MaybeObject* SetPropertyWithHandler(
7749       String* name,
7750       Object* value,
7751       PropertyAttributes attributes,
7752       StrictModeFlag strict_mode);
7753   MUST_USE_RESULT MaybeObject* SetElementWithHandler(
7754       uint32_t index,
7755       Object* value,
7756       StrictModeFlag strict_mode);
7757
7758   // If the handler defines an accessor property, invoke its setter
7759   // (or throw if only a getter exists) and set *found to true. Otherwise false.
7760   MUST_USE_RESULT MaybeObject* SetPropertyWithHandlerIfDefiningSetter(
7761       String* name,
7762       Object* value,
7763       PropertyAttributes attributes,
7764       StrictModeFlag strict_mode,
7765       bool* found);
7766
7767   MUST_USE_RESULT MaybeObject* DeletePropertyWithHandler(
7768       String* name,
7769       DeleteMode mode);
7770   MUST_USE_RESULT MaybeObject* DeleteElementWithHandler(
7771       uint32_t index,
7772       DeleteMode mode);
7773
7774   MUST_USE_RESULT PropertyAttributes GetPropertyAttributeWithHandler(
7775       JSReceiver* receiver,
7776       String* name);
7777   MUST_USE_RESULT PropertyAttributes GetElementAttributeWithHandler(
7778       JSReceiver* receiver,
7779       uint32_t index);
7780
7781   MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
7782
7783   // Turn this into an (empty) JSObject.
7784   void Fix();
7785
7786   // Initializes the body after the handler slot.
7787   inline void InitializeBody(int object_size, Object* value);
7788
7789   // Invoke a trap by name. If the trap does not exist on this's handler,
7790   // but derived_trap is non-NULL, invoke that instead.  May cause GC.
7791   Handle<Object> CallTrap(const char* name,
7792                           Handle<Object> derived_trap,
7793                           int argc,
7794                           Handle<Object> args[]);
7795
7796   // Dispatched behavior.
7797 #ifdef OBJECT_PRINT
7798   inline void JSProxyPrint() {
7799     JSProxyPrint(stdout);
7800   }
7801   void JSProxyPrint(FILE* out);
7802 #endif
7803 #ifdef DEBUG
7804   void JSProxyVerify();
7805 #endif
7806
7807   // Layout description. We add padding so that a proxy has the same
7808   // size as a virgin JSObject. This is essential for becoming a JSObject
7809   // upon freeze.
7810   static const int kHandlerOffset = HeapObject::kHeaderSize;
7811   static const int kHashOffset = kHandlerOffset + kPointerSize;
7812   static const int kPaddingOffset = kHashOffset + kPointerSize;
7813   static const int kSize = JSObject::kHeaderSize;
7814   static const int kHeaderSize = kPaddingOffset;
7815   static const int kPaddingSize = kSize - kPaddingOffset;
7816
7817   STATIC_CHECK(kPaddingSize >= 0);
7818
7819   typedef FixedBodyDescriptor<kHandlerOffset,
7820                               kPaddingOffset,
7821                               kSize> BodyDescriptor;
7822
7823  private:
7824   DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
7825 };
7826
7827
7828 class JSFunctionProxy: public JSProxy {
7829  public:
7830   // [call_trap]: The call trap.
7831   DECL_ACCESSORS(call_trap, Object)
7832
7833   // [construct_trap]: The construct trap.
7834   DECL_ACCESSORS(construct_trap, Object)
7835
7836   // Casting.
7837   static inline JSFunctionProxy* cast(Object* obj);
7838
7839   // Dispatched behavior.
7840 #ifdef OBJECT_PRINT
7841   inline void JSFunctionProxyPrint() {
7842     JSFunctionProxyPrint(stdout);
7843   }
7844   void JSFunctionProxyPrint(FILE* out);
7845 #endif
7846 #ifdef DEBUG
7847   void JSFunctionProxyVerify();
7848 #endif
7849
7850   // Layout description.
7851   static const int kCallTrapOffset = JSProxy::kPaddingOffset;
7852   static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
7853   static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
7854   static const int kSize = JSFunction::kSize;
7855   static const int kPaddingSize = kSize - kPaddingOffset;
7856
7857   STATIC_CHECK(kPaddingSize >= 0);
7858
7859   typedef FixedBodyDescriptor<kHandlerOffset,
7860                               kConstructTrapOffset + kPointerSize,
7861                               kSize> BodyDescriptor;
7862
7863  private:
7864   DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
7865 };
7866
7867
7868 // The JSSet describes EcmaScript Harmony sets
7869 class JSSet: public JSObject {
7870  public:
7871   // [set]: the backing hash set containing keys.
7872   DECL_ACCESSORS(table, Object)
7873
7874   // Casting.
7875   static inline JSSet* cast(Object* obj);
7876
7877 #ifdef OBJECT_PRINT
7878   inline void JSSetPrint() {
7879     JSSetPrint(stdout);
7880   }
7881   void JSSetPrint(FILE* out);
7882 #endif
7883 #ifdef DEBUG
7884   void JSSetVerify();
7885 #endif
7886
7887   static const int kTableOffset = JSObject::kHeaderSize;
7888   static const int kSize = kTableOffset + kPointerSize;
7889
7890  private:
7891   DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
7892 };
7893
7894
7895 // The JSMap describes EcmaScript Harmony maps
7896 class JSMap: public JSObject {
7897  public:
7898   // [table]: the backing hash table mapping keys to values.
7899   DECL_ACCESSORS(table, Object)
7900
7901   // Casting.
7902   static inline JSMap* cast(Object* obj);
7903
7904 #ifdef OBJECT_PRINT
7905   inline void JSMapPrint() {
7906     JSMapPrint(stdout);
7907   }
7908   void JSMapPrint(FILE* out);
7909 #endif
7910 #ifdef DEBUG
7911   void JSMapVerify();
7912 #endif
7913
7914   static const int kTableOffset = JSObject::kHeaderSize;
7915   static const int kSize = kTableOffset + kPointerSize;
7916
7917  private:
7918   DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
7919 };
7920
7921
7922 // The JSWeakMap describes EcmaScript Harmony weak maps
7923 class JSWeakMap: public JSObject {
7924  public:
7925   // [table]: the backing hash table mapping keys to values.
7926   DECL_ACCESSORS(table, Object)
7927
7928   // [next]: linked list of encountered weak maps during GC.
7929   DECL_ACCESSORS(next, Object)
7930
7931   // Casting.
7932   static inline JSWeakMap* cast(Object* obj);
7933
7934 #ifdef OBJECT_PRINT
7935   inline void JSWeakMapPrint() {
7936     JSWeakMapPrint(stdout);
7937   }
7938   void JSWeakMapPrint(FILE* out);
7939 #endif
7940 #ifdef DEBUG
7941   void JSWeakMapVerify();
7942 #endif
7943
7944   static const int kTableOffset = JSObject::kHeaderSize;
7945   static const int kNextOffset = kTableOffset + kPointerSize;
7946   static const int kSize = kNextOffset + kPointerSize;
7947
7948  private:
7949   DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
7950 };
7951
7952
7953 // Foreign describes objects pointing from JavaScript to C structures.
7954 // Since they cannot contain references to JS HeapObjects they can be
7955 // placed in old_data_space.
7956 class Foreign: public HeapObject {
7957  public:
7958   // [address]: field containing the address.
7959   inline Address foreign_address();
7960   inline void set_foreign_address(Address value);
7961
7962   // Casting.
7963   static inline Foreign* cast(Object* obj);
7964
7965   // Dispatched behavior.
7966   inline void ForeignIterateBody(ObjectVisitor* v);
7967
7968   template<typename StaticVisitor>
7969   inline void ForeignIterateBody();
7970
7971 #ifdef OBJECT_PRINT
7972   inline void ForeignPrint() {
7973     ForeignPrint(stdout);
7974   }
7975   void ForeignPrint(FILE* out);
7976 #endif
7977 #ifdef DEBUG
7978   void ForeignVerify();
7979 #endif
7980
7981   // Layout description.
7982
7983   static const int kForeignAddressOffset = HeapObject::kHeaderSize;
7984   static const int kSize = kForeignAddressOffset + kPointerSize;
7985
7986   STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
7987
7988  private:
7989   DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
7990 };
7991
7992
7993 // The JSArray describes JavaScript Arrays
7994 //  Such an array can be in one of two modes:
7995 //    - fast, backing storage is a FixedArray and length <= elements.length();
7996 //       Please note: push and pop can be used to grow and shrink the array.
7997 //    - slow, backing storage is a HashTable with numbers as keys.
7998 class JSArray: public JSObject {
7999  public:
8000   // [length]: The length property.
8001   DECL_ACCESSORS(length, Object)
8002
8003   // Overload the length setter to skip write barrier when the length
8004   // is set to a smi. This matches the set function on FixedArray.
8005   inline void set_length(Smi* length);
8006
8007   MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
8008                                                             Object* value);
8009
8010   // Initialize the array with the given capacity. The function may
8011   // fail due to out-of-memory situations, but only if the requested
8012   // capacity is non-zero.
8013   MUST_USE_RESULT MaybeObject* Initialize(int capacity);
8014
8015   // Initializes the array to a certain length.
8016   inline bool AllowsSetElementsLength();
8017   MUST_USE_RESULT MaybeObject* SetElementsLength(Object* length);
8018
8019   // Set the content of the array to the content of storage.
8020   MUST_USE_RESULT inline MaybeObject* SetContent(FixedArrayBase* storage);
8021
8022   // Casting.
8023   static inline JSArray* cast(Object* obj);
8024
8025   // Uses handles.  Ensures that the fixed array backing the JSArray has at
8026   // least the stated size.
8027   inline void EnsureSize(int minimum_size_of_backing_fixed_array);
8028
8029   // Dispatched behavior.
8030 #ifdef OBJECT_PRINT
8031   inline void JSArrayPrint() {
8032     JSArrayPrint(stdout);
8033   }
8034   void JSArrayPrint(FILE* out);
8035 #endif
8036 #ifdef DEBUG
8037   void JSArrayVerify();
8038 #endif
8039
8040   // Number of element slots to pre-allocate for an empty array.
8041   static const int kPreallocatedArrayElements = 4;
8042
8043   // Layout description.
8044   static const int kLengthOffset = JSObject::kHeaderSize;
8045   static const int kSize = kLengthOffset + kPointerSize;
8046
8047  private:
8048   // Expand the fixed array backing of a fast-case JSArray to at least
8049   // the requested size.
8050   void Expand(int minimum_size_of_backing_fixed_array);
8051
8052   DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
8053 };
8054
8055
8056 // JSRegExpResult is just a JSArray with a specific initial map.
8057 // This initial map adds in-object properties for "index" and "input"
8058 // properties, as assigned by RegExp.prototype.exec, which allows
8059 // faster creation of RegExp exec results.
8060 // This class just holds constants used when creating the result.
8061 // After creation the result must be treated as a JSArray in all regards.
8062 class JSRegExpResult: public JSArray {
8063  public:
8064   // Offsets of object fields.
8065   static const int kIndexOffset = JSArray::kSize;
8066   static const int kInputOffset = kIndexOffset + kPointerSize;
8067   static const int kSize = kInputOffset + kPointerSize;
8068   // Indices of in-object properties.
8069   static const int kIndexIndex = 0;
8070   static const int kInputIndex = 1;
8071  private:
8072   DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
8073 };
8074
8075
8076 // An accessor must have a getter, but can have no setter.
8077 //
8078 // When setting a property, V8 searches accessors in prototypes.
8079 // If an accessor was found and it does not have a setter,
8080 // the request is ignored.
8081 //
8082 // If the accessor in the prototype has the READ_ONLY property attribute, then
8083 // a new value is added to the local object when the property is set.
8084 // This shadows the accessor in the prototype.
8085 class AccessorInfo: public Struct {
8086  public:
8087   DECL_ACCESSORS(getter, Object)
8088   DECL_ACCESSORS(setter, Object)
8089   DECL_ACCESSORS(data, Object)
8090   DECL_ACCESSORS(name, Object)
8091   DECL_ACCESSORS(flag, Smi)
8092
8093   inline bool all_can_read();
8094   inline void set_all_can_read(bool value);
8095
8096   inline bool all_can_write();
8097   inline void set_all_can_write(bool value);
8098
8099   inline bool prohibits_overwriting();
8100   inline void set_prohibits_overwriting(bool value);
8101
8102   inline PropertyAttributes property_attributes();
8103   inline void set_property_attributes(PropertyAttributes attributes);
8104
8105   static inline AccessorInfo* cast(Object* obj);
8106
8107 #ifdef OBJECT_PRINT
8108   inline void AccessorInfoPrint() {
8109     AccessorInfoPrint(stdout);
8110   }
8111   void AccessorInfoPrint(FILE* out);
8112 #endif
8113 #ifdef DEBUG
8114   void AccessorInfoVerify();
8115 #endif
8116
8117   static const int kGetterOffset = HeapObject::kHeaderSize;
8118   static const int kSetterOffset = kGetterOffset + kPointerSize;
8119   static const int kDataOffset = kSetterOffset + kPointerSize;
8120   static const int kNameOffset = kDataOffset + kPointerSize;
8121   static const int kFlagOffset = kNameOffset + kPointerSize;
8122   static const int kSize = kFlagOffset + kPointerSize;
8123
8124  private:
8125   // Bit positions in flag.
8126   static const int kAllCanReadBit = 0;
8127   static const int kAllCanWriteBit = 1;
8128   static const int kProhibitsOverwritingBit = 2;
8129   class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
8130
8131   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
8132 };
8133
8134
8135 // Support for JavaScript accessors: A pair of a getter and a setter. Each
8136 // accessor can either be
8137 //   * a pointer to a JavaScript function or proxy: a real accessor
8138 //   * undefined: considered an accessor by the spec, too, strangely enough
8139 //   * the hole: an accessor which has not been set
8140 //   * a pointer to a map: a transition used to ensure map sharing
8141 class AccessorPair: public Struct {
8142  public:
8143   DECL_ACCESSORS(getter, Object)
8144   DECL_ACCESSORS(setter, Object)
8145
8146   static inline AccessorPair* cast(Object* obj);
8147
8148   MUST_USE_RESULT MaybeObject* CopyWithoutTransitions();
8149
8150   // Note: Returns undefined instead in case of a hole.
8151   Object* GetComponent(AccessorComponent component);
8152
8153   // Set both components, skipping arguments which are a JavaScript null.
8154   void SetComponents(Object* getter, Object* setter) {
8155     if (!getter->IsNull()) set_getter(getter);
8156     if (!setter->IsNull()) set_setter(setter);
8157   }
8158
8159   bool ContainsAccessor() {
8160     return IsJSAccessor(getter()) || IsJSAccessor(setter());
8161   }
8162
8163 #ifdef OBJECT_PRINT
8164   void AccessorPairPrint(FILE* out = stdout);
8165 #endif
8166 #ifdef DEBUG
8167   void AccessorPairVerify();
8168 #endif
8169
8170   static const int kGetterOffset = HeapObject::kHeaderSize;
8171   static const int kSetterOffset = kGetterOffset + kPointerSize;
8172   static const int kSize = kSetterOffset + kPointerSize;
8173
8174  private:
8175   // Strangely enough, in addition to functions and harmony proxies, the spec
8176   // requires us to consider undefined as a kind of accessor, too:
8177   //    var obj = {};
8178   //    Object.defineProperty(obj, "foo", {get: undefined});
8179   //    assertTrue("foo" in obj);
8180   bool IsJSAccessor(Object* obj) {
8181     return obj->IsSpecFunction() || obj->IsUndefined();
8182   }
8183
8184   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
8185 };
8186
8187
8188 class AccessCheckInfo: public Struct {
8189  public:
8190   DECL_ACCESSORS(named_callback, Object)
8191   DECL_ACCESSORS(indexed_callback, Object)
8192   DECL_ACCESSORS(data, Object)
8193
8194   static inline AccessCheckInfo* cast(Object* obj);
8195
8196 #ifdef OBJECT_PRINT
8197   inline void AccessCheckInfoPrint() {
8198     AccessCheckInfoPrint(stdout);
8199   }
8200   void AccessCheckInfoPrint(FILE* out);
8201 #endif
8202 #ifdef DEBUG
8203   void AccessCheckInfoVerify();
8204 #endif
8205
8206   static const int kNamedCallbackOffset   = HeapObject::kHeaderSize;
8207   static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
8208   static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
8209   static const int kSize = kDataOffset + kPointerSize;
8210
8211  private:
8212   DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
8213 };
8214
8215
8216 class InterceptorInfo: public Struct {
8217  public:
8218   DECL_ACCESSORS(getter, Object)
8219   DECL_ACCESSORS(setter, Object)
8220   DECL_ACCESSORS(query, Object)
8221   DECL_ACCESSORS(deleter, Object)
8222   DECL_ACCESSORS(enumerator, Object)
8223   DECL_ACCESSORS(data, Object)
8224   DECL_ACCESSORS(is_fallback, Smi)
8225
8226   static inline InterceptorInfo* cast(Object* obj);
8227
8228 #ifdef OBJECT_PRINT
8229   inline void InterceptorInfoPrint() {
8230     InterceptorInfoPrint(stdout);
8231   }
8232   void InterceptorInfoPrint(FILE* out);
8233 #endif
8234 #ifdef DEBUG
8235   void InterceptorInfoVerify();
8236 #endif
8237
8238   static const int kGetterOffset = HeapObject::kHeaderSize;
8239   static const int kSetterOffset = kGetterOffset + kPointerSize;
8240   static const int kQueryOffset = kSetterOffset + kPointerSize;
8241   static const int kDeleterOffset = kQueryOffset + kPointerSize;
8242   static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
8243   static const int kDataOffset = kEnumeratorOffset + kPointerSize;
8244   static const int kFallbackOffset = kDataOffset + kPointerSize;
8245   static const int kSize = kFallbackOffset + kPointerSize;
8246
8247  private:
8248   DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
8249 };
8250
8251
8252 class CallHandlerInfo: public Struct {
8253  public:
8254   DECL_ACCESSORS(callback, Object)
8255   DECL_ACCESSORS(data, Object)
8256
8257   static inline CallHandlerInfo* cast(Object* obj);
8258
8259 #ifdef OBJECT_PRINT
8260   inline void CallHandlerInfoPrint() {
8261     CallHandlerInfoPrint(stdout);
8262   }
8263   void CallHandlerInfoPrint(FILE* out);
8264 #endif
8265 #ifdef DEBUG
8266   void CallHandlerInfoVerify();
8267 #endif
8268
8269   static const int kCallbackOffset = HeapObject::kHeaderSize;
8270   static const int kDataOffset = kCallbackOffset + kPointerSize;
8271   static const int kSize = kDataOffset + kPointerSize;
8272
8273  private:
8274   DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
8275 };
8276
8277
8278 class TemplateInfo: public Struct {
8279  public:
8280   DECL_ACCESSORS(tag, Object)
8281   DECL_ACCESSORS(property_list, Object)
8282
8283 #ifdef DEBUG
8284   void TemplateInfoVerify();
8285 #endif
8286
8287   static const int kTagOffset          = HeapObject::kHeaderSize;
8288   static const int kPropertyListOffset = kTagOffset + kPointerSize;
8289   static const int kHeaderSize         = kPropertyListOffset + kPointerSize;
8290
8291  private:
8292   DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
8293 };
8294
8295
8296 class FunctionTemplateInfo: public TemplateInfo {
8297  public:
8298   DECL_ACCESSORS(serial_number, Object)
8299   DECL_ACCESSORS(call_code, Object)
8300   DECL_ACCESSORS(property_accessors, Object)
8301   DECL_ACCESSORS(prototype_template, Object)
8302   DECL_ACCESSORS(parent_template, Object)
8303   DECL_ACCESSORS(named_property_handler, Object)
8304   DECL_ACCESSORS(indexed_property_handler, Object)
8305   DECL_ACCESSORS(instance_template, Object)
8306   DECL_ACCESSORS(class_name, Object)
8307   DECL_ACCESSORS(signature, Object)
8308   DECL_ACCESSORS(instance_call_handler, Object)
8309   DECL_ACCESSORS(access_check_info, Object)
8310   DECL_ACCESSORS(flag, Smi)
8311
8312   // Following properties use flag bits.
8313   DECL_BOOLEAN_ACCESSORS(hidden_prototype)
8314   DECL_BOOLEAN_ACCESSORS(undetectable)
8315   // If the bit is set, object instances created by this function
8316   // requires access check.
8317   DECL_BOOLEAN_ACCESSORS(needs_access_check)
8318   DECL_BOOLEAN_ACCESSORS(read_only_prototype)
8319
8320   static inline FunctionTemplateInfo* cast(Object* obj);
8321
8322 #ifdef OBJECT_PRINT
8323   inline void FunctionTemplateInfoPrint() {
8324     FunctionTemplateInfoPrint(stdout);
8325   }
8326   void FunctionTemplateInfoPrint(FILE* out);
8327 #endif
8328 #ifdef DEBUG
8329   void FunctionTemplateInfoVerify();
8330 #endif
8331
8332   static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
8333   static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
8334   static const int kPropertyAccessorsOffset = kCallCodeOffset + kPointerSize;
8335   static const int kPrototypeTemplateOffset =
8336       kPropertyAccessorsOffset + kPointerSize;
8337   static const int kParentTemplateOffset =
8338       kPrototypeTemplateOffset + kPointerSize;
8339   static const int kNamedPropertyHandlerOffset =
8340       kParentTemplateOffset + kPointerSize;
8341   static const int kIndexedPropertyHandlerOffset =
8342       kNamedPropertyHandlerOffset + kPointerSize;
8343   static const int kInstanceTemplateOffset =
8344       kIndexedPropertyHandlerOffset + kPointerSize;
8345   static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
8346   static const int kSignatureOffset = kClassNameOffset + kPointerSize;
8347   static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
8348   static const int kAccessCheckInfoOffset =
8349       kInstanceCallHandlerOffset + kPointerSize;
8350   static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
8351   static const int kSize = kFlagOffset + kPointerSize;
8352
8353  private:
8354   // Bit position in the flag, from least significant bit position.
8355   static const int kHiddenPrototypeBit   = 0;
8356   static const int kUndetectableBit      = 1;
8357   static const int kNeedsAccessCheckBit  = 2;
8358   static const int kReadOnlyPrototypeBit = 3;
8359
8360   DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
8361 };
8362
8363
8364 class ObjectTemplateInfo: public TemplateInfo {
8365  public:
8366   DECL_ACCESSORS(constructor, Object)
8367   DECL_ACCESSORS(internal_field_count, Object)
8368   DECL_ACCESSORS(has_external_resource, Object)
8369
8370   static inline ObjectTemplateInfo* cast(Object* obj);
8371
8372 #ifdef OBJECT_PRINT
8373   inline void ObjectTemplateInfoPrint() {
8374     ObjectTemplateInfoPrint(stdout);
8375   }
8376   void ObjectTemplateInfoPrint(FILE* out);
8377 #endif
8378 #ifdef DEBUG
8379   void ObjectTemplateInfoVerify();
8380 #endif
8381
8382   static const int kConstructorOffset = TemplateInfo::kHeaderSize;
8383   static const int kInternalFieldCountOffset =
8384       kConstructorOffset + kPointerSize;
8385   static const int kHasExternalResourceOffset = kInternalFieldCountOffset + kPointerSize;
8386   static const int kSize = kHasExternalResourceOffset + kPointerSize;
8387 };
8388
8389
8390 class SignatureInfo: public Struct {
8391  public:
8392   DECL_ACCESSORS(receiver, Object)
8393   DECL_ACCESSORS(args, Object)
8394
8395   static inline SignatureInfo* cast(Object* obj);
8396
8397 #ifdef OBJECT_PRINT
8398   inline void SignatureInfoPrint() {
8399     SignatureInfoPrint(stdout);
8400   }
8401   void SignatureInfoPrint(FILE* out);
8402 #endif
8403 #ifdef DEBUG
8404   void SignatureInfoVerify();
8405 #endif
8406
8407   static const int kReceiverOffset = Struct::kHeaderSize;
8408   static const int kArgsOffset     = kReceiverOffset + kPointerSize;
8409   static const int kSize           = kArgsOffset + kPointerSize;
8410
8411  private:
8412   DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
8413 };
8414
8415
8416 class TypeSwitchInfo: public Struct {
8417  public:
8418   DECL_ACCESSORS(types, Object)
8419
8420   static inline TypeSwitchInfo* cast(Object* obj);
8421
8422 #ifdef OBJECT_PRINT
8423   inline void TypeSwitchInfoPrint() {
8424     TypeSwitchInfoPrint(stdout);
8425   }
8426   void TypeSwitchInfoPrint(FILE* out);
8427 #endif
8428 #ifdef DEBUG
8429   void TypeSwitchInfoVerify();
8430 #endif
8431
8432   static const int kTypesOffset = Struct::kHeaderSize;
8433   static const int kSize        = kTypesOffset + kPointerSize;
8434 };
8435
8436
8437 #ifdef ENABLE_DEBUGGER_SUPPORT
8438 // The DebugInfo class holds additional information for a function being
8439 // debugged.
8440 class DebugInfo: public Struct {
8441  public:
8442   // The shared function info for the source being debugged.
8443   DECL_ACCESSORS(shared, SharedFunctionInfo)
8444   // Code object for the original code.
8445   DECL_ACCESSORS(original_code, Code)
8446   // Code object for the patched code. This code object is the code object
8447   // currently active for the function.
8448   DECL_ACCESSORS(code, Code)
8449   // Fixed array holding status information for each active break point.
8450   DECL_ACCESSORS(break_points, FixedArray)
8451
8452   // Check if there is a break point at a code position.
8453   bool HasBreakPoint(int code_position);
8454   // Get the break point info object for a code position.
8455   Object* GetBreakPointInfo(int code_position);
8456   // Clear a break point.
8457   static void ClearBreakPoint(Handle<DebugInfo> debug_info,
8458                               int code_position,
8459                               Handle<Object> break_point_object);
8460   // Set a break point.
8461   static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
8462                             int source_position, int statement_position,
8463                             Handle<Object> break_point_object);
8464   // Get the break point objects for a code position.
8465   Object* GetBreakPointObjects(int code_position);
8466   // Find the break point info holding this break point object.
8467   static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
8468                                     Handle<Object> break_point_object);
8469   // Get the number of break points for this function.
8470   int GetBreakPointCount();
8471
8472   static inline DebugInfo* cast(Object* obj);
8473
8474 #ifdef OBJECT_PRINT
8475   inline void DebugInfoPrint() {
8476     DebugInfoPrint(stdout);
8477   }
8478   void DebugInfoPrint(FILE* out);
8479 #endif
8480 #ifdef DEBUG
8481   void DebugInfoVerify();
8482 #endif
8483
8484   static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
8485   static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
8486   static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
8487   static const int kActiveBreakPointsCountIndex =
8488       kPatchedCodeIndex + kPointerSize;
8489   static const int kBreakPointsStateIndex =
8490       kActiveBreakPointsCountIndex + kPointerSize;
8491   static const int kSize = kBreakPointsStateIndex + kPointerSize;
8492
8493  private:
8494   static const int kNoBreakPointInfo = -1;
8495
8496   // Lookup the index in the break_points array for a code position.
8497   int GetBreakPointInfoIndex(int code_position);
8498
8499   DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
8500 };
8501
8502
8503 // The BreakPointInfo class holds information for break points set in a
8504 // function. The DebugInfo object holds a BreakPointInfo object for each code
8505 // position with one or more break points.
8506 class BreakPointInfo: public Struct {
8507  public:
8508   // The position in the code for the break point.
8509   DECL_ACCESSORS(code_position, Smi)
8510   // The position in the source for the break position.
8511   DECL_ACCESSORS(source_position, Smi)
8512   // The position in the source for the last statement before this break
8513   // position.
8514   DECL_ACCESSORS(statement_position, Smi)
8515   // List of related JavaScript break points.
8516   DECL_ACCESSORS(break_point_objects, Object)
8517
8518   // Removes a break point.
8519   static void ClearBreakPoint(Handle<BreakPointInfo> info,
8520                               Handle<Object> break_point_object);
8521   // Set a break point.
8522   static void SetBreakPoint(Handle<BreakPointInfo> info,
8523                             Handle<Object> break_point_object);
8524   // Check if break point info has this break point object.
8525   static bool HasBreakPointObject(Handle<BreakPointInfo> info,
8526                                   Handle<Object> break_point_object);
8527   // Get the number of break points for this code position.
8528   int GetBreakPointCount();
8529
8530   static inline BreakPointInfo* cast(Object* obj);
8531
8532 #ifdef OBJECT_PRINT
8533   inline void BreakPointInfoPrint() {
8534     BreakPointInfoPrint(stdout);
8535   }
8536   void BreakPointInfoPrint(FILE* out);
8537 #endif
8538 #ifdef DEBUG
8539   void BreakPointInfoVerify();
8540 #endif
8541
8542   static const int kCodePositionIndex = Struct::kHeaderSize;
8543   static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
8544   static const int kStatementPositionIndex =
8545       kSourcePositionIndex + kPointerSize;
8546   static const int kBreakPointObjectsIndex =
8547       kStatementPositionIndex + kPointerSize;
8548   static const int kSize = kBreakPointObjectsIndex + kPointerSize;
8549
8550  private:
8551   DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
8552 };
8553 #endif  // ENABLE_DEBUGGER_SUPPORT
8554
8555
8556 #undef DECL_BOOLEAN_ACCESSORS
8557 #undef DECL_ACCESSORS
8558
8559 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V)                            \
8560   V(kSymbolTable, "symbol_table", "(Symbols)")                          \
8561   V(kExternalStringsTable, "external_strings_table", "(External strings)") \
8562   V(kStrongRootList, "strong_root_list", "(Strong roots)")              \
8563   V(kSymbol, "symbol", "(Symbol)")                                      \
8564   V(kBootstrapper, "bootstrapper", "(Bootstrapper)")                    \
8565   V(kTop, "top", "(Isolate)")                                           \
8566   V(kRelocatable, "relocatable", "(Relocatable)")                       \
8567   V(kDebug, "debug", "(Debugger)")                                      \
8568   V(kCompilationCache, "compilationcache", "(Compilation cache)")       \
8569   V(kHandleScope, "handlescope", "(Handle scope)")                      \
8570   V(kBuiltins, "builtins", "(Builtins)")                                \
8571   V(kGlobalHandles, "globalhandles", "(Global handles)")                \
8572   V(kThreadManager, "threadmanager", "(Thread manager)")                \
8573   V(kExtensions, "Extensions", "(Extensions)")
8574
8575 class VisitorSynchronization : public AllStatic {
8576  public:
8577 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
8578   enum SyncTag {
8579     VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
8580     kNumberOfSyncTags
8581   };
8582 #undef DECLARE_ENUM
8583
8584   static const char* const kTags[kNumberOfSyncTags];
8585   static const char* const kTagNames[kNumberOfSyncTags];
8586 };
8587
8588 // Abstract base class for visiting, and optionally modifying, the
8589 // pointers contained in Objects. Used in GC and serialization/deserialization.
8590 class ObjectVisitor BASE_EMBEDDED {
8591  public:
8592   virtual ~ObjectVisitor() {}
8593
8594   // Visits a contiguous arrays of pointers in the half-open range
8595   // [start, end). Any or all of the values may be modified on return.
8596   virtual void VisitPointers(Object** start, Object** end) = 0;
8597
8598   // To allow lazy clearing of inline caches the visitor has
8599   // a rich interface for iterating over Code objects..
8600
8601   // Visits a code target in the instruction stream.
8602   virtual void VisitCodeTarget(RelocInfo* rinfo);
8603
8604   // Visits a code entry in a JS function.
8605   virtual void VisitCodeEntry(Address entry_address);
8606
8607   // Visits a global property cell reference in the instruction stream.
8608   virtual void VisitGlobalPropertyCell(RelocInfo* rinfo);
8609
8610   // Visits a runtime entry in the instruction stream.
8611   virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
8612
8613   // Visits the resource of an ASCII or two-byte string.
8614   virtual void VisitExternalAsciiString(
8615       v8::String::ExternalAsciiStringResource** resource) {}
8616   virtual void VisitExternalTwoByteString(
8617       v8::String::ExternalStringResource** resource) {}
8618
8619   // Visits a debug call target in the instruction stream.
8620   virtual void VisitDebugTarget(RelocInfo* rinfo);
8621
8622   // Handy shorthand for visiting a single pointer.
8623   virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
8624
8625   // Visit pointer embedded into a code object.
8626   virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
8627
8628   virtual void VisitSharedFunctionInfo(SharedFunctionInfo* shared) {}
8629
8630   // Visits a contiguous arrays of external references (references to the C++
8631   // heap) in the half-open range [start, end). Any or all of the values
8632   // may be modified on return.
8633   virtual void VisitExternalReferences(Address* start, Address* end) {}
8634
8635   virtual void VisitExternalReference(RelocInfo* rinfo);
8636
8637   inline void VisitExternalReference(Address* p) {
8638     VisitExternalReferences(p, p + 1);
8639   }
8640
8641   // Visits a handle that has an embedder-assigned class ID.
8642   virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
8643
8644   // Intended for serialization/deserialization checking: insert, or
8645   // check for the presence of, a tag at this position in the stream.
8646   // Also used for marking up GC roots in heap snapshots.
8647   virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
8648 };
8649
8650
8651 class StructBodyDescriptor : public
8652   FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
8653  public:
8654   static inline int SizeOf(Map* map, HeapObject* object) {
8655     return map->instance_size();
8656   }
8657 };
8658
8659
8660 // BooleanBit is a helper class for setting and getting a bit in an
8661 // integer or Smi.
8662 class BooleanBit : public AllStatic {
8663  public:
8664   static inline bool get(Smi* smi, int bit_position) {
8665     return get(smi->value(), bit_position);
8666   }
8667
8668   static inline bool get(int value, int bit_position) {
8669     return (value & (1 << bit_position)) != 0;
8670   }
8671
8672   static inline Smi* set(Smi* smi, int bit_position, bool v) {
8673     return Smi::FromInt(set(smi->value(), bit_position, v));
8674   }
8675
8676   static inline int set(int value, int bit_position, bool v) {
8677     if (v) {
8678       value |= (1 << bit_position);
8679     } else {
8680       value &= ~(1 << bit_position);
8681     }
8682     return value;
8683   }
8684 };
8685
8686 } }  // namespace v8::internal
8687
8688 #endif  // V8_OBJECTS_H_