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