blob: e9430f5b34f5ed25ea0511ef2a964e1e0da3d900 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 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 "builtins.h"
32#include "code-stubs.h"
33#include "smart-pointer.h"
34#include "unicode-inl.h"
35
36//
37// All object types in the V8 JavaScript are described in this file.
38//
39// Inheritance hierarchy:
40// - Object
41// - Smi (immediate small integer)
42// - Failure (immediate for marking failed operation)
43// - HeapObject (superclass for everything allocated in the heap)
44// - JSObject
45// - JSArray
46// - JSRegExp
47// - JSFunction
48// - GlobalObject
49// - JSGlobalObject
50// - JSBuiltinsObject
51// - JSGlobalProxy
52// - JSValue
53// - Array
54// - ByteArray
55// - PixelArray
56// - FixedArray
57// - DescriptorArray
58// - HashTable
59// - Dictionary
60// - SymbolTable
61// - CompilationCacheTable
62// - MapCache
63// - Context
64// - GlobalContext
65// - String
66// - SeqString
67// - SeqAsciiString
68// - SeqTwoByteString
69// - ConsString
70// - SlicedString
71// - ExternalString
72// - ExternalAsciiString
73// - ExternalTwoByteString
74// - HeapNumber
75// - Code
76// - Map
77// - Oddball
78// - Proxy
79// - SharedFunctionInfo
80// - Struct
81// - AccessorInfo
82// - AccessCheckInfo
83// - InterceptorInfo
84// - CallHandlerInfo
85// - TemplateInfo
86// - FunctionTemplateInfo
87// - ObjectTemplateInfo
88// - Script
89// - SignatureInfo
90// - TypeSwitchInfo
91// - DebugInfo
92// - BreakPointInfo
93//
94// Formats of Object*:
95// Smi: [31 bit signed int] 0
96// HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
97// Failure: [30 bit signed int] 11
98
99// Ecma-262 3rd 8.6.1
100enum PropertyAttributes {
101 NONE = v8::None,
102 READ_ONLY = v8::ReadOnly,
103 DONT_ENUM = v8::DontEnum,
104 DONT_DELETE = v8::DontDelete,
105 ABSENT = 16 // Used in runtime to indicate a property is absent.
106 // ABSENT can never be stored in or returned from a descriptor's attributes
107 // bitfield. It is only used as a return value meaning the attributes of
108 // a non-existent property.
109};
110
111namespace v8 {
112namespace internal {
113
114
115// PropertyDetails captures type and attributes for a property.
116// They are used both in property dictionaries and instance descriptors.
117class PropertyDetails BASE_EMBEDDED {
118 public:
119
120 PropertyDetails(PropertyAttributes attributes,
121 PropertyType type,
122 int index = 0) {
123 ASSERT(TypeField::is_valid(type));
124 ASSERT(AttributesField::is_valid(attributes));
125 ASSERT(IndexField::is_valid(index));
126
127 value_ = TypeField::encode(type)
128 | AttributesField::encode(attributes)
129 | IndexField::encode(index);
130
131 ASSERT(type == this->type());
132 ASSERT(attributes == this->attributes());
133 ASSERT(index == this->index());
134 }
135
136 // Conversion for storing details as Object*.
137 inline PropertyDetails(Smi* smi);
138 inline Smi* AsSmi();
139
140 PropertyType type() { return TypeField::decode(value_); }
141
142 bool IsTransition() {
143 PropertyType t = type();
144 ASSERT(t != INTERCEPTOR);
145 return t == MAP_TRANSITION || t == CONSTANT_TRANSITION;
146 }
147
148 bool IsProperty() {
149 return type() < FIRST_PHANTOM_PROPERTY_TYPE;
150 }
151
152 PropertyAttributes attributes() { return AttributesField::decode(value_); }
153
154 int index() { return IndexField::decode(value_); }
155
156 inline PropertyDetails AsDeleted();
157
158 static bool IsValidIndex(int index) { return IndexField::is_valid(index); }
159
160 bool IsReadOnly() { return (attributes() & READ_ONLY) != 0; }
161 bool IsDontDelete() { return (attributes() & DONT_DELETE) != 0; }
162 bool IsDontEnum() { return (attributes() & DONT_ENUM) != 0; }
163 bool IsDeleted() { return DeletedField::decode(value_) != 0;}
164
165 // Bit fields in value_ (type, shift, size). Must be public so the
166 // constants can be embedded in generated code.
167 class TypeField: public BitField<PropertyType, 0, 3> {};
168 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
169 class DeletedField: public BitField<uint32_t, 6, 1> {};
170 class IndexField: public BitField<uint32_t, 7, 31-7> {};
171
172 static const int kInitialIndex = 1;
173 private:
174 uint32_t value_;
175};
176
177
178// Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
179enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
180
181
182// PropertyNormalizationMode is used to specify whether to keep
183// inobject properties when normalizing properties of a JSObject.
184enum PropertyNormalizationMode {
185 CLEAR_INOBJECT_PROPERTIES,
186 KEEP_INOBJECT_PROPERTIES
187};
188
189
190// All Maps have a field instance_type containing a InstanceType.
191// It describes the type of the instances.
192//
193// As an example, a JavaScript object is a heap object and its map
194// instance_type is JS_OBJECT_TYPE.
195//
196// The names of the string instance types are intended to systematically
197// mirror their encoding in the instance_type field of the map. The length
198// (SHORT, MEDIUM, or LONG) is always mentioned. The default encoding is
199// considered TWO_BYTE. It is not mentioned in the name. ASCII encoding is
200// mentioned explicitly in the name. Likewise, the default representation is
201// considered sequential. It is not mentioned in the name. The other
202// representations (eg, CONS, SLICED, EXTERNAL) are explicitly mentioned.
203// Finally, the string is either a SYMBOL_TYPE (if it is a symbol) or a
204// STRING_TYPE (if it is not a symbol).
205//
206// NOTE: The following things are some that depend on the string types having
207// instance_types that are less than those of all other types:
208// HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
209// Object::IsString.
210//
211// NOTE: Everything following JS_VALUE_TYPE is considered a
212// JSObject for GC purposes. The first four entries here have typeof
213// 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
214#define INSTANCE_TYPE_LIST_ALL(V) \
215 V(SHORT_SYMBOL_TYPE) \
216 V(MEDIUM_SYMBOL_TYPE) \
217 V(LONG_SYMBOL_TYPE) \
218 V(SHORT_ASCII_SYMBOL_TYPE) \
219 V(MEDIUM_ASCII_SYMBOL_TYPE) \
220 V(LONG_ASCII_SYMBOL_TYPE) \
221 V(SHORT_CONS_SYMBOL_TYPE) \
222 V(MEDIUM_CONS_SYMBOL_TYPE) \
223 V(LONG_CONS_SYMBOL_TYPE) \
224 V(SHORT_CONS_ASCII_SYMBOL_TYPE) \
225 V(MEDIUM_CONS_ASCII_SYMBOL_TYPE) \
226 V(LONG_CONS_ASCII_SYMBOL_TYPE) \
227 V(SHORT_SLICED_SYMBOL_TYPE) \
228 V(MEDIUM_SLICED_SYMBOL_TYPE) \
229 V(LONG_SLICED_SYMBOL_TYPE) \
230 V(SHORT_SLICED_ASCII_SYMBOL_TYPE) \
231 V(MEDIUM_SLICED_ASCII_SYMBOL_TYPE) \
232 V(LONG_SLICED_ASCII_SYMBOL_TYPE) \
233 V(SHORT_EXTERNAL_SYMBOL_TYPE) \
234 V(MEDIUM_EXTERNAL_SYMBOL_TYPE) \
235 V(LONG_EXTERNAL_SYMBOL_TYPE) \
236 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE) \
237 V(MEDIUM_EXTERNAL_ASCII_SYMBOL_TYPE) \
238 V(LONG_EXTERNAL_ASCII_SYMBOL_TYPE) \
239 V(SHORT_STRING_TYPE) \
240 V(MEDIUM_STRING_TYPE) \
241 V(LONG_STRING_TYPE) \
242 V(SHORT_ASCII_STRING_TYPE) \
243 V(MEDIUM_ASCII_STRING_TYPE) \
244 V(LONG_ASCII_STRING_TYPE) \
245 V(SHORT_CONS_STRING_TYPE) \
246 V(MEDIUM_CONS_STRING_TYPE) \
247 V(LONG_CONS_STRING_TYPE) \
248 V(SHORT_CONS_ASCII_STRING_TYPE) \
249 V(MEDIUM_CONS_ASCII_STRING_TYPE) \
250 V(LONG_CONS_ASCII_STRING_TYPE) \
251 V(SHORT_SLICED_STRING_TYPE) \
252 V(MEDIUM_SLICED_STRING_TYPE) \
253 V(LONG_SLICED_STRING_TYPE) \
254 V(SHORT_SLICED_ASCII_STRING_TYPE) \
255 V(MEDIUM_SLICED_ASCII_STRING_TYPE) \
256 V(LONG_SLICED_ASCII_STRING_TYPE) \
257 V(SHORT_EXTERNAL_STRING_TYPE) \
258 V(MEDIUM_EXTERNAL_STRING_TYPE) \
259 V(LONG_EXTERNAL_STRING_TYPE) \
260 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
261 V(MEDIUM_EXTERNAL_ASCII_STRING_TYPE) \
262 V(LONG_EXTERNAL_ASCII_STRING_TYPE) \
263 V(LONG_PRIVATE_EXTERNAL_ASCII_STRING_TYPE) \
264 \
265 V(MAP_TYPE) \
266 V(HEAP_NUMBER_TYPE) \
267 V(FIXED_ARRAY_TYPE) \
268 V(CODE_TYPE) \
269 V(JS_GLOBAL_PROPERTY_CELL_TYPE) \
270 V(ODDBALL_TYPE) \
271 V(PROXY_TYPE) \
272 V(BYTE_ARRAY_TYPE) \
273 V(PIXEL_ARRAY_TYPE) \
274 V(FILLER_TYPE) \
275 \
276 V(ACCESSOR_INFO_TYPE) \
277 V(ACCESS_CHECK_INFO_TYPE) \
278 V(INTERCEPTOR_INFO_TYPE) \
279 V(SHARED_FUNCTION_INFO_TYPE) \
280 V(CALL_HANDLER_INFO_TYPE) \
281 V(FUNCTION_TEMPLATE_INFO_TYPE) \
282 V(OBJECT_TEMPLATE_INFO_TYPE) \
283 V(SIGNATURE_INFO_TYPE) \
284 V(TYPE_SWITCH_INFO_TYPE) \
285 V(SCRIPT_TYPE) \
286 \
287 V(JS_VALUE_TYPE) \
288 V(JS_OBJECT_TYPE) \
289 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
290 V(JS_GLOBAL_OBJECT_TYPE) \
291 V(JS_BUILTINS_OBJECT_TYPE) \
292 V(JS_GLOBAL_PROXY_TYPE) \
293 V(JS_ARRAY_TYPE) \
294 V(JS_REGEXP_TYPE) \
295 \
296 V(JS_FUNCTION_TYPE) \
297
298#ifdef ENABLE_DEBUGGER_SUPPORT
299#define INSTANCE_TYPE_LIST_DEBUGGER(V) \
300 V(DEBUG_INFO_TYPE) \
301 V(BREAK_POINT_INFO_TYPE)
302#else
303#define INSTANCE_TYPE_LIST_DEBUGGER(V)
304#endif
305
306#define INSTANCE_TYPE_LIST(V) \
307 INSTANCE_TYPE_LIST_ALL(V) \
308 INSTANCE_TYPE_LIST_DEBUGGER(V)
309
310
311// Since string types are not consecutive, this macro is used to
312// iterate over them.
313#define STRING_TYPE_LIST(V) \
314 V(SHORT_SYMBOL_TYPE, \
315 SeqTwoByteString::kAlignedSize, \
316 short_symbol, \
317 ShortSymbol) \
318 V(MEDIUM_SYMBOL_TYPE, \
319 SeqTwoByteString::kAlignedSize, \
320 medium_symbol, \
321 MediumSymbol) \
322 V(LONG_SYMBOL_TYPE, \
323 SeqTwoByteString::kAlignedSize, \
324 long_symbol, \
325 LongSymbol) \
326 V(SHORT_ASCII_SYMBOL_TYPE, \
327 SeqAsciiString::kAlignedSize, \
328 short_ascii_symbol, \
329 ShortAsciiSymbol) \
330 V(MEDIUM_ASCII_SYMBOL_TYPE, \
331 SeqAsciiString::kAlignedSize, \
332 medium_ascii_symbol, \
333 MediumAsciiSymbol) \
334 V(LONG_ASCII_SYMBOL_TYPE, \
335 SeqAsciiString::kAlignedSize, \
336 long_ascii_symbol, \
337 LongAsciiSymbol) \
338 V(SHORT_CONS_SYMBOL_TYPE, \
339 ConsString::kSize, \
340 short_cons_symbol, \
341 ShortConsSymbol) \
342 V(MEDIUM_CONS_SYMBOL_TYPE, \
343 ConsString::kSize, \
344 medium_cons_symbol, \
345 MediumConsSymbol) \
346 V(LONG_CONS_SYMBOL_TYPE, \
347 ConsString::kSize, \
348 long_cons_symbol, \
349 LongConsSymbol) \
350 V(SHORT_CONS_ASCII_SYMBOL_TYPE, \
351 ConsString::kSize, \
352 short_cons_ascii_symbol, \
353 ShortConsAsciiSymbol) \
354 V(MEDIUM_CONS_ASCII_SYMBOL_TYPE, \
355 ConsString::kSize, \
356 medium_cons_ascii_symbol, \
357 MediumConsAsciiSymbol) \
358 V(LONG_CONS_ASCII_SYMBOL_TYPE, \
359 ConsString::kSize, \
360 long_cons_ascii_symbol, \
361 LongConsAsciiSymbol) \
362 V(SHORT_SLICED_SYMBOL_TYPE, \
363 SlicedString::kSize, \
364 short_sliced_symbol, \
365 ShortSlicedSymbol) \
366 V(MEDIUM_SLICED_SYMBOL_TYPE, \
367 SlicedString::kSize, \
368 medium_sliced_symbol, \
369 MediumSlicedSymbol) \
370 V(LONG_SLICED_SYMBOL_TYPE, \
371 SlicedString::kSize, \
372 long_sliced_symbol, \
373 LongSlicedSymbol) \
374 V(SHORT_SLICED_ASCII_SYMBOL_TYPE, \
375 SlicedString::kSize, \
376 short_sliced_ascii_symbol, \
377 ShortSlicedAsciiSymbol) \
378 V(MEDIUM_SLICED_ASCII_SYMBOL_TYPE, \
379 SlicedString::kSize, \
380 medium_sliced_ascii_symbol, \
381 MediumSlicedAsciiSymbol) \
382 V(LONG_SLICED_ASCII_SYMBOL_TYPE, \
383 SlicedString::kSize, \
384 long_sliced_ascii_symbol, \
385 LongSlicedAsciiSymbol) \
386 V(SHORT_EXTERNAL_SYMBOL_TYPE, \
387 ExternalTwoByteString::kSize, \
388 short_external_symbol, \
389 ShortExternalSymbol) \
390 V(MEDIUM_EXTERNAL_SYMBOL_TYPE, \
391 ExternalTwoByteString::kSize, \
392 medium_external_symbol, \
393 MediumExternalSymbol) \
394 V(LONG_EXTERNAL_SYMBOL_TYPE, \
395 ExternalTwoByteString::kSize, \
396 long_external_symbol, \
397 LongExternalSymbol) \
398 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE, \
399 ExternalAsciiString::kSize, \
400 short_external_ascii_symbol, \
401 ShortExternalAsciiSymbol) \
402 V(MEDIUM_EXTERNAL_ASCII_SYMBOL_TYPE, \
403 ExternalAsciiString::kSize, \
404 medium_external_ascii_symbol, \
405 MediumExternalAsciiSymbol) \
406 V(LONG_EXTERNAL_ASCII_SYMBOL_TYPE, \
407 ExternalAsciiString::kSize, \
408 long_external_ascii_symbol, \
409 LongExternalAsciiSymbol) \
410 V(SHORT_STRING_TYPE, \
411 SeqTwoByteString::kAlignedSize, \
412 short_string, \
413 ShortString) \
414 V(MEDIUM_STRING_TYPE, \
415 SeqTwoByteString::kAlignedSize, \
416 medium_string, \
417 MediumString) \
418 V(LONG_STRING_TYPE, \
419 SeqTwoByteString::kAlignedSize, \
420 long_string, \
421 LongString) \
422 V(SHORT_ASCII_STRING_TYPE, \
423 SeqAsciiString::kAlignedSize, \
424 short_ascii_string, \
425 ShortAsciiString) \
426 V(MEDIUM_ASCII_STRING_TYPE, \
427 SeqAsciiString::kAlignedSize, \
428 medium_ascii_string, \
429 MediumAsciiString) \
430 V(LONG_ASCII_STRING_TYPE, \
431 SeqAsciiString::kAlignedSize, \
432 long_ascii_string, \
433 LongAsciiString) \
434 V(SHORT_CONS_STRING_TYPE, \
435 ConsString::kSize, \
436 short_cons_string, \
437 ShortConsString) \
438 V(MEDIUM_CONS_STRING_TYPE, \
439 ConsString::kSize, \
440 medium_cons_string, \
441 MediumConsString) \
442 V(LONG_CONS_STRING_TYPE, \
443 ConsString::kSize, \
444 long_cons_string, \
445 LongConsString) \
446 V(SHORT_CONS_ASCII_STRING_TYPE, \
447 ConsString::kSize, \
448 short_cons_ascii_string, \
449 ShortConsAsciiString) \
450 V(MEDIUM_CONS_ASCII_STRING_TYPE, \
451 ConsString::kSize, \
452 medium_cons_ascii_string, \
453 MediumConsAsciiString) \
454 V(LONG_CONS_ASCII_STRING_TYPE, \
455 ConsString::kSize, \
456 long_cons_ascii_string, \
457 LongConsAsciiString) \
458 V(SHORT_SLICED_STRING_TYPE, \
459 SlicedString::kSize, \
460 short_sliced_string, \
461 ShortSlicedString) \
462 V(MEDIUM_SLICED_STRING_TYPE, \
463 SlicedString::kSize, \
464 medium_sliced_string, \
465 MediumSlicedString) \
466 V(LONG_SLICED_STRING_TYPE, \
467 SlicedString::kSize, \
468 long_sliced_string, \
469 LongSlicedString) \
470 V(SHORT_SLICED_ASCII_STRING_TYPE, \
471 SlicedString::kSize, \
472 short_sliced_ascii_string, \
473 ShortSlicedAsciiString) \
474 V(MEDIUM_SLICED_ASCII_STRING_TYPE, \
475 SlicedString::kSize, \
476 medium_sliced_ascii_string, \
477 MediumSlicedAsciiString) \
478 V(LONG_SLICED_ASCII_STRING_TYPE, \
479 SlicedString::kSize, \
480 long_sliced_ascii_string, \
481 LongSlicedAsciiString) \
482 V(SHORT_EXTERNAL_STRING_TYPE, \
483 ExternalTwoByteString::kSize, \
484 short_external_string, \
485 ShortExternalString) \
486 V(MEDIUM_EXTERNAL_STRING_TYPE, \
487 ExternalTwoByteString::kSize, \
488 medium_external_string, \
489 MediumExternalString) \
490 V(LONG_EXTERNAL_STRING_TYPE, \
491 ExternalTwoByteString::kSize, \
492 long_external_string, \
493 LongExternalString) \
494 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
495 ExternalAsciiString::kSize, \
496 short_external_ascii_string, \
497 ShortExternalAsciiString) \
498 V(MEDIUM_EXTERNAL_ASCII_STRING_TYPE, \
499 ExternalAsciiString::kSize, \
500 medium_external_ascii_string, \
501 MediumExternalAsciiString) \
502 V(LONG_EXTERNAL_ASCII_STRING_TYPE, \
503 ExternalAsciiString::kSize, \
504 long_external_ascii_string, \
505 LongExternalAsciiString)
506
507// A struct is a simple object a set of object-valued fields. Including an
508// object type in this causes the compiler to generate most of the boilerplate
509// code for the class including allocation and garbage collection routines,
510// casts and predicates. All you need to define is the class, methods and
511// object verification routines. Easy, no?
512//
513// Note that for subtle reasons related to the ordering or numerical values of
514// type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
515// manually.
516#define STRUCT_LIST_ALL(V) \
517 V(ACCESSOR_INFO, AccessorInfo, accessor_info) \
518 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
519 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
520 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
521 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
522 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
523 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
524 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
525 V(SCRIPT, Script, script)
526
527#ifdef ENABLE_DEBUGGER_SUPPORT
528#define STRUCT_LIST_DEBUGGER(V) \
529 V(DEBUG_INFO, DebugInfo, debug_info) \
530 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
531#else
532#define STRUCT_LIST_DEBUGGER(V)
533#endif
534
535#define STRUCT_LIST(V) \
536 STRUCT_LIST_ALL(V) \
537 STRUCT_LIST_DEBUGGER(V)
538
539// We use the full 8 bits of the instance_type field to encode heap object
540// instance types. The high-order bit (bit 7) is set if the object is not a
541// string, and cleared if it is a string.
542const uint32_t kIsNotStringMask = 0x80;
543const uint32_t kStringTag = 0x0;
544const uint32_t kNotStringTag = 0x80;
545
546// If bit 7 is clear, bit 5 indicates that the string is a symbol (if set) or
547// not (if cleared).
548const uint32_t kIsSymbolMask = 0x20;
549const uint32_t kNotSymbolTag = 0x0;
550const uint32_t kSymbolTag = 0x20;
551
552// If bit 7 is clear, bits 3 and 4 are the string's size (short, medium or
553// long). These values are very special in that they are also used to shift
554// the length field to get the length, removing the hash value. This avoids
555// using if or switch when getting the length of a string.
556const uint32_t kStringSizeMask = 0x18;
557const uint32_t kShortStringTag = 0x18;
558const uint32_t kMediumStringTag = 0x10;
559const uint32_t kLongStringTag = 0x00;
560
561// If bit 7 is clear then bit 2 indicates whether the string consists of
562// two-byte characters or one-byte characters.
563const uint32_t kStringEncodingMask = 0x4;
564const uint32_t kTwoByteStringTag = 0x0;
565const uint32_t kAsciiStringTag = 0x4;
566
567// If bit 7 is clear, the low-order 2 bits indicate the representation
568// of the string.
569const uint32_t kStringRepresentationMask = 0x03;
570enum StringRepresentationTag {
571 kSeqStringTag = 0x0,
572 kConsStringTag = 0x1,
573 kSlicedStringTag = 0x2,
574 kExternalStringTag = 0x3
575};
576
577
578// A ConsString with an empty string as the right side is a candidate
579// for being shortcut by the garbage collector unless it is a
580// symbol. It's not common to have non-flat symbols, so we do not
581// shortcut them thereby avoiding turning symbols into strings. See
582// heap.cc and mark-compact.cc.
583const uint32_t kShortcutTypeMask =
584 kIsNotStringMask |
585 kIsSymbolMask |
586 kStringRepresentationMask;
587const uint32_t kShortcutTypeTag = kConsStringTag;
588
589
590enum InstanceType {
591 SHORT_SYMBOL_TYPE = kShortStringTag | kSymbolTag | kSeqStringTag,
592 MEDIUM_SYMBOL_TYPE = kMediumStringTag | kSymbolTag | kSeqStringTag,
593 LONG_SYMBOL_TYPE = kLongStringTag | kSymbolTag | kSeqStringTag,
594 SHORT_ASCII_SYMBOL_TYPE =
595 kShortStringTag | kAsciiStringTag | kSymbolTag | kSeqStringTag,
596 MEDIUM_ASCII_SYMBOL_TYPE =
597 kMediumStringTag | kAsciiStringTag | kSymbolTag | kSeqStringTag,
598 LONG_ASCII_SYMBOL_TYPE =
599 kLongStringTag | kAsciiStringTag | kSymbolTag | kSeqStringTag,
600 SHORT_CONS_SYMBOL_TYPE = kShortStringTag | kSymbolTag | kConsStringTag,
601 MEDIUM_CONS_SYMBOL_TYPE = kMediumStringTag | kSymbolTag | kConsStringTag,
602 LONG_CONS_SYMBOL_TYPE = kLongStringTag | kSymbolTag | kConsStringTag,
603 SHORT_CONS_ASCII_SYMBOL_TYPE =
604 kShortStringTag | kAsciiStringTag | kSymbolTag | kConsStringTag,
605 MEDIUM_CONS_ASCII_SYMBOL_TYPE =
606 kMediumStringTag | kAsciiStringTag | kSymbolTag | kConsStringTag,
607 LONG_CONS_ASCII_SYMBOL_TYPE =
608 kLongStringTag | kAsciiStringTag | kSymbolTag | kConsStringTag,
609 SHORT_SLICED_SYMBOL_TYPE = kShortStringTag | kSymbolTag | kSlicedStringTag,
610 MEDIUM_SLICED_SYMBOL_TYPE = kMediumStringTag | kSymbolTag | kSlicedStringTag,
611 LONG_SLICED_SYMBOL_TYPE = kLongStringTag | kSymbolTag | kSlicedStringTag,
612 SHORT_SLICED_ASCII_SYMBOL_TYPE =
613 kShortStringTag | kAsciiStringTag | kSymbolTag | kSlicedStringTag,
614 MEDIUM_SLICED_ASCII_SYMBOL_TYPE =
615 kMediumStringTag | kAsciiStringTag | kSymbolTag | kSlicedStringTag,
616 LONG_SLICED_ASCII_SYMBOL_TYPE =
617 kLongStringTag | kAsciiStringTag | kSymbolTag | kSlicedStringTag,
618 SHORT_EXTERNAL_SYMBOL_TYPE =
619 kShortStringTag | kSymbolTag | kExternalStringTag,
620 MEDIUM_EXTERNAL_SYMBOL_TYPE =
621 kMediumStringTag | kSymbolTag | kExternalStringTag,
622 LONG_EXTERNAL_SYMBOL_TYPE = kLongStringTag | kSymbolTag | kExternalStringTag,
623 SHORT_EXTERNAL_ASCII_SYMBOL_TYPE =
624 kShortStringTag | kAsciiStringTag | kSymbolTag | kExternalStringTag,
625 MEDIUM_EXTERNAL_ASCII_SYMBOL_TYPE =
626 kMediumStringTag | kAsciiStringTag | kSymbolTag | kExternalStringTag,
627 LONG_EXTERNAL_ASCII_SYMBOL_TYPE =
628 kLongStringTag | kAsciiStringTag | kSymbolTag | kExternalStringTag,
629 SHORT_STRING_TYPE = kShortStringTag | kSeqStringTag,
630 MEDIUM_STRING_TYPE = kMediumStringTag | kSeqStringTag,
631 LONG_STRING_TYPE = kLongStringTag | kSeqStringTag,
632 SHORT_ASCII_STRING_TYPE = kShortStringTag | kAsciiStringTag | kSeqStringTag,
633 MEDIUM_ASCII_STRING_TYPE = kMediumStringTag | kAsciiStringTag | kSeqStringTag,
634 LONG_ASCII_STRING_TYPE = kLongStringTag | kAsciiStringTag | kSeqStringTag,
635 SHORT_CONS_STRING_TYPE = kShortStringTag | kConsStringTag,
636 MEDIUM_CONS_STRING_TYPE = kMediumStringTag | kConsStringTag,
637 LONG_CONS_STRING_TYPE = kLongStringTag | kConsStringTag,
638 SHORT_CONS_ASCII_STRING_TYPE =
639 kShortStringTag | kAsciiStringTag | kConsStringTag,
640 MEDIUM_CONS_ASCII_STRING_TYPE =
641 kMediumStringTag | kAsciiStringTag | kConsStringTag,
642 LONG_CONS_ASCII_STRING_TYPE =
643 kLongStringTag | kAsciiStringTag | kConsStringTag,
644 SHORT_SLICED_STRING_TYPE = kShortStringTag | kSlicedStringTag,
645 MEDIUM_SLICED_STRING_TYPE = kMediumStringTag | kSlicedStringTag,
646 LONG_SLICED_STRING_TYPE = kLongStringTag | kSlicedStringTag,
647 SHORT_SLICED_ASCII_STRING_TYPE =
648 kShortStringTag | kAsciiStringTag | kSlicedStringTag,
649 MEDIUM_SLICED_ASCII_STRING_TYPE =
650 kMediumStringTag | kAsciiStringTag | kSlicedStringTag,
651 LONG_SLICED_ASCII_STRING_TYPE =
652 kLongStringTag | kAsciiStringTag | kSlicedStringTag,
653 SHORT_EXTERNAL_STRING_TYPE = kShortStringTag | kExternalStringTag,
654 MEDIUM_EXTERNAL_STRING_TYPE = kMediumStringTag | kExternalStringTag,
655 LONG_EXTERNAL_STRING_TYPE = kLongStringTag | kExternalStringTag,
656 SHORT_EXTERNAL_ASCII_STRING_TYPE =
657 kShortStringTag | kAsciiStringTag | kExternalStringTag,
658 MEDIUM_EXTERNAL_ASCII_STRING_TYPE =
659 kMediumStringTag | kAsciiStringTag | kExternalStringTag,
660 LONG_EXTERNAL_ASCII_STRING_TYPE =
661 kLongStringTag | kAsciiStringTag | kExternalStringTag,
662 LONG_PRIVATE_EXTERNAL_ASCII_STRING_TYPE = LONG_EXTERNAL_ASCII_STRING_TYPE,
663
664 MAP_TYPE = kNotStringTag,
665 HEAP_NUMBER_TYPE,
666 FIXED_ARRAY_TYPE,
667 CODE_TYPE,
668 ODDBALL_TYPE,
669 JS_GLOBAL_PROPERTY_CELL_TYPE,
670 PROXY_TYPE,
671 BYTE_ARRAY_TYPE,
672 PIXEL_ARRAY_TYPE,
673 FILLER_TYPE,
674 SMI_TYPE,
675
676 ACCESSOR_INFO_TYPE,
677 ACCESS_CHECK_INFO_TYPE,
678 INTERCEPTOR_INFO_TYPE,
679 SHARED_FUNCTION_INFO_TYPE,
680 CALL_HANDLER_INFO_TYPE,
681 FUNCTION_TEMPLATE_INFO_TYPE,
682 OBJECT_TEMPLATE_INFO_TYPE,
683 SIGNATURE_INFO_TYPE,
684 TYPE_SWITCH_INFO_TYPE,
685#ifdef ENABLE_DEBUGGER_SUPPORT
686 DEBUG_INFO_TYPE,
687 BREAK_POINT_INFO_TYPE,
688#endif
689 SCRIPT_TYPE,
690
691 JS_VALUE_TYPE,
692 JS_OBJECT_TYPE,
693 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
694 JS_GLOBAL_OBJECT_TYPE,
695 JS_BUILTINS_OBJECT_TYPE,
696 JS_GLOBAL_PROXY_TYPE,
697 JS_ARRAY_TYPE,
698 JS_REGEXP_TYPE,
699
700 JS_FUNCTION_TYPE,
701
702 // Pseudo-types
703 FIRST_NONSTRING_TYPE = MAP_TYPE,
704 FIRST_TYPE = 0x0,
705 INVALID_TYPE = FIRST_TYPE - 1,
706 LAST_TYPE = JS_FUNCTION_TYPE,
707 // Boundaries for testing the type is a JavaScript "object". Note that
708 // function objects are not counted as objects, even though they are
709 // implemented as such; only values whose typeof is "object" are included.
710 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
711 LAST_JS_OBJECT_TYPE = JS_REGEXP_TYPE
712};
713
714
715enum CompareResult {
716 LESS = -1,
717 EQUAL = 0,
718 GREATER = 1,
719
720 NOT_EQUAL = GREATER
721};
722
723
724#define DECL_BOOLEAN_ACCESSORS(name) \
725 inline bool name(); \
726 inline void set_##name(bool value); \
727
728
729#define DECL_ACCESSORS(name, type) \
730 inline type* name(); \
731 inline void set_##name(type* value, \
732 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
733
734
735class StringStream;
736class ObjectVisitor;
737
738struct ValueInfo : public Malloced {
739 ValueInfo() : type(FIRST_TYPE), ptr(NULL), str(NULL), number(0) { }
740 InstanceType type;
741 Object* ptr;
742 const char* str;
743 double number;
744};
745
746
747// A template-ized version of the IsXXX functions.
748template <class C> static inline bool Is(Object* obj);
749
750
751// Object is the abstract superclass for all classes in the
752// object hierarchy.
753// Object does not use any virtual functions to avoid the
754// allocation of the C++ vtable.
755// Since Smi and Failure are subclasses of Object no
756// data members can be present in Object.
757class Object BASE_EMBEDDED {
758 public:
759 // Type testing.
760 inline bool IsSmi();
761 inline bool IsHeapObject();
762 inline bool IsHeapNumber();
763 inline bool IsString();
764 inline bool IsSymbol();
765#ifdef DEBUG
766 // See objects-inl.h for more details
767 inline bool IsSeqString();
768 inline bool IsSlicedString();
769 inline bool IsExternalString();
770 inline bool IsExternalTwoByteString();
771 inline bool IsExternalAsciiString();
772 inline bool IsSeqTwoByteString();
773 inline bool IsSeqAsciiString();
774#endif // DEBUG
775 inline bool IsConsString();
776
777 inline bool IsNumber();
778 inline bool IsByteArray();
779 inline bool IsPixelArray();
780 inline bool IsFailure();
781 inline bool IsRetryAfterGC();
782 inline bool IsOutOfMemoryFailure();
783 inline bool IsException();
784 inline bool IsJSObject();
785 inline bool IsJSContextExtensionObject();
786 inline bool IsMap();
787 inline bool IsFixedArray();
788 inline bool IsDescriptorArray();
789 inline bool IsContext();
790 inline bool IsCatchContext();
791 inline bool IsGlobalContext();
792 inline bool IsJSFunction();
793 inline bool IsCode();
794 inline bool IsOddball();
795 inline bool IsSharedFunctionInfo();
796 inline bool IsJSValue();
797 inline bool IsStringWrapper();
798 inline bool IsProxy();
799 inline bool IsBoolean();
800 inline bool IsJSArray();
801 inline bool IsJSRegExp();
802 inline bool IsHashTable();
803 inline bool IsDictionary();
804 inline bool IsSymbolTable();
805 inline bool IsCompilationCacheTable();
806 inline bool IsMapCache();
807 inline bool IsPrimitive();
808 inline bool IsGlobalObject();
809 inline bool IsJSGlobalObject();
810 inline bool IsJSBuiltinsObject();
811 inline bool IsJSGlobalProxy();
812 inline bool IsUndetectableObject();
813 inline bool IsAccessCheckNeeded();
814 inline bool IsJSGlobalPropertyCell();
815
816 // Returns true if this object is an instance of the specified
817 // function template.
818 inline bool IsInstanceOf(FunctionTemplateInfo* type);
819
820 inline bool IsStruct();
821#define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
822 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
823#undef DECLARE_STRUCT_PREDICATE
824
825 // Oddball testing.
826 INLINE(bool IsUndefined());
827 INLINE(bool IsTheHole());
828 INLINE(bool IsNull());
829 INLINE(bool IsTrue());
830 INLINE(bool IsFalse());
831
832 // Extract the number.
833 inline double Number();
834
835 inline bool HasSpecificClassOf(String* name);
836
837 Object* ToObject(); // ECMA-262 9.9.
838 Object* ToBoolean(); // ECMA-262 9.2.
839
840 // Convert to a JSObject if needed.
841 // global_context is used when creating wrapper object.
842 Object* ToObject(Context* global_context);
843
844 // Converts this to a Smi if possible.
845 // Failure is returned otherwise.
846 inline Object* ToSmi();
847
848 void Lookup(String* name, LookupResult* result);
849
850 // Property access.
851 inline Object* GetProperty(String* key);
852 inline Object* GetProperty(String* key, PropertyAttributes* attributes);
853 Object* GetPropertyWithReceiver(Object* receiver,
854 String* key,
855 PropertyAttributes* attributes);
856 Object* GetProperty(Object* receiver,
857 LookupResult* result,
858 String* key,
859 PropertyAttributes* attributes);
860 Object* GetPropertyWithCallback(Object* receiver,
861 Object* structure,
862 String* name,
863 Object* holder);
864 Object* GetPropertyWithDefinedGetter(Object* receiver,
865 JSFunction* getter);
866
867 inline Object* GetElement(uint32_t index);
868 Object* GetElementWithReceiver(Object* receiver, uint32_t index);
869
870 // Return the object's prototype (might be Heap::null_value()).
871 Object* GetPrototype();
872
873 // Returns true if this is a JSValue containing a string and the index is
874 // < the length of the string. Used to implement [] on strings.
875 inline bool IsStringObjectWithCharacterAt(uint32_t index);
876
877#ifdef DEBUG
878 // Prints this object with details.
879 void Print();
880 void PrintLn();
881 // Verifies the object.
882 void Verify();
883
884 // Verify a pointer is a valid object pointer.
885 static void VerifyPointer(Object* p);
886#endif
887
888 // Prints this object without details.
889 void ShortPrint();
890
891 // Prints this object without details to a message accumulator.
892 void ShortPrint(StringStream* accumulator);
893
894 // Casting: This cast is only needed to satisfy macros in objects-inl.h.
895 static Object* cast(Object* value) { return value; }
896
897 // Layout description.
898 static const int kHeaderSize = 0; // Object does not take up any space.
899
900 private:
901 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
902};
903
904
905// Smi represents integer Numbers that can be stored in 31 bits.
906// Smis are immediate which means they are NOT allocated in the heap.
907// Smi stands for small integer.
908// The this pointer has the following format: [31 bit signed int] 0
909// On 64-bit, the top 32 bits of the pointer is allowed to have any
910// value.
911class Smi: public Object {
912 public:
913 // Returns the integer value.
914 inline int value();
915
916 // Convert a value to a Smi object.
917 static inline Smi* FromInt(int value);
918
919 static inline Smi* FromIntptr(intptr_t value);
920
921 // Returns whether value can be represented in a Smi.
922 static inline bool IsValid(intptr_t value);
923
924 static inline bool IsIntptrValid(intptr_t);
925
926 // Casting.
927 static inline Smi* cast(Object* object);
928
929 // Dispatched behavior.
930 void SmiPrint();
931 void SmiPrint(StringStream* accumulator);
932#ifdef DEBUG
933 void SmiVerify();
934#endif
935
936 static const int kSmiNumBits = 31;
937 // Min and max limits for Smi values.
938 static const int kMinValue = -(1 << (kSmiNumBits - 1));
939 static const int kMaxValue = (1 << (kSmiNumBits - 1)) - 1;
940
941 private:
942 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
943};
944
945
946// Failure is used for reporting out of memory situations and
947// propagating exceptions through the runtime system. Failure objects
948// are transient and cannot occur as part of the object graph.
949//
950// Failures are a single word, encoded as follows:
951// +-------------------------+---+--+--+
952// |rrrrrrrrrrrrrrrrrrrrrrrrr|sss|tt|11|
953// +-------------------------+---+--+--+
954// 3 7 6 4 32 10
955// 1
956//
957// The low two bits, 0-1, are the failure tag, 11. The next two bits,
958// 2-3, are a failure type tag 'tt' with possible values:
959// 00 RETRY_AFTER_GC
960// 01 EXCEPTION
961// 10 INTERNAL_ERROR
962// 11 OUT_OF_MEMORY_EXCEPTION
963//
964// The next three bits, 4-6, are an allocation space tag 'sss'. The
965// allocation space tag is 000 for all failure types except
966// RETRY_AFTER_GC. For RETRY_AFTER_GC, the possible values are the
967// allocation spaces (the encoding is found in globals.h).
968//
969// The remaining bits is the size of the allocation request in units
970// of the pointer size, and is zeroed except for RETRY_AFTER_GC
971// failures. The 25 bits (on a 32 bit platform) gives a representable
972// range of 2^27 bytes (128MB).
973
974// Failure type tag info.
975const int kFailureTypeTagSize = 2;
976const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
977
978class Failure: public Object {
979 public:
980 // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
981 enum Type {
982 RETRY_AFTER_GC = 0,
983 EXCEPTION = 1, // Returning this marker tells the real exception
984 // is in Top::pending_exception.
985 INTERNAL_ERROR = 2,
986 OUT_OF_MEMORY_EXCEPTION = 3
987 };
988
989 inline Type type() const;
990
991 // Returns the space that needs to be collected for RetryAfterGC failures.
992 inline AllocationSpace allocation_space() const;
993
994 // Returns the number of bytes requested (up to the representable maximum)
995 // for RetryAfterGC failures.
996 inline int requested() const;
997
998 inline bool IsInternalError() const;
999 inline bool IsOutOfMemoryException() const;
1000
1001 static Failure* RetryAfterGC(int requested_bytes, AllocationSpace space);
1002 static inline Failure* RetryAfterGC(int requested_bytes); // NEW_SPACE
1003 static inline Failure* Exception();
1004 static inline Failure* InternalError();
1005 static inline Failure* OutOfMemoryException();
1006 // Casting.
1007 static inline Failure* cast(Object* object);
1008
1009 // Dispatched behavior.
1010 void FailurePrint();
1011 void FailurePrint(StringStream* accumulator);
1012#ifdef DEBUG
1013 void FailureVerify();
1014#endif
1015
1016 private:
1017 inline int value() const;
1018 static inline Failure* Construct(Type type, int value = 0);
1019
1020 DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1021};
1022
1023
1024// Heap objects typically have a map pointer in their first word. However,
1025// during GC other data (eg, mark bits, forwarding addresses) is sometimes
1026// encoded in the first word. The class MapWord is an abstraction of the
1027// value in a heap object's first word.
1028class MapWord BASE_EMBEDDED {
1029 public:
1030 // Normal state: the map word contains a map pointer.
1031
1032 // Create a map word from a map pointer.
1033 static inline MapWord FromMap(Map* map);
1034
1035 // View this map word as a map pointer.
1036 inline Map* ToMap();
1037
1038
1039 // Scavenge collection: the map word of live objects in the from space
1040 // contains a forwarding address (a heap object pointer in the to space).
1041
1042 // True if this map word is a forwarding address for a scavenge
1043 // collection. Only valid during a scavenge collection (specifically,
1044 // when all map words are heap object pointers, ie. not during a full GC).
1045 inline bool IsForwardingAddress();
1046
1047 // Create a map word from a forwarding address.
1048 static inline MapWord FromForwardingAddress(HeapObject* object);
1049
1050 // View this map word as a forwarding address.
1051 inline HeapObject* ToForwardingAddress();
1052
1053
1054 // Marking phase of full collection: the map word of live objects is
1055 // marked, and may be marked as overflowed (eg, the object is live, its
1056 // children have not been visited, and it does not fit in the marking
1057 // stack).
1058
1059 // True if this map word's mark bit is set.
1060 inline bool IsMarked();
1061
1062 // Return this map word but with its mark bit set.
1063 inline void SetMark();
1064
1065 // Return this map word but with its mark bit cleared.
1066 inline void ClearMark();
1067
1068 // True if this map word's overflow bit is set.
1069 inline bool IsOverflowed();
1070
1071 // Return this map word but with its overflow bit set.
1072 inline void SetOverflow();
1073
1074 // Return this map word but with its overflow bit cleared.
1075 inline void ClearOverflow();
1076
1077
1078 // Compacting phase of a full compacting collection: the map word of live
1079 // objects contains an encoding of the original map address along with the
1080 // forwarding address (represented as an offset from the first live object
1081 // in the same page as the (old) object address).
1082
1083 // Create a map word from a map address and a forwarding address offset.
1084 static inline MapWord EncodeAddress(Address map_address, int offset);
1085
1086 // Return the map address encoded in this map word.
1087 inline Address DecodeMapAddress(MapSpace* map_space);
1088
1089 // Return the forwarding offset encoded in this map word.
1090 inline int DecodeOffset();
1091
1092
1093 // During serialization: the map word is used to hold an encoded
1094 // address, and possibly a mark bit (set and cleared with SetMark
1095 // and ClearMark).
1096
1097 // Create a map word from an encoded address.
1098 static inline MapWord FromEncodedAddress(Address address);
1099
1100 inline Address ToEncodedAddress();
1101
1102 // Bits used by the marking phase of the garbage collector.
1103 //
1104 // The first word of a heap object is normally a map pointer. The last two
1105 // bits are tagged as '01' (kHeapObjectTag). We reuse the last two bits to
1106 // mark an object as live and/or overflowed:
1107 // last bit = 0, marked as alive
1108 // second bit = 1, overflowed
1109 // An object is only marked as overflowed when it is marked as live while
1110 // the marking stack is overflowed.
1111 static const int kMarkingBit = 0; // marking bit
1112 static const int kMarkingMask = (1 << kMarkingBit); // marking mask
1113 static const int kOverflowBit = 1; // overflow bit
1114 static const int kOverflowMask = (1 << kOverflowBit); // overflow mask
1115
1116 // Forwarding pointers and map pointer encoding
1117 // 31 21 20 10 9 0
1118 // +-----------------+------------------+-----------------+
1119 // |forwarding offset|page offset of map|page index of map|
1120 // +-----------------+------------------+-----------------+
1121 // 11 bits 11 bits 10 bits
1122 static const int kMapPageIndexBits = 10;
1123 static const int kMapPageOffsetBits = 11;
1124 static const int kForwardingOffsetBits = 11;
1125
1126 static const int kMapPageIndexShift = 0;
1127 static const int kMapPageOffsetShift =
1128 kMapPageIndexShift + kMapPageIndexBits;
1129 static const int kForwardingOffsetShift =
1130 kMapPageOffsetShift + kMapPageOffsetBits;
1131
1132 // 0x000003FF
1133 static const uint32_t kMapPageIndexMask =
1134 (1 << kMapPageOffsetShift) - 1;
1135
1136 // 0x001FFC00
1137 static const uint32_t kMapPageOffsetMask =
1138 ((1 << kForwardingOffsetShift) - 1) & ~kMapPageIndexMask;
1139
1140 // 0xFFE00000
1141 static const uint32_t kForwardingOffsetMask =
1142 ~(kMapPageIndexMask | kMapPageOffsetMask);
1143
1144 private:
1145 // HeapObject calls the private constructor and directly reads the value.
1146 friend class HeapObject;
1147
1148 explicit MapWord(uintptr_t value) : value_(value) {}
1149
1150 uintptr_t value_;
1151};
1152
1153
1154// HeapObject is the superclass for all classes describing heap allocated
1155// objects.
1156class HeapObject: public Object {
1157 public:
1158 // [map]: Contains a map which contains the object's reflective
1159 // information.
1160 inline Map* map();
1161 inline void set_map(Map* value);
1162
1163 // During garbage collection, the map word of a heap object does not
1164 // necessarily contain a map pointer.
1165 inline MapWord map_word();
1166 inline void set_map_word(MapWord map_word);
1167
1168 // Converts an address to a HeapObject pointer.
1169 static inline HeapObject* FromAddress(Address address);
1170
1171 // Returns the address of this HeapObject.
1172 inline Address address();
1173
1174 // Iterates over pointers contained in the object (including the Map)
1175 void Iterate(ObjectVisitor* v);
1176
1177 // Iterates over all pointers contained in the object except the
1178 // first map pointer. The object type is given in the first
1179 // parameter. This function does not access the map pointer in the
1180 // object, and so is safe to call while the map pointer is modified.
1181 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1182
1183 // This method only applies to struct objects. Iterates over all the fields
1184 // of this struct.
1185 void IterateStructBody(int object_size, ObjectVisitor* v);
1186
1187 // Returns the heap object's size in bytes
1188 inline int Size();
1189
1190 // Given a heap object's map pointer, returns the heap size in bytes
1191 // Useful when the map pointer field is used for other purposes.
1192 // GC internal.
1193 inline int SizeFromMap(Map* map);
1194
1195 // Support for the marking heap objects during the marking phase of GC.
1196 // True if the object is marked live.
1197 inline bool IsMarked();
1198
1199 // Mutate this object's map pointer to indicate that the object is live.
1200 inline void SetMark();
1201
1202 // Mutate this object's map pointer to remove the indication that the
1203 // object is live (ie, partially restore the map pointer).
1204 inline void ClearMark();
1205
1206 // True if this object is marked as overflowed. Overflowed objects have
1207 // been reached and marked during marking of the heap, but their children
1208 // have not necessarily been marked and they have not been pushed on the
1209 // marking stack.
1210 inline bool IsOverflowed();
1211
1212 // Mutate this object's map pointer to indicate that the object is
1213 // overflowed.
1214 inline void SetOverflow();
1215
1216 // Mutate this object's map pointer to remove the indication that the
1217 // object is overflowed (ie, partially restore the map pointer).
1218 inline void ClearOverflow();
1219
1220 // Returns the field at offset in obj, as a read/write Object* reference.
1221 // Does no checking, and is safe to use during GC, while maps are invalid.
1222 // Does not update remembered sets, so should only be assigned to
1223 // during marking GC.
1224 static inline Object** RawField(HeapObject* obj, int offset);
1225
1226 // Casting.
1227 static inline HeapObject* cast(Object* obj);
1228
1229 // Return the write barrier mode for this.
1230 inline WriteBarrierMode GetWriteBarrierMode();
1231
1232 // Dispatched behavior.
1233 void HeapObjectShortPrint(StringStream* accumulator);
1234#ifdef DEBUG
1235 void HeapObjectPrint();
1236 void HeapObjectVerify();
1237 inline void VerifyObjectField(int offset);
1238
1239 void PrintHeader(const char* id);
1240
1241 // Verify a pointer is a valid HeapObject pointer that points to object
1242 // areas in the heap.
1243 static void VerifyHeapPointer(Object* p);
1244#endif
1245
1246 // Layout description.
1247 // First field in a heap object is map.
1248 static const int kMapOffset = Object::kHeaderSize;
1249 static const int kHeaderSize = kMapOffset + kPointerSize;
1250
1251 STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1252
1253 protected:
1254 // helpers for calling an ObjectVisitor to iterate over pointers in the
1255 // half-open range [start, end) specified as integer offsets
1256 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1257 // as above, for the single element at "offset"
1258 inline void IteratePointer(ObjectVisitor* v, int offset);
1259
1260 // Computes the object size from the map.
1261 // Should only be used from SizeFromMap.
1262 int SlowSizeFromMap(Map* map);
1263
1264 private:
1265 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1266};
1267
1268
1269// The HeapNumber class describes heap allocated numbers that cannot be
1270// represented in a Smi (small integer)
1271class HeapNumber: public HeapObject {
1272 public:
1273 // [value]: number value.
1274 inline double value();
1275 inline void set_value(double value);
1276
1277 // Casting.
1278 static inline HeapNumber* cast(Object* obj);
1279
1280 // Dispatched behavior.
1281 Object* HeapNumberToBoolean();
1282 void HeapNumberPrint();
1283 void HeapNumberPrint(StringStream* accumulator);
1284#ifdef DEBUG
1285 void HeapNumberVerify();
1286#endif
1287
1288 // Layout description.
1289 static const int kValueOffset = HeapObject::kHeaderSize;
1290 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1291 // is a mixture of sign, exponent and mantissa. Our current platforms are all
1292 // little endian apart from non-EABI arm which is little endian with big
1293 // endian floating point word ordering!
1294#if !defined(V8_HOST_ARCH_ARM) || __ARM_EABI__
1295 static const int kMantissaOffset = kValueOffset;
1296 static const int kExponentOffset = kValueOffset + 4;
1297#else
1298 static const int kMantissaOffset = kValueOffset + 4;
1299 static const int kExponentOffset = kValueOffset;
1300# define BIG_ENDIAN_FLOATING_POINT 1
1301#endif
1302 static const int kSize = kValueOffset + kDoubleSize;
1303
1304 static const uint32_t kSignMask = 0x80000000u;
1305 static const uint32_t kExponentMask = 0x7ff00000u;
1306 static const uint32_t kMantissaMask = 0xfffffu;
1307 static const int kExponentBias = 1023;
1308 static const int kExponentShift = 20;
1309 static const int kMantissaBitsInTopWord = 20;
1310 static const int kNonMantissaBitsInTopWord = 12;
1311
1312 private:
1313 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1314};
1315
1316
1317// The JSObject describes real heap allocated JavaScript objects with
1318// properties.
1319// Note that the map of JSObject changes during execution to enable inline
1320// caching.
1321class JSObject: public HeapObject {
1322 public:
1323 enum DeleteMode { NORMAL_DELETION, FORCE_DELETION };
1324 enum ElementsKind {
1325 FAST_ELEMENTS,
1326 DICTIONARY_ELEMENTS,
1327 PIXEL_ELEMENTS
1328 };
1329
1330 // [properties]: Backing storage for properties.
1331 // properties is a FixedArray in the fast case, and a Dictionary in the
1332 // slow case.
1333 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1334 inline void initialize_properties();
1335 inline bool HasFastProperties();
1336 inline StringDictionary* property_dictionary(); // Gets slow properties.
1337
1338 // [elements]: The elements (properties with names that are integers).
1339 // elements is a FixedArray in the fast case, and a Dictionary in the slow
1340 // case or a PixelArray in a special case.
1341 DECL_ACCESSORS(elements, Array) // Get and set fast elements.
1342 inline void initialize_elements();
1343 inline ElementsKind GetElementsKind();
1344 inline bool HasFastElements();
1345 inline bool HasDictionaryElements();
1346 inline bool HasPixelElements();
1347 inline NumberDictionary* element_dictionary(); // Gets slow elements.
1348
1349 // Collects elements starting at index 0.
1350 // Undefined values are placed after non-undefined values.
1351 // Returns the number of non-undefined values.
1352 Object* PrepareElementsForSort(uint32_t limit);
1353 // As PrepareElementsForSort, but only on objects where elements is
1354 // a dictionary, and it will stay a dictionary.
1355 Object* PrepareSlowElementsForSort(uint32_t limit);
1356
1357 Object* SetProperty(String* key,
1358 Object* value,
1359 PropertyAttributes attributes);
1360 Object* SetProperty(LookupResult* result,
1361 String* key,
1362 Object* value,
1363 PropertyAttributes attributes);
1364 Object* SetPropertyWithFailedAccessCheck(LookupResult* result,
1365 String* name,
1366 Object* value);
1367 Object* SetPropertyWithCallback(Object* structure,
1368 String* name,
1369 Object* value,
1370 JSObject* holder);
1371 Object* SetPropertyWithDefinedSetter(JSFunction* setter,
1372 Object* value);
1373 Object* SetPropertyWithInterceptor(String* name,
1374 Object* value,
1375 PropertyAttributes attributes);
1376 Object* SetPropertyPostInterceptor(String* name,
1377 Object* value,
1378 PropertyAttributes attributes);
1379 Object* IgnoreAttributesAndSetLocalProperty(String* key,
1380 Object* value,
1381 PropertyAttributes attributes);
1382
1383 // Retrieve a value in a normalized object given a lookup result.
1384 // Handles the special representation of JS global objects.
1385 Object* GetNormalizedProperty(LookupResult* result);
1386
1387 // Sets the property value in a normalized object given a lookup result.
1388 // Handles the special representation of JS global objects.
1389 Object* SetNormalizedProperty(LookupResult* result, Object* value);
1390
1391 // Sets the property value in a normalized object given (key, value, details).
1392 // Handles the special representation of JS global objects.
1393 Object* SetNormalizedProperty(String* name,
1394 Object* value,
1395 PropertyDetails details);
1396
1397 // Deletes the named property in a normalized object.
1398 Object* DeleteNormalizedProperty(String* name, DeleteMode mode);
1399
1400 // Sets a property that currently has lazy loading.
1401 Object* SetLazyProperty(LookupResult* result,
1402 String* name,
1403 Object* value,
1404 PropertyAttributes attributes);
1405
1406 // Returns the class name ([[Class]] property in the specification).
1407 String* class_name();
1408
1409 // Returns the constructor name (the name (possibly, inferred name) of the
1410 // function that was used to instantiate the object).
1411 String* constructor_name();
1412
1413 // Retrieve interceptors.
1414 InterceptorInfo* GetNamedInterceptor();
1415 InterceptorInfo* GetIndexedInterceptor();
1416
1417 inline PropertyAttributes GetPropertyAttribute(String* name);
1418 PropertyAttributes GetPropertyAttributeWithReceiver(JSObject* receiver,
1419 String* name);
1420 PropertyAttributes GetLocalPropertyAttribute(String* name);
1421
1422 Object* DefineAccessor(String* name, bool is_getter, JSFunction* fun,
1423 PropertyAttributes attributes);
1424 Object* LookupAccessor(String* name, bool is_getter);
1425
1426 // Used from Object::GetProperty().
1427 Object* GetPropertyWithFailedAccessCheck(Object* receiver,
1428 LookupResult* result,
1429 String* name,
1430 PropertyAttributes* attributes);
1431 Object* GetPropertyWithInterceptor(JSObject* receiver,
1432 String* name,
1433 PropertyAttributes* attributes);
1434 Object* GetPropertyPostInterceptor(JSObject* receiver,
1435 String* name,
1436 PropertyAttributes* attributes);
1437 Object* GetLazyProperty(Object* receiver,
1438 LookupResult* result,
1439 String* name,
1440 PropertyAttributes* attributes);
1441
1442 // Tells whether this object needs to be loaded.
1443 inline bool IsLoaded();
1444
1445 // Returns true if this is an instance of an api function and has
1446 // been modified since it was created. May give false positives.
1447 bool IsDirty();
1448
1449 bool HasProperty(String* name) {
1450 return GetPropertyAttribute(name) != ABSENT;
1451 }
1452
1453 // Can cause a GC if it hits an interceptor.
1454 bool HasLocalProperty(String* name) {
1455 return GetLocalPropertyAttribute(name) != ABSENT;
1456 }
1457
1458 Object* DeleteProperty(String* name, DeleteMode mode);
1459 Object* DeleteElement(uint32_t index, DeleteMode mode);
1460 Object* DeleteLazyProperty(LookupResult* result,
1461 String* name,
1462 DeleteMode mode);
1463
1464 // Tests for the fast common case for property enumeration.
1465 bool IsSimpleEnum();
1466
1467 // Do we want to keep the elements in fast case when increasing the
1468 // capacity?
1469 bool ShouldConvertToSlowElements(int new_capacity);
1470 // Returns true if the backing storage for the slow-case elements of
1471 // this object takes up nearly as much space as a fast-case backing
1472 // storage would. In that case the JSObject should have fast
1473 // elements.
1474 bool ShouldConvertToFastElements();
1475
1476 // Return the object's prototype (might be Heap::null_value()).
1477 inline Object* GetPrototype();
1478
1479 // Tells whether the index'th element is present.
1480 inline bool HasElement(uint32_t index);
1481 bool HasElementWithReceiver(JSObject* receiver, uint32_t index);
1482 bool HasLocalElement(uint32_t index);
1483
1484 bool HasElementWithInterceptor(JSObject* receiver, uint32_t index);
1485 bool HasElementPostInterceptor(JSObject* receiver, uint32_t index);
1486
1487 Object* SetFastElement(uint32_t index, Object* value);
1488
1489 // Set the index'th array element.
1490 // A Failure object is returned if GC is needed.
1491 Object* SetElement(uint32_t index, Object* value);
1492
1493 // Returns the index'th element.
1494 // The undefined object if index is out of bounds.
1495 Object* GetElementWithReceiver(JSObject* receiver, uint32_t index);
1496
1497 void SetFastElements(FixedArray* elements);
1498 Object* SetSlowElements(Object* length);
1499
1500 // Lookup interceptors are used for handling properties controlled by host
1501 // objects.
1502 inline bool HasNamedInterceptor();
1503 inline bool HasIndexedInterceptor();
1504
1505 // Support functions for v8 api (needed for correct interceptor behavior).
1506 bool HasRealNamedProperty(String* key);
1507 bool HasRealElementProperty(uint32_t index);
1508 bool HasRealNamedCallbackProperty(String* key);
1509
1510 // Initializes the array to a certain length
1511 Object* SetElementsLength(Object* length);
1512
1513 // Get the header size for a JSObject. Used to compute the index of
1514 // internal fields as well as the number of internal fields.
1515 inline int GetHeaderSize();
1516
1517 inline int GetInternalFieldCount();
1518 inline Object* GetInternalField(int index);
1519 inline void SetInternalField(int index, Object* value);
1520
1521 // Lookup a property. If found, the result is valid and has
1522 // detailed information.
1523 void LocalLookup(String* name, LookupResult* result);
1524 void Lookup(String* name, LookupResult* result);
1525
1526 // The following lookup functions skip interceptors.
1527 void LocalLookupRealNamedProperty(String* name, LookupResult* result);
1528 void LookupRealNamedProperty(String* name, LookupResult* result);
1529 void LookupRealNamedPropertyInPrototypes(String* name, LookupResult* result);
1530 void LookupCallbackSetterInPrototypes(String* name, LookupResult* result);
1531 Object* LookupCallbackSetterInPrototypes(uint32_t index);
1532 void LookupCallback(String* name, LookupResult* result);
1533
1534 // Returns the number of properties on this object filtering out properties
1535 // with the specified attributes (ignoring interceptors).
1536 int NumberOfLocalProperties(PropertyAttributes filter);
1537 // Returns the number of enumerable properties (ignoring interceptors).
1538 int NumberOfEnumProperties();
1539 // Fill in details for properties into storage starting at the specified
1540 // index.
1541 void GetLocalPropertyNames(FixedArray* storage, int index);
1542
1543 // Returns the number of properties on this object filtering out properties
1544 // with the specified attributes (ignoring interceptors).
1545 int NumberOfLocalElements(PropertyAttributes filter);
1546 // Returns the number of enumerable elements (ignoring interceptors).
1547 int NumberOfEnumElements();
1548 // Returns the number of elements on this object filtering out elements
1549 // with the specified attributes (ignoring interceptors).
1550 int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
1551 // Count and fill in the enumerable elements into storage.
1552 // (storage->length() == NumberOfEnumElements()).
1553 // If storage is NULL, will count the elements without adding
1554 // them to any storage.
1555 // Returns the number of enumerable elements.
1556 int GetEnumElementKeys(FixedArray* storage);
1557
1558 // Add a property to a fast-case object using a map transition to
1559 // new_map.
1560 Object* AddFastPropertyUsingMap(Map* new_map,
1561 String* name,
1562 Object* value);
1563
1564 // Add a constant function property to a fast-case object.
1565 // This leaves a CONSTANT_TRANSITION in the old map, and
1566 // if it is called on a second object with this map, a
1567 // normal property is added instead, with a map transition.
1568 // This avoids the creation of many maps with the same constant
1569 // function, all orphaned.
1570 Object* AddConstantFunctionProperty(String* name,
1571 JSFunction* function,
1572 PropertyAttributes attributes);
1573
1574 Object* ReplaceSlowProperty(String* name,
1575 Object* value,
1576 PropertyAttributes attributes);
1577
1578 // Converts a descriptor of any other type to a real field,
1579 // backed by the properties array. Descriptors of visible
1580 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1581 // Converts the descriptor on the original object's map to a
1582 // map transition, and the the new field is on the object's new map.
1583 Object* ConvertDescriptorToFieldAndMapTransition(
1584 String* name,
1585 Object* new_value,
1586 PropertyAttributes attributes);
1587
1588 // Converts a descriptor of any other type to a real field,
1589 // backed by the properties array. Descriptors of visible
1590 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1591 Object* ConvertDescriptorToField(String* name,
1592 Object* new_value,
1593 PropertyAttributes attributes);
1594
1595 // Add a property to a fast-case object.
1596 Object* AddFastProperty(String* name,
1597 Object* value,
1598 PropertyAttributes attributes);
1599
1600 // Add a property to a slow-case object.
1601 Object* AddSlowProperty(String* name,
1602 Object* value,
1603 PropertyAttributes attributes);
1604
1605 // Add a property to an object.
1606 Object* AddProperty(String* name,
1607 Object* value,
1608 PropertyAttributes attributes);
1609
1610 // Convert the object to use the canonical dictionary
1611 // representation. If the object is expected to have additional properties
1612 // added this number can be indicated to have the backing store allocated to
1613 // an initial capacity for holding these properties.
1614 Object* NormalizeProperties(PropertyNormalizationMode mode,
1615 int expected_additional_properties);
1616 Object* NormalizeElements();
1617
1618 // Transform slow named properties to fast variants.
1619 // Returns failure if allocation failed.
1620 Object* TransformToFastProperties(int unused_property_fields);
1621
1622 // Access fast-case object properties at index.
1623 inline Object* FastPropertyAt(int index);
1624 inline Object* FastPropertyAtPut(int index, Object* value);
1625
1626 // Access to in object properties.
1627 inline Object* InObjectPropertyAt(int index);
1628 inline Object* InObjectPropertyAtPut(int index,
1629 Object* value,
1630 WriteBarrierMode mode
1631 = UPDATE_WRITE_BARRIER);
1632
1633 // initializes the body after properties slot, properties slot is
1634 // initialized by set_properties
1635 // Note: this call does not update write barrier, it is caller's
1636 // reponsibility to ensure that *v* can be collected without WB here.
1637 inline void InitializeBody(int object_size);
1638
1639 // Check whether this object references another object
1640 bool ReferencesObject(Object* obj);
1641
1642 // Casting.
1643 static inline JSObject* cast(Object* obj);
1644
1645 // Dispatched behavior.
1646 void JSObjectIterateBody(int object_size, ObjectVisitor* v);
1647 void JSObjectShortPrint(StringStream* accumulator);
1648#ifdef DEBUG
1649 void JSObjectPrint();
1650 void JSObjectVerify();
1651 void PrintProperties();
1652 void PrintElements();
1653
1654 // Structure for collecting spill information about JSObjects.
1655 class SpillInformation {
1656 public:
1657 void Clear();
1658 void Print();
1659 int number_of_objects_;
1660 int number_of_objects_with_fast_properties_;
1661 int number_of_objects_with_fast_elements_;
1662 int number_of_fast_used_fields_;
1663 int number_of_fast_unused_fields_;
1664 int number_of_slow_used_properties_;
1665 int number_of_slow_unused_properties_;
1666 int number_of_fast_used_elements_;
1667 int number_of_fast_unused_elements_;
1668 int number_of_slow_used_elements_;
1669 int number_of_slow_unused_elements_;
1670 };
1671
1672 void IncrementSpillStatistics(SpillInformation* info);
1673#endif
1674 Object* SlowReverseLookup(Object* value);
1675
1676 static const uint32_t kMaxGap = 1024;
1677 static const int kMaxFastElementsLength = 5000;
1678 static const int kInitialMaxFastElementArray = 100000;
1679 static const int kMaxFastProperties = 8;
1680 static const int kMaxInstanceSize = 255 * kPointerSize;
1681 // When extending the backing storage for property values, we increase
1682 // its size by more than the 1 entry necessary, so sequentially adding fields
1683 // to the same object requires fewer allocations and copies.
1684 static const int kFieldsAdded = 3;
1685
1686 // Layout description.
1687 static const int kPropertiesOffset = HeapObject::kHeaderSize;
1688 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
1689 static const int kHeaderSize = kElementsOffset + kPointerSize;
1690
1691 STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
1692
1693 Object* GetElementWithInterceptor(JSObject* receiver, uint32_t index);
1694
1695 private:
1696 Object* SetElementWithInterceptor(uint32_t index, Object* value);
1697 Object* SetElementWithoutInterceptor(uint32_t index, Object* value);
1698
1699 Object* GetElementPostInterceptor(JSObject* receiver, uint32_t index);
1700
1701 Object* DeletePropertyPostInterceptor(String* name, DeleteMode mode);
1702 Object* DeletePropertyWithInterceptor(String* name);
1703
1704 Object* DeleteElementPostInterceptor(uint32_t index, DeleteMode mode);
1705 Object* DeleteElementWithInterceptor(uint32_t index);
1706
1707 PropertyAttributes GetPropertyAttributePostInterceptor(JSObject* receiver,
1708 String* name,
1709 bool continue_search);
1710 PropertyAttributes GetPropertyAttributeWithInterceptor(JSObject* receiver,
1711 String* name,
1712 bool continue_search);
1713 PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
1714 Object* receiver,
1715 LookupResult* result,
1716 String* name,
1717 bool continue_search);
1718 PropertyAttributes GetPropertyAttribute(JSObject* receiver,
1719 LookupResult* result,
1720 String* name,
1721 bool continue_search);
1722
1723 // Returns true if most of the elements backing storage is used.
1724 bool HasDenseElements();
1725
1726 Object* DefineGetterSetter(String* name, PropertyAttributes attributes);
1727
1728 void LookupInDescriptor(String* name, LookupResult* result);
1729
1730 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
1731};
1732
1733
1734// Abstract super class arrays. It provides length behavior.
1735class Array: public HeapObject {
1736 public:
1737 // [length]: length of the array.
1738 inline int length();
1739 inline void set_length(int value);
1740
1741 // Convert an object to an array index.
1742 // Returns true if the conversion succeeded.
1743 static inline bool IndexFromObject(Object* object, uint32_t* index);
1744
1745 // Layout descriptor.
1746 static const int kLengthOffset = HeapObject::kHeaderSize;
1747
1748 protected:
1749 // No code should use the Array class directly, only its subclasses.
1750 // Use the kHeaderSize of the appropriate subclass, which may be aligned.
1751 static const int kHeaderSize = kLengthOffset + kIntSize;
1752 static const int kAlignedSize = POINTER_SIZE_ALIGN(kHeaderSize);
1753
1754 private:
1755 DISALLOW_IMPLICIT_CONSTRUCTORS(Array);
1756};
1757
1758
1759// FixedArray describes fixed sized arrays where element
1760// type is Object*.
1761
1762class FixedArray: public Array {
1763 public:
1764
1765 // Setter and getter for elements.
1766 inline Object* get(int index);
1767 // Setter that uses write barrier.
1768 inline void set(int index, Object* value);
1769
1770 // Setter that doesn't need write barrier).
1771 inline void set(int index, Smi* value);
1772 // Setter with explicit barrier mode.
1773 inline void set(int index, Object* value, WriteBarrierMode mode);
1774
1775 // Setters for frequently used oddballs located in old space.
1776 inline void set_undefined(int index);
1777 inline void set_null(int index);
1778 inline void set_the_hole(int index);
1779
1780 // Copy operations.
1781 inline Object* Copy();
1782 Object* CopySize(int new_length);
1783
1784 // Add the elements of a JSArray to this FixedArray.
1785 Object* AddKeysFromJSArray(JSArray* array);
1786
1787 // Compute the union of this and other.
1788 Object* UnionOfKeys(FixedArray* other);
1789
1790 // Copy a sub array from the receiver to dest.
1791 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
1792
1793 // Garbage collection support.
1794 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
1795
1796 // Code Generation support.
1797 static int OffsetOfElementAt(int index) { return SizeFor(index); }
1798
1799 // Casting.
1800 static inline FixedArray* cast(Object* obj);
1801
1802 // Align data at kPointerSize, even if Array.kHeaderSize isn't aligned.
1803 static const int kHeaderSize = POINTER_SIZE_ALIGN(Array::kHeaderSize);
1804
1805 // Dispatched behavior.
1806 int FixedArraySize() { return SizeFor(length()); }
1807 void FixedArrayIterateBody(ObjectVisitor* v);
1808#ifdef DEBUG
1809 void FixedArrayPrint();
1810 void FixedArrayVerify();
1811 // Checks if two FixedArrays have identical contents.
1812 bool IsEqualTo(FixedArray* other);
1813#endif
1814
1815 // Swap two elements in a pair of arrays. If this array and the
1816 // numbers array are the same object, the elements are only swapped
1817 // once.
1818 void SwapPairs(FixedArray* numbers, int i, int j);
1819
1820 // Sort prefix of this array and the numbers array as pairs wrt. the
1821 // numbers. If the numbers array and the this array are the same
1822 // object, the prefix of this array is sorted.
1823 void SortPairs(FixedArray* numbers, uint32_t len);
1824
1825 protected:
1826 // Set operation on FixedArray without using write barriers.
1827 static inline void fast_set(FixedArray* array, int index, Object* value);
1828
1829 private:
1830 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
1831};
1832
1833
1834// DescriptorArrays are fixed arrays used to hold instance descriptors.
1835// The format of the these objects is:
1836// [0]: point to a fixed array with (value, detail) pairs.
1837// [1]: next enumeration index (Smi), or pointer to small fixed array:
1838// [0]: next enumeration index (Smi)
1839// [1]: pointer to fixed array with enum cache
1840// [2]: first key
1841// [length() - 1]: last key
1842//
1843class DescriptorArray: public FixedArray {
1844 public:
1845 // Is this the singleton empty_descriptor_array?
1846 inline bool IsEmpty();
1847 // Returns the number of descriptors in the array.
1848 int number_of_descriptors() {
1849 return IsEmpty() ? 0 : length() - kFirstIndex;
1850 }
1851
1852 int NextEnumerationIndex() {
1853 if (IsEmpty()) return PropertyDetails::kInitialIndex;
1854 Object* obj = get(kEnumerationIndexIndex);
1855 if (obj->IsSmi()) {
1856 return Smi::cast(obj)->value();
1857 } else {
1858 Object* index = FixedArray::cast(obj)->get(kEnumCacheBridgeEnumIndex);
1859 return Smi::cast(index)->value();
1860 }
1861 }
1862
1863 // Set next enumeration index and flush any enum cache.
1864 void SetNextEnumerationIndex(int value) {
1865 if (!IsEmpty()) {
1866 fast_set(this, kEnumerationIndexIndex, Smi::FromInt(value));
1867 }
1868 }
1869 bool HasEnumCache() {
1870 return !IsEmpty() && !get(kEnumerationIndexIndex)->IsSmi();
1871 }
1872
1873 Object* GetEnumCache() {
1874 ASSERT(HasEnumCache());
1875 FixedArray* bridge = FixedArray::cast(get(kEnumerationIndexIndex));
1876 return bridge->get(kEnumCacheBridgeCacheIndex);
1877 }
1878
1879 // Initialize or change the enum cache,
1880 // using the supplied storage for the small "bridge".
1881 void SetEnumCache(FixedArray* bridge_storage, FixedArray* new_cache);
1882
1883 // Accessors for fetching instance descriptor at descriptor number.
1884 inline String* GetKey(int descriptor_number);
1885 inline Object* GetValue(int descriptor_number);
1886 inline Smi* GetDetails(int descriptor_number);
1887 inline PropertyType GetType(int descriptor_number);
1888 inline int GetFieldIndex(int descriptor_number);
1889 inline JSFunction* GetConstantFunction(int descriptor_number);
1890 inline Object* GetCallbacksObject(int descriptor_number);
1891 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
1892 inline bool IsProperty(int descriptor_number);
1893 inline bool IsTransition(int descriptor_number);
1894 inline bool IsNullDescriptor(int descriptor_number);
1895 inline bool IsDontEnum(int descriptor_number);
1896
1897 // Accessor for complete descriptor.
1898 inline void Get(int descriptor_number, Descriptor* desc);
1899 inline void Set(int descriptor_number, Descriptor* desc);
1900
1901 // Transfer complete descriptor from another descriptor array to
1902 // this one.
1903 inline void CopyFrom(int index, DescriptorArray* src, int src_index);
1904
1905 // Copy the descriptor array, insert a new descriptor and optionally
1906 // remove map transitions. If the descriptor is already present, it is
1907 // replaced. If a replaced descriptor is a real property (not a transition
1908 // or null), its enumeration index is kept as is.
1909 // If adding a real property, map transitions must be removed. If adding
1910 // a transition, they must not be removed. All null descriptors are removed.
1911 Object* CopyInsert(Descriptor* descriptor, TransitionFlag transition_flag);
1912
1913 // Remove all transitions. Return a copy of the array with all transitions
1914 // removed, or a Failure object if the new array could not be allocated.
1915 Object* RemoveTransitions();
1916
1917 // Sort the instance descriptors by the hash codes of their keys.
1918 void Sort();
1919
1920 // Search the instance descriptors for given name.
1921 inline int Search(String* name);
1922
1923 // Tells whether the name is present int the array.
1924 bool Contains(String* name) { return kNotFound != Search(name); }
1925
1926 // Perform a binary search in the instance descriptors represented
1927 // by this fixed array. low and high are descriptor indices. If there
1928 // are three instance descriptors in this array it should be called
1929 // with low=0 and high=2.
1930 int BinarySearch(String* name, int low, int high);
1931
1932 // Perform a linear search in the instance descriptors represented
1933 // by this fixed array. len is the number of descriptor indices that are
1934 // valid. Does not require the descriptors to be sorted.
1935 int LinearSearch(String* name, int len);
1936
1937 // Allocates a DescriptorArray, but returns the singleton
1938 // empty descriptor array object if number_of_descriptors is 0.
1939 static Object* Allocate(int number_of_descriptors);
1940
1941 // Casting.
1942 static inline DescriptorArray* cast(Object* obj);
1943
1944 // Constant for denoting key was not found.
1945 static const int kNotFound = -1;
1946
1947 static const int kContentArrayIndex = 0;
1948 static const int kEnumerationIndexIndex = 1;
1949 static const int kFirstIndex = 2;
1950
1951 // The length of the "bridge" to the enum cache.
1952 static const int kEnumCacheBridgeLength = 2;
1953 static const int kEnumCacheBridgeEnumIndex = 0;
1954 static const int kEnumCacheBridgeCacheIndex = 1;
1955
1956 // Layout description.
1957 static const int kContentArrayOffset = FixedArray::kHeaderSize;
1958 static const int kEnumerationIndexOffset = kContentArrayOffset + kPointerSize;
1959 static const int kFirstOffset = kEnumerationIndexOffset + kPointerSize;
1960
1961 // Layout description for the bridge array.
1962 static const int kEnumCacheBridgeEnumOffset = FixedArray::kHeaderSize;
1963 static const int kEnumCacheBridgeCacheOffset =
1964 kEnumCacheBridgeEnumOffset + kPointerSize;
1965
1966#ifdef DEBUG
1967 // Print all the descriptors.
1968 void PrintDescriptors();
1969
1970 // Is the descriptor array sorted and without duplicates?
1971 bool IsSortedNoDuplicates();
1972
1973 // Are two DescriptorArrays equal?
1974 bool IsEqualTo(DescriptorArray* other);
1975#endif
1976
1977 // The maximum number of descriptors we want in a descriptor array (should
1978 // fit in a page).
1979 static const int kMaxNumberOfDescriptors = 1024 + 512;
1980
1981 private:
1982 // Conversion from descriptor number to array indices.
1983 static int ToKeyIndex(int descriptor_number) {
1984 return descriptor_number+kFirstIndex;
1985 }
1986 static int ToValueIndex(int descriptor_number) {
1987 return descriptor_number << 1;
1988 }
1989 static int ToDetailsIndex(int descriptor_number) {
1990 return( descriptor_number << 1) + 1;
1991 }
1992
1993 bool is_null_descriptor(int descriptor_number) {
1994 return PropertyDetails(GetDetails(descriptor_number)).type() ==
1995 NULL_DESCRIPTOR;
1996 }
1997 // Swap operation on FixedArray without using write barriers.
1998 static inline void fast_swap(FixedArray* array, int first, int second);
1999
2000 // Swap descriptor first and second.
2001 inline void Swap(int first, int second);
2002
2003 FixedArray* GetContentArray() {
2004 return FixedArray::cast(get(kContentArrayIndex));
2005 }
2006 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2007};
2008
2009
2010// HashTable is a subclass of FixedArray that implements a hash table
2011// that uses open addressing and quadratic probing.
2012//
2013// In order for the quadratic probing to work, elements that have not
2014// yet been used and elements that have been deleted are
2015// distinguished. Probing continues when deleted elements are
2016// encountered and stops when unused elements are encountered.
2017//
2018// - Elements with key == undefined have not been used yet.
2019// - Elements with key == null have been deleted.
2020//
2021// The hash table class is parameterized with a Shape and a Key.
2022// Shape must be a class with the following interface:
2023// class ExampleShape {
2024// public:
2025// // Tells whether key matches other.
2026// static bool IsMatch(Key key, Object* other);
2027// // Returns the hash value for key.
2028// static uint32_t Hash(Key key);
2029// // Returns the hash value for object.
2030// static uint32_t HashForObject(Key key, Object* object);
2031// // Convert key to an object.
2032// static inline Object* AsObject(Key key);
2033// // The prefix size indicates number of elements in the beginning
2034// // of the backing storage.
2035// static const int kPrefixSize = ..;
2036// // The Element size indicates number of elements per entry.
2037// static const int kEntrySize = ..;
2038// };
2039// table. The prefix size indicates an amount of memory in the
2040// beginning of the backing storage that can be used for non-element
2041// information by subclasses.
2042
2043template<typename Shape, typename Key>
2044class HashTable: public FixedArray {
2045 public:
2046 // Returns the number of elements in the dictionary.
2047 int NumberOfElements() {
2048 return Smi::cast(get(kNumberOfElementsIndex))->value();
2049 }
2050
2051 // Returns the capacity of the dictionary.
2052 int Capacity() {
2053 return Smi::cast(get(kCapacityIndex))->value();
2054 }
2055
2056 // ElementAdded should be called whenever an element is added to a
2057 // dictionary.
2058 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2059
2060 // ElementRemoved should be called whenever an element is removed from
2061 // a dictionary.
2062 void ElementRemoved() { SetNumberOfElements(NumberOfElements() - 1); }
2063 void ElementsRemoved(int n) { SetNumberOfElements(NumberOfElements() - n); }
2064
2065 // Returns a new array for dictionary usage. Might return Failure.
2066 static Object* Allocate(int at_least_space_for);
2067
2068 // Returns the key at entry.
2069 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2070
2071 // Tells whether k is a real key. Null and undefined are not allowed
2072 // as keys and can be used to indicate missing or deleted elements.
2073 bool IsKey(Object* k) {
2074 return !k->IsNull() && !k->IsUndefined();
2075 }
2076
2077 // Garbage collection support.
2078 void IteratePrefix(ObjectVisitor* visitor);
2079 void IterateElements(ObjectVisitor* visitor);
2080
2081 // Casting.
2082 static inline HashTable* cast(Object* obj);
2083
2084 // Compute the probe offset (quadratic probing).
2085 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2086 return (n + n * n) >> 1;
2087 }
2088
2089 static const int kNumberOfElementsIndex = 0;
2090 static const int kCapacityIndex = 1;
2091 static const int kPrefixStartIndex = 2;
2092 static const int kElementsStartIndex =
2093 kPrefixStartIndex + Shape::kPrefixSize;
2094 static const int kEntrySize = Shape::kEntrySize;
2095 static const int kElementsStartOffset =
2096 kHeaderSize + kElementsStartIndex * kPointerSize;
2097
2098 // Constant used for denoting a absent entry.
2099 static const int kNotFound = -1;
2100
2101 // Find entry for key otherwise return -1.
2102 int FindEntry(Key key);
2103
2104 protected:
2105
2106 // Find the entry at which to insert element with the given key that
2107 // has the given hash value.
2108 uint32_t FindInsertionEntry(uint32_t hash);
2109
2110 // Returns the index for an entry (of the key)
2111 static inline int EntryToIndex(int entry) {
2112 return (entry * kEntrySize) + kElementsStartIndex;
2113 }
2114
2115 // Update the number of elements in the dictionary.
2116 void SetNumberOfElements(int nof) {
2117 fast_set(this, kNumberOfElementsIndex, Smi::FromInt(nof));
2118 }
2119
2120 // Sets the capacity of the hash table.
2121 void SetCapacity(int capacity) {
2122 // To scale a computed hash code to fit within the hash table, we
2123 // use bit-wise AND with a mask, so the capacity must be positive
2124 // and non-zero.
2125 ASSERT(capacity > 0);
2126 fast_set(this, kCapacityIndex, Smi::FromInt(capacity));
2127 }
2128
2129
2130 // Returns probe entry.
2131 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2132 ASSERT(IsPowerOf2(size));
2133 return (hash + GetProbeOffset(number)) & (size - 1);
2134 }
2135
2136 // Ensure enough space for n additional elements.
2137 Object* EnsureCapacity(int n, Key key);
2138};
2139
2140
2141
2142// HashTableKey is an abstract superclass for virtual key behavior.
2143class HashTableKey {
2144 public:
2145 // Returns whether the other object matches this key.
2146 virtual bool IsMatch(Object* other) = 0;
2147 // Returns the hash value for this key.
2148 virtual uint32_t Hash() = 0;
2149 // Returns the hash value for object.
2150 virtual uint32_t HashForObject(Object* key) = 0;
2151 // Returns the key object for storing into the dictionary.
2152 // If allocations fails a failure object is returned.
2153 virtual Object* AsObject() = 0;
2154 // Required.
2155 virtual ~HashTableKey() {}
2156};
2157
2158class SymbolTableShape {
2159 public:
2160 static bool IsMatch(HashTableKey* key, Object* value) {
2161 return key->IsMatch(value);
2162 }
2163 static uint32_t Hash(HashTableKey* key) {
2164 return key->Hash();
2165 }
2166 static uint32_t HashForObject(HashTableKey* key, Object* object) {
2167 return key->HashForObject(object);
2168 }
2169 static Object* AsObject(HashTableKey* key) {
2170 return key->AsObject();
2171 }
2172
2173 static const int kPrefixSize = 0;
2174 static const int kEntrySize = 1;
2175};
2176
2177// SymbolTable.
2178//
2179// No special elements in the prefix and the element size is 1
2180// because only the symbol itself (the key) needs to be stored.
2181class SymbolTable: public HashTable<SymbolTableShape, HashTableKey*> {
2182 public:
2183 // Find symbol in the symbol table. If it is not there yet, it is
2184 // added. The return value is the symbol table which might have
2185 // been enlarged. If the return value is not a failure, the symbol
2186 // pointer *s is set to the symbol found.
2187 Object* LookupSymbol(Vector<const char> str, Object** s);
2188 Object* LookupString(String* key, Object** s);
2189
2190 // Looks up a symbol that is equal to the given string and returns
2191 // true if it is found, assigning the symbol to the given output
2192 // parameter.
2193 bool LookupSymbolIfExists(String* str, String** symbol);
2194
2195 // Casting.
2196 static inline SymbolTable* cast(Object* obj);
2197
2198 private:
2199 Object* LookupKey(HashTableKey* key, Object** s);
2200
2201 DISALLOW_IMPLICIT_CONSTRUCTORS(SymbolTable);
2202};
2203
2204
2205class MapCacheShape {
2206 public:
2207 static bool IsMatch(HashTableKey* key, Object* value) {
2208 return key->IsMatch(value);
2209 }
2210 static uint32_t Hash(HashTableKey* key) {
2211 return key->Hash();
2212 }
2213
2214 static uint32_t HashForObject(HashTableKey* key, Object* object) {
2215 return key->HashForObject(object);
2216 }
2217
2218 static Object* AsObject(HashTableKey* key) {
2219 return key->AsObject();
2220 }
2221
2222 static const int kPrefixSize = 0;
2223 static const int kEntrySize = 2;
2224};
2225
2226
2227// MapCache.
2228//
2229// Maps keys that are a fixed array of symbols to a map.
2230// Used for canonicalize maps for object literals.
2231class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
2232 public:
2233 // Find cached value for a string key, otherwise return null.
2234 Object* Lookup(FixedArray* key);
2235 Object* Put(FixedArray* key, Map* value);
2236 static inline MapCache* cast(Object* obj);
2237
2238 private:
2239 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
2240};
2241
2242
2243template <typename Shape, typename Key>
2244class Dictionary: public HashTable<Shape, Key> {
2245 public:
2246
2247 static inline Dictionary<Shape, Key>* cast(Object* obj) {
2248 return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
2249 }
2250
2251 // Returns the value at entry.
2252 Object* ValueAt(int entry) {
2253 return get(HashTable<Shape, Key>::EntryToIndex(entry)+1);
2254 }
2255
2256 // Set the value for entry.
2257 void ValueAtPut(int entry, Object* value) {
2258 set(HashTable<Shape, Key>::EntryToIndex(entry)+1, value);
2259 }
2260
2261 // Returns the property details for the property at entry.
2262 PropertyDetails DetailsAt(int entry) {
2263 ASSERT(entry >= 0); // Not found is -1, which is not caught by get().
2264 return PropertyDetails(
2265 Smi::cast(get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
2266 }
2267
2268 // Set the details for entry.
2269 void DetailsAtPut(int entry, PropertyDetails value) {
2270 set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
2271 }
2272
2273 // Sorting support
2274 void CopyValuesTo(FixedArray* elements);
2275
2276 // Delete a property from the dictionary.
2277 Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
2278
2279 // Returns the number of elements in the dictionary filtering out properties
2280 // with the specified attributes.
2281 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
2282
2283 // Returns the number of enumerable elements in the dictionary.
2284 int NumberOfEnumElements();
2285
2286 // Copies keys to preallocated fixed array.
2287 void CopyKeysTo(FixedArray* storage, PropertyAttributes filter);
2288 // Fill in details for properties into storage.
2289 void CopyKeysTo(FixedArray* storage);
2290
2291 // Accessors for next enumeration index.
2292 void SetNextEnumerationIndex(int index) {
2293 fast_set(this, kNextEnumerationIndexIndex, Smi::FromInt(index));
2294 }
2295
2296 int NextEnumerationIndex() {
2297 return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
2298 }
2299
2300 // Returns a new array for dictionary usage. Might return Failure.
2301 static Object* Allocate(int at_least_space_for);
2302
2303 // Ensure enough space for n additional elements.
2304 Object* EnsureCapacity(int n, Key key);
2305
2306#ifdef DEBUG
2307 void Print();
2308#endif
2309 // Returns the key (slow).
2310 Object* SlowReverseLookup(Object* value);
2311
2312 // Sets the entry to (key, value) pair.
2313 inline void SetEntry(int entry,
2314 Object* key,
2315 Object* value,
2316 PropertyDetails details);
2317
2318 Object* Add(Key key, Object* value, PropertyDetails details);
2319
2320 protected:
2321 // Generic at put operation.
2322 Object* AtPut(Key key, Object* value);
2323
2324 // Add entry to dictionary.
2325 Object* AddEntry(Key key,
2326 Object* value,
2327 PropertyDetails details,
2328 uint32_t hash);
2329
2330 // Generate new enumeration indices to avoid enumeration index overflow.
2331 Object* GenerateNewEnumerationIndices();
2332 static const int kMaxNumberKeyIndex =
2333 HashTable<Shape, Key>::kPrefixStartIndex;
2334 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
2335};
2336
2337
2338class StringDictionaryShape {
2339 public:
2340 static inline bool IsMatch(String* key, Object* other);
2341 static inline uint32_t Hash(String* key);
2342 static inline uint32_t HashForObject(String* key, Object* object);
2343 static inline Object* AsObject(String* key);
2344 static const int kPrefixSize = 2;
2345 static const int kEntrySize = 3;
2346 static const bool kIsEnumerable = true;
2347};
2348
2349
2350class StringDictionary: public Dictionary<StringDictionaryShape, String*> {
2351 public:
2352 static inline StringDictionary* cast(Object* obj) {
2353 ASSERT(obj->IsDictionary());
2354 return reinterpret_cast<StringDictionary*>(obj);
2355 }
2356
2357 // Copies enumerable keys to preallocated fixed array.
2358 void CopyEnumKeysTo(FixedArray* storage, FixedArray* sort_array);
2359
2360 // For transforming properties of a JSObject.
2361 Object* TransformPropertiesToFastFor(JSObject* obj,
2362 int unused_property_fields);
2363};
2364
2365
2366class NumberDictionaryShape {
2367 public:
2368 static inline bool IsMatch(uint32_t key, Object* other);
2369 static inline uint32_t Hash(uint32_t key);
2370 static inline uint32_t HashForObject(uint32_t key, Object* object);
2371 static inline Object* AsObject(uint32_t key);
2372 static const int kPrefixSize = 2;
2373 static const int kEntrySize = 3;
2374 static const bool kIsEnumerable = false;
2375};
2376
2377
2378class NumberDictionary: public Dictionary<NumberDictionaryShape, uint32_t> {
2379 public:
2380 static NumberDictionary* cast(Object* obj) {
2381 ASSERT(obj->IsDictionary());
2382 return reinterpret_cast<NumberDictionary*>(obj);
2383 }
2384
2385 // Type specific at put (default NONE attributes is used when adding).
2386 Object* AtNumberPut(uint32_t key, Object* value);
2387 Object* AddNumberEntry(uint32_t key,
2388 Object* value,
2389 PropertyDetails details);
2390
2391 // Set an existing entry or add a new one if needed.
2392 Object* Set(uint32_t key, Object* value, PropertyDetails details);
2393
2394 void UpdateMaxNumberKey(uint32_t key);
2395
2396 // If slow elements are required we will never go back to fast-case
2397 // for the elements kept in this dictionary. We require slow
2398 // elements if an element has been added at an index larger than
2399 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
2400 // when defining a getter or setter with a number key.
2401 inline bool requires_slow_elements();
2402 inline void set_requires_slow_elements();
2403
2404 // Get the value of the max number key that has been added to this
2405 // dictionary. max_number_key can only be called if
2406 // requires_slow_elements returns false.
2407 inline uint32_t max_number_key();
2408
2409 // Remove all entries were key is a number and (from <= key && key < to).
2410 void RemoveNumberEntries(uint32_t from, uint32_t to);
2411
2412 // Bit masks.
2413 static const int kRequiresSlowElementsMask = 1;
2414 static const int kRequiresSlowElementsTagSize = 1;
2415 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
2416};
2417
2418
2419// ByteArray represents fixed sized byte arrays. Used by the outside world,
2420// such as PCRE, and also by the memory allocator and garbage collector to
2421// fill in free blocks in the heap.
2422class ByteArray: public Array {
2423 public:
2424 // Setter and getter.
2425 inline byte get(int index);
2426 inline void set(int index, byte value);
2427
2428 // Treat contents as an int array.
2429 inline int get_int(int index);
2430
2431 static int SizeFor(int length) {
2432 return OBJECT_SIZE_ALIGN(kHeaderSize + length);
2433 }
2434 // We use byte arrays for free blocks in the heap. Given a desired size in
2435 // bytes that is a multiple of the word size and big enough to hold a byte
2436 // array, this function returns the number of elements a byte array should
2437 // have.
2438 static int LengthFor(int size_in_bytes) {
2439 ASSERT(IsAligned(size_in_bytes, kPointerSize));
2440 ASSERT(size_in_bytes >= kHeaderSize);
2441 return size_in_bytes - kHeaderSize;
2442 }
2443
2444 // Returns data start address.
2445 inline Address GetDataStartAddress();
2446
2447 // Returns a pointer to the ByteArray object for a given data start address.
2448 static inline ByteArray* FromDataStartAddress(Address address);
2449
2450 // Casting.
2451 static inline ByteArray* cast(Object* obj);
2452
2453 // Dispatched behavior.
2454 int ByteArraySize() { return SizeFor(length()); }
2455#ifdef DEBUG
2456 void ByteArrayPrint();
2457 void ByteArrayVerify();
2458#endif
2459
2460 // ByteArray headers are not quadword aligned.
2461 static const int kHeaderSize = Array::kHeaderSize;
2462 static const int kAlignedSize = Array::kAlignedSize;
2463
2464 private:
2465 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
2466};
2467
2468
2469// A PixelArray represents a fixed-size byte array with special semantics
2470// used for implementing the CanvasPixelArray object. Please see the
2471// specification at:
2472// http://www.whatwg.org/specs/web-apps/current-work/
2473// multipage/the-canvas-element.html#canvaspixelarray
2474// In particular, write access clamps the value written to 0 or 255 if the
2475// value written is outside this range.
2476class PixelArray: public Array {
2477 public:
2478 // [external_pointer]: The pointer to the external memory area backing this
2479 // pixel array.
2480 DECL_ACCESSORS(external_pointer, uint8_t) // Pointer to the data store.
2481
2482 // Setter and getter.
2483 inline uint8_t get(int index);
2484 inline void set(int index, uint8_t value);
2485
2486 // This accessor applies the correct conversion from Smi, HeapNumber and
2487 // undefined and clamps the converted value between 0 and 255.
2488 Object* SetValue(uint32_t index, Object* value);
2489
2490 // Casting.
2491 static inline PixelArray* cast(Object* obj);
2492
2493#ifdef DEBUG
2494 void PixelArrayPrint();
2495 void PixelArrayVerify();
2496#endif // DEBUG
2497
2498 // PixelArray headers are not quadword aligned.
2499 static const int kExternalPointerOffset = Array::kAlignedSize;
2500 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
2501 static const int kAlignedSize = OBJECT_SIZE_ALIGN(kHeaderSize);
2502
2503 private:
2504 DISALLOW_IMPLICIT_CONSTRUCTORS(PixelArray);
2505};
2506
2507
2508// Code describes objects with on-the-fly generated machine code.
2509class Code: public HeapObject {
2510 public:
2511 // Opaque data type for encapsulating code flags like kind, inline
2512 // cache state, and arguments count.
2513 enum Flags { };
2514
2515 enum Kind {
2516 FUNCTION,
2517 STUB,
2518 BUILTIN,
2519 LOAD_IC,
2520 KEYED_LOAD_IC,
2521 CALL_IC,
2522 STORE_IC,
2523 KEYED_STORE_IC,
2524 // No more than eight kinds. The value currently encoded in three bits in
2525 // Flags.
2526
2527 // Pseudo-kinds.
2528 REGEXP = BUILTIN,
2529 FIRST_IC_KIND = LOAD_IC,
2530 LAST_IC_KIND = KEYED_STORE_IC
2531 };
2532
2533 enum {
2534 NUMBER_OF_KINDS = KEYED_STORE_IC + 1
2535 };
2536
2537#ifdef ENABLE_DISASSEMBLER
2538 // Printing
2539 static const char* Kind2String(Kind kind);
2540 static const char* ICState2String(InlineCacheState state);
2541 static const char* PropertyType2String(PropertyType type);
2542 void Disassemble(const char* name);
2543#endif // ENABLE_DISASSEMBLER
2544
2545 // [instruction_size]: Size of the native instructions
2546 inline int instruction_size();
2547 inline void set_instruction_size(int value);
2548
2549 // [relocation_size]: Size of relocation information.
2550 inline int relocation_size();
2551 inline void set_relocation_size(int value);
2552
2553 // [sinfo_size]: Size of scope information.
2554 inline int sinfo_size();
2555 inline void set_sinfo_size(int value);
2556
2557 // [flags]: Various code flags.
2558 inline Flags flags();
2559 inline void set_flags(Flags flags);
2560
2561 // [flags]: Access to specific code flags.
2562 inline Kind kind();
2563 inline InlineCacheState ic_state(); // Only valid for IC stubs.
2564 inline InLoopFlag ic_in_loop(); // Only valid for IC stubs.
2565 inline PropertyType type(); // Only valid for monomorphic IC stubs.
2566 inline int arguments_count(); // Only valid for call IC stubs.
2567
2568 // Testers for IC stub kinds.
2569 inline bool is_inline_cache_stub();
2570 inline bool is_load_stub() { return kind() == LOAD_IC; }
2571 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
2572 inline bool is_store_stub() { return kind() == STORE_IC; }
2573 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
2574 inline bool is_call_stub() { return kind() == CALL_IC; }
2575
2576 // [major_key]: For kind STUB, the major key.
2577 inline CodeStub::Major major_key();
2578 inline void set_major_key(CodeStub::Major major);
2579
2580 // Flags operations.
2581 static inline Flags ComputeFlags(Kind kind,
2582 InLoopFlag in_loop = NOT_IN_LOOP,
2583 InlineCacheState ic_state = UNINITIALIZED,
2584 PropertyType type = NORMAL,
2585 int argc = -1);
2586
2587 static inline Flags ComputeMonomorphicFlags(
2588 Kind kind,
2589 PropertyType type,
2590 InLoopFlag in_loop = NOT_IN_LOOP,
2591 int argc = -1);
2592
2593 static inline Kind ExtractKindFromFlags(Flags flags);
2594 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
2595 static inline InLoopFlag ExtractICInLoopFromFlags(Flags flags);
2596 static inline PropertyType ExtractTypeFromFlags(Flags flags);
2597 static inline int ExtractArgumentsCountFromFlags(Flags flags);
2598 static inline Flags RemoveTypeFromFlags(Flags flags);
2599
2600 // Convert a target address into a code object.
2601 static inline Code* GetCodeFromTargetAddress(Address address);
2602
2603 // Returns the address of the first instruction.
2604 inline byte* instruction_start();
2605
2606 // Returns the size of the instructions, padding, and relocation information.
2607 inline int body_size();
2608
2609 // Returns the address of the first relocation info (read backwards!).
2610 inline byte* relocation_start();
2611
2612 // Code entry point.
2613 inline byte* entry();
2614
2615 // Returns true if pc is inside this object's instructions.
2616 inline bool contains(byte* pc);
2617
2618 // Returns the address of the scope information.
2619 inline byte* sinfo_start();
2620
2621 // Relocate the code by delta bytes. Called to signal that this code
2622 // object has been moved by delta bytes.
2623 void Relocate(int delta);
2624
2625 // Migrate code described by desc.
2626 void CopyFrom(const CodeDesc& desc);
2627
2628 // Returns the object size for a given body and sinfo size (Used for
2629 // allocation).
2630 static int SizeFor(int body_size, int sinfo_size) {
2631 ASSERT_SIZE_TAG_ALIGNED(body_size);
2632 ASSERT_SIZE_TAG_ALIGNED(sinfo_size);
2633 return RoundUp(kHeaderSize + body_size + sinfo_size, kCodeAlignment);
2634 }
2635
2636 // Calculate the size of the code object to report for log events. This takes
2637 // the layout of the code object into account.
2638 int ExecutableSize() {
2639 // Check that the assumptions about the layout of the code object holds.
2640 ASSERT_EQ(static_cast<int>(instruction_start() - address()),
2641 Code::kHeaderSize);
2642 return instruction_size() + Code::kHeaderSize;
2643 }
2644
2645 // Locating source position.
2646 int SourcePosition(Address pc);
2647 int SourceStatementPosition(Address pc);
2648
2649 // Casting.
2650 static inline Code* cast(Object* obj);
2651
2652 // Dispatched behavior.
2653 int CodeSize() { return SizeFor(body_size(), sinfo_size()); }
2654 void CodeIterateBody(ObjectVisitor* v);
2655#ifdef DEBUG
2656 void CodePrint();
2657 void CodeVerify();
2658#endif
2659 // Code entry points are aligned to 32 bytes.
2660 static const int kCodeAlignment = 32;
2661 static const int kCodeAlignmentMask = kCodeAlignment - 1;
2662
2663 // Layout description.
2664 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
2665 static const int kRelocationSizeOffset = kInstructionSizeOffset + kIntSize;
2666 static const int kSInfoSizeOffset = kRelocationSizeOffset + kIntSize;
2667 static const int kFlagsOffset = kSInfoSizeOffset + kIntSize;
2668 static const int kKindSpecificFlagsOffset = kFlagsOffset + kIntSize;
2669 // Add padding to align the instruction start following right after
2670 // the Code object header.
2671 static const int kHeaderSize =
2672 (kKindSpecificFlagsOffset + kIntSize + kCodeAlignmentMask) &
2673 ~kCodeAlignmentMask;
2674
2675 // Byte offsets within kKindSpecificFlagsOffset.
2676 static const int kStubMajorKeyOffset = kKindSpecificFlagsOffset + 1;
2677
2678 // Flags layout.
2679 static const int kFlagsICStateShift = 0;
2680 static const int kFlagsICInLoopShift = 3;
2681 static const int kFlagsKindShift = 4;
2682 static const int kFlagsTypeShift = 7;
2683 static const int kFlagsArgumentsCountShift = 10;
2684
2685 static const int kFlagsICStateMask = 0x00000007; // 0000000111
2686 static const int kFlagsICInLoopMask = 0x00000008; // 0000001000
2687 static const int kFlagsKindMask = 0x00000070; // 0001110000
2688 static const int kFlagsTypeMask = 0x00000380; // 1110000000
2689 static const int kFlagsArgumentsCountMask = 0xFFFFFC00;
2690
2691 static const int kFlagsNotUsedInLookup =
2692 (kFlagsICInLoopMask | kFlagsTypeMask);
2693
2694 private:
2695 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
2696};
2697
2698
2699// All heap objects have a Map that describes their structure.
2700// A Map contains information about:
2701// - Size information about the object
2702// - How to iterate over an object (for garbage collection)
2703class Map: public HeapObject {
2704 public:
2705 // Instance size.
2706 inline int instance_size();
2707 inline void set_instance_size(int value);
2708
2709 // Count of properties allocated in the object.
2710 inline int inobject_properties();
2711 inline void set_inobject_properties(int value);
2712
2713 // Count of property fields pre-allocated in the object when first allocated.
2714 inline int pre_allocated_property_fields();
2715 inline void set_pre_allocated_property_fields(int value);
2716
2717 // Instance type.
2718 inline InstanceType instance_type();
2719 inline void set_instance_type(InstanceType value);
2720
2721 // Tells how many unused property fields are available in the
2722 // instance (only used for JSObject in fast mode).
2723 inline int unused_property_fields();
2724 inline void set_unused_property_fields(int value);
2725
2726 // Bit field.
2727 inline byte bit_field();
2728 inline void set_bit_field(byte value);
2729
2730 // Bit field 2.
2731 inline byte bit_field2();
2732 inline void set_bit_field2(byte value);
2733
2734 // Tells whether the object in the prototype property will be used
2735 // for instances created from this function. If the prototype
2736 // property is set to a value that is not a JSObject, the prototype
2737 // property will not be used to create instances of the function.
2738 // See ECMA-262, 13.2.2.
2739 inline void set_non_instance_prototype(bool value);
2740 inline bool has_non_instance_prototype();
2741
2742 // Tells whether the instance with this map should be ignored by the
2743 // __proto__ accessor.
2744 inline void set_is_hidden_prototype() {
2745 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
2746 }
2747
2748 inline bool is_hidden_prototype() {
2749 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
2750 }
2751
2752 // Records and queries whether the instance has a named interceptor.
2753 inline void set_has_named_interceptor() {
2754 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
2755 }
2756
2757 inline bool has_named_interceptor() {
2758 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
2759 }
2760
2761 // Records and queries whether the instance has an indexed interceptor.
2762 inline void set_has_indexed_interceptor() {
2763 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
2764 }
2765
2766 inline bool has_indexed_interceptor() {
2767 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
2768 }
2769
2770 // Tells whether the instance is undetectable.
2771 // An undetectable object is a special class of JSObject: 'typeof' operator
2772 // returns undefined, ToBoolean returns false. Otherwise it behaves like
2773 // a normal JS object. It is useful for implementing undetectable
2774 // document.all in Firefox & Safari.
2775 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
2776 inline void set_is_undetectable() {
2777 set_bit_field(bit_field() | (1 << kIsUndetectable));
2778 }
2779
2780 inline bool is_undetectable() {
2781 return ((1 << kIsUndetectable) & bit_field()) != 0;
2782 }
2783
2784 inline void set_needs_loading(bool value) {
2785 if (value) {
2786 set_bit_field2(bit_field2() | (1 << kNeedsLoading));
2787 } else {
2788 set_bit_field2(bit_field2() & ~(1 << kNeedsLoading));
2789 }
2790 }
2791
2792 // Does this object or function require a lazily loaded script to be
2793 // run before being used?
2794 inline bool needs_loading() {
2795 return ((1 << kNeedsLoading) & bit_field2()) != 0;
2796 }
2797
2798 // Tells whether the instance has a call-as-function handler.
2799 inline void set_has_instance_call_handler() {
2800 set_bit_field(bit_field() | (1 << kHasInstanceCallHandler));
2801 }
2802
2803 inline bool has_instance_call_handler() {
2804 return ((1 << kHasInstanceCallHandler) & bit_field()) != 0;
2805 }
2806
2807 // Tells whether the instance needs security checks when accessing its
2808 // properties.
2809 inline void set_is_access_check_needed(bool access_check_needed);
2810 inline bool is_access_check_needed();
2811
2812 // [prototype]: implicit prototype object.
2813 DECL_ACCESSORS(prototype, Object)
2814
2815 // [constructor]: points back to the function responsible for this map.
2816 DECL_ACCESSORS(constructor, Object)
2817
2818 // [instance descriptors]: describes the object.
2819 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
2820
2821 // [stub cache]: contains stubs compiled for this map.
2822 DECL_ACCESSORS(code_cache, FixedArray)
2823
2824 // Returns a copy of the map.
2825 Object* CopyDropDescriptors();
2826
2827 // Returns a copy of the map, with all transitions dropped from the
2828 // instance descriptors.
2829 Object* CopyDropTransitions();
2830
2831 // Returns the property index for name (only valid for FAST MODE).
2832 int PropertyIndexFor(String* name);
2833
2834 // Returns the next free property index (only valid for FAST MODE).
2835 int NextFreePropertyIndex();
2836
2837 // Returns the number of properties described in instance_descriptors.
2838 int NumberOfDescribedProperties();
2839
2840 // Casting.
2841 static inline Map* cast(Object* obj);
2842
2843 // Locate an accessor in the instance descriptor.
2844 AccessorDescriptor* FindAccessor(String* name);
2845
2846 // Code cache operations.
2847
2848 // Clears the code cache.
2849 inline void ClearCodeCache();
2850
2851 // Update code cache.
2852 Object* UpdateCodeCache(String* name, Code* code);
2853
2854 // Returns the found code or undefined if absent.
2855 Object* FindInCodeCache(String* name, Code::Flags flags);
2856
2857 // Returns the non-negative index of the code object if it is in the
2858 // cache and -1 otherwise.
2859 int IndexInCodeCache(Code* code);
2860
2861 // Removes a code object from the code cache at the given index.
2862 void RemoveFromCodeCache(int index);
2863
2864 // For every transition in this map, makes the transition's
2865 // target's prototype pointer point back to this map.
2866 // This is undone in MarkCompactCollector::ClearNonLiveTransitions().
2867 void CreateBackPointers();
2868
2869 // Set all map transitions from this map to dead maps to null.
2870 // Also, restore the original prototype on the targets of these
2871 // transitions, so that we do not process this map again while
2872 // following back pointers.
2873 void ClearNonLiveTransitions(Object* real_prototype);
2874
2875 // Dispatched behavior.
2876 void MapIterateBody(ObjectVisitor* v);
2877#ifdef DEBUG
2878 void MapPrint();
2879 void MapVerify();
2880#endif
2881
2882 static const int kMaxPreAllocatedPropertyFields = 255;
2883
2884 // Layout description.
2885 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
2886 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
2887 static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
2888 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
2889 static const int kInstanceDescriptorsOffset =
2890 kConstructorOffset + kPointerSize;
2891 static const int kCodeCacheOffset = kInstanceDescriptorsOffset + kPointerSize;
2892 static const int kSize = kCodeCacheOffset + kPointerSize;
2893
2894 // Byte offsets within kInstanceSizesOffset.
2895 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
2896 static const int kInObjectPropertiesByte = 1;
2897 static const int kInObjectPropertiesOffset =
2898 kInstanceSizesOffset + kInObjectPropertiesByte;
2899 static const int kPreAllocatedPropertyFieldsByte = 2;
2900 static const int kPreAllocatedPropertyFieldsOffset =
2901 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
2902 // The byte at position 3 is not in use at the moment.
2903
2904 // Byte offsets within kInstanceAttributesOffset attributes.
2905 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
2906 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
2907 static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
2908 static const int kBitField2Offset = kInstanceAttributesOffset + 3;
2909
2910 STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
2911
2912 // Bit positions for bit field.
2913 static const int kUnused = 0; // To be used for marking recently used maps.
2914 static const int kHasNonInstancePrototype = 1;
2915 static const int kIsHiddenPrototype = 2;
2916 static const int kHasNamedInterceptor = 3;
2917 static const int kHasIndexedInterceptor = 4;
2918 static const int kIsUndetectable = 5;
2919 static const int kHasInstanceCallHandler = 6;
2920 static const int kIsAccessCheckNeeded = 7;
2921
2922 // Bit positions for bit field 2
2923 static const int kNeedsLoading = 0;
2924
2925 private:
2926 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
2927};
2928
2929
2930// An abstract superclass, a marker class really, for simple structure classes.
2931// It doesn't carry much functionality but allows struct classes to me
2932// identified in the type system.
2933class Struct: public HeapObject {
2934 public:
2935 inline void InitializeBody(int object_size);
2936 static inline Struct* cast(Object* that);
2937};
2938
2939
2940// Script describes a script which has been added to the VM.
2941class Script: public Struct {
2942 public:
2943 // Script types.
2944 enum Type {
2945 TYPE_NATIVE = 0,
2946 TYPE_EXTENSION = 1,
2947 TYPE_NORMAL = 2
2948 };
2949
2950 // Script compilation types.
2951 enum CompilationType {
2952 COMPILATION_TYPE_HOST = 0,
2953 COMPILATION_TYPE_EVAL = 1,
2954 COMPILATION_TYPE_JSON = 2
2955 };
2956
2957 // [source]: the script source.
2958 DECL_ACCESSORS(source, Object)
2959
2960 // [name]: the script name.
2961 DECL_ACCESSORS(name, Object)
2962
2963 // [id]: the script id.
2964 DECL_ACCESSORS(id, Object)
2965
2966 // [line_offset]: script line offset in resource from where it was extracted.
2967 DECL_ACCESSORS(line_offset, Smi)
2968
2969 // [column_offset]: script column offset in resource from where it was
2970 // extracted.
2971 DECL_ACCESSORS(column_offset, Smi)
2972
2973 // [data]: additional data associated with this script.
2974 DECL_ACCESSORS(data, Object)
2975
2976 // [context_data]: context data for the context this script was compiled in.
2977 DECL_ACCESSORS(context_data, Object)
2978
2979 // [wrapper]: the wrapper cache.
2980 DECL_ACCESSORS(wrapper, Proxy)
2981
2982 // [type]: the script type.
2983 DECL_ACCESSORS(type, Smi)
2984
2985 // [compilation]: how the the script was compiled.
2986 DECL_ACCESSORS(compilation_type, Smi)
2987
2988 // [line_ends]: array of line ends positions.
2989 DECL_ACCESSORS(line_ends, Object)
2990
2991 // [eval_from_function]: for eval scripts the funcion from which eval was
2992 // called.
2993 DECL_ACCESSORS(eval_from_function, Object)
2994
2995 // [eval_from_instructions_offset]: the instruction offset in the code for the
2996 // function from which eval was called where eval was called.
2997 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
2998
2999 static inline Script* cast(Object* obj);
3000
3001#ifdef DEBUG
3002 void ScriptPrint();
3003 void ScriptVerify();
3004#endif
3005
3006 static const int kSourceOffset = HeapObject::kHeaderSize;
3007 static const int kNameOffset = kSourceOffset + kPointerSize;
3008 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
3009 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
3010 static const int kDataOffset = kColumnOffsetOffset + kPointerSize;
3011 static const int kContextOffset = kDataOffset + kPointerSize;
3012 static const int kWrapperOffset = kContextOffset + kPointerSize;
3013 static const int kTypeOffset = kWrapperOffset + kPointerSize;
3014 static const int kCompilationTypeOffset = kTypeOffset + kPointerSize;
3015 static const int kLineEndsOffset = kCompilationTypeOffset + kPointerSize;
3016 static const int kIdOffset = kLineEndsOffset + kPointerSize;
3017 static const int kEvalFromFunctionOffset = kIdOffset + kPointerSize;
3018 static const int kEvalFrominstructionsOffsetOffset =
3019 kEvalFromFunctionOffset + kPointerSize;
3020 static const int kSize = kEvalFrominstructionsOffsetOffset + kPointerSize;
3021
3022 private:
3023 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
3024};
3025
3026
3027// SharedFunctionInfo describes the JSFunction information that can be
3028// shared by multiple instances of the function.
3029class SharedFunctionInfo: public HeapObject {
3030 public:
3031 // [name]: Function name.
3032 DECL_ACCESSORS(name, Object)
3033
3034 // [code]: Function code.
3035 DECL_ACCESSORS(code, Code)
3036
3037 // [construct stub]: Code stub for constructing instances of this function.
3038 DECL_ACCESSORS(construct_stub, Code)
3039
3040 // Returns if this function has been compiled to native code yet.
3041 inline bool is_compiled();
3042
3043 // [length]: The function length - usually the number of declared parameters.
3044 // Use up to 2^30 parameters.
3045 inline int length();
3046 inline void set_length(int value);
3047
3048 // [formal parameter count]: The declared number of parameters.
3049 inline int formal_parameter_count();
3050 inline void set_formal_parameter_count(int value);
3051
3052 // Set the formal parameter count so the function code will be
3053 // called without using argument adaptor frames.
3054 inline void DontAdaptArguments();
3055
3056 // [expected_nof_properties]: Expected number of properties for the function.
3057 inline int expected_nof_properties();
3058 inline void set_expected_nof_properties(int value);
3059
3060 // [instance class name]: class name for instances.
3061 DECL_ACCESSORS(instance_class_name, Object)
3062
3063 // [function data]: This field has been added for make benefit the API.
3064 // In the long run we don't want all functions to have this field but
3065 // we can fix that when we have a better model for storing hidden data
3066 // on objects.
3067 DECL_ACCESSORS(function_data, Object)
3068
3069 // [script info]: Script from which the function originates.
3070 DECL_ACCESSORS(script, Object)
3071
3072 // [start_position_and_type]: Field used to store both the source code
3073 // position, whether or not the function is a function expression,
3074 // and whether or not the function is a toplevel function. The two
3075 // least significants bit indicates whether the function is an
3076 // expression and the rest contains the source code position.
3077 inline int start_position_and_type();
3078 inline void set_start_position_and_type(int value);
3079
3080 // [debug info]: Debug information.
3081 DECL_ACCESSORS(debug_info, Object)
3082
3083 // [inferred name]: Name inferred from variable or property
3084 // assignment of this function. Used to facilitate debugging and
3085 // profiling of JavaScript code written in OO style, where almost
3086 // all functions are anonymous but are assigned to object
3087 // properties.
3088 DECL_ACCESSORS(inferred_name, String)
3089
3090 // Position of the 'function' token in the script source.
3091 inline int function_token_position();
3092 inline void set_function_token_position(int function_token_position);
3093
3094 // Position of this function in the script source.
3095 inline int start_position();
3096 inline void set_start_position(int start_position);
3097
3098 // End position of this function in the script source.
3099 inline int end_position();
3100 inline void set_end_position(int end_position);
3101
3102 // Is this function a function expression in the source code.
3103 inline bool is_expression();
3104 inline void set_is_expression(bool value);
3105
3106 // Is this function a top-level function (scripts, evals).
3107 inline bool is_toplevel();
3108 inline void set_is_toplevel(bool value);
3109
3110 // Bit field containing various information collected by the compiler to
3111 // drive optimization.
3112 inline int compiler_hints();
3113 inline void set_compiler_hints(int value);
3114
3115 // Add information on assignments of the form this.x = ...;
3116 void SetThisPropertyAssignmentsInfo(
3117 bool has_only_this_property_assignments,
3118 bool has_only_simple_this_property_assignments,
3119 FixedArray* this_property_assignments);
3120
3121 // Clear information on assignments of the form this.x = ...;
3122 void ClearThisPropertyAssignmentsInfo();
3123
3124 // Indicate that this function only consists of assignments of the form
3125 // this.x = ...;.
3126 inline bool has_only_this_property_assignments();
3127
3128 // Indicate that this function only consists of assignments of the form
3129 // this.x = y; where y is either a constant or refers to an argument.
3130 inline bool has_only_simple_this_property_assignments();
3131
3132 // For functions which only contains this property assignments this provides
3133 // access to the names for the properties assigned.
3134 DECL_ACCESSORS(this_property_assignments, Object)
3135 inline int this_property_assignments_count();
3136 inline void set_this_property_assignments_count(int value);
3137 String* GetThisPropertyAssignmentName(int index);
3138 bool IsThisPropertyAssignmentArgument(int index);
3139 int GetThisPropertyAssignmentArgument(int index);
3140 Object* GetThisPropertyAssignmentConstant(int index);
3141
3142 // [source code]: Source code for the function.
3143 bool HasSourceCode();
3144 Object* GetSourceCode();
3145
3146 // Calculate the instance size.
3147 int CalculateInstanceSize();
3148
3149 // Calculate the number of in-object properties.
3150 int CalculateInObjectProperties();
3151
3152 // Dispatched behavior.
3153 void SharedFunctionInfoIterateBody(ObjectVisitor* v);
3154 // Set max_length to -1 for unlimited length.
3155 void SourceCodePrint(StringStream* accumulator, int max_length);
3156#ifdef DEBUG
3157 void SharedFunctionInfoPrint();
3158 void SharedFunctionInfoVerify();
3159#endif
3160
3161 // Casting.
3162 static inline SharedFunctionInfo* cast(Object* obj);
3163
3164 // Constants.
3165 static const int kDontAdaptArgumentsSentinel = -1;
3166
3167 // Layout description.
3168 // (An even number of integers has a size that is a multiple of a pointer.)
3169 static const int kNameOffset = HeapObject::kHeaderSize;
3170 static const int kCodeOffset = kNameOffset + kPointerSize;
3171 static const int kConstructStubOffset = kCodeOffset + kPointerSize;
3172 static const int kLengthOffset = kConstructStubOffset + kPointerSize;
3173 static const int kFormalParameterCountOffset = kLengthOffset + kIntSize;
3174 static const int kExpectedNofPropertiesOffset =
3175 kFormalParameterCountOffset + kIntSize;
3176 static const int kStartPositionAndTypeOffset =
3177 kExpectedNofPropertiesOffset + kIntSize;
3178 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
3179 static const int kFunctionTokenPositionOffset = kEndPositionOffset + kIntSize;
3180 static const int kInstanceClassNameOffset =
3181 kFunctionTokenPositionOffset + kIntSize;
3182 static const int kExternalReferenceDataOffset =
3183 kInstanceClassNameOffset + kPointerSize;
3184 static const int kScriptOffset = kExternalReferenceDataOffset + kPointerSize;
3185 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
3186 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
3187 static const int kCompilerHintsOffset = kInferredNameOffset + kPointerSize;
3188 static const int kThisPropertyAssignmentsOffset =
3189 kCompilerHintsOffset + kPointerSize;
3190 static const int kThisPropertyAssignmentsCountOffset =
3191 kThisPropertyAssignmentsOffset + kPointerSize;
3192 static const int kSize = kThisPropertyAssignmentsCountOffset + kPointerSize;
3193
3194 private:
3195 // Bit positions in length_and_flg.
3196 // The least significant bit is used as the flag.
3197 static const int kFlagBit = 0;
3198 static const int kLengthShift = 1;
3199 static const int kLengthMask = ~((1 << kLengthShift) - 1);
3200
3201 // Bit positions in start_position_and_type.
3202 // The source code start position is in the 30 most significant bits of
3203 // the start_position_and_type field.
3204 static const int kIsExpressionBit = 0;
3205 static const int kIsTopLevelBit = 1;
3206 static const int kStartPositionShift = 2;
3207 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
3208
3209 // Bit positions in compiler_hints.
3210 static const int kHasOnlyThisPropertyAssignments = 0;
3211 static const int kHasOnlySimpleThisPropertyAssignments = 1;
3212
3213 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
3214};
3215
3216
3217// JSFunction describes JavaScript functions.
3218class JSFunction: public JSObject {
3219 public:
3220 // [prototype_or_initial_map]:
3221 DECL_ACCESSORS(prototype_or_initial_map, Object)
3222
3223 // [shared_function_info]: The information about the function that
3224 // can be shared by instances.
3225 DECL_ACCESSORS(shared, SharedFunctionInfo)
3226
3227 // [context]: The context for this function.
3228 inline Context* context();
3229 inline Object* unchecked_context();
3230 inline void set_context(Object* context);
3231
3232 // [code]: The generated code object for this function. Executed
3233 // when the function is invoked, e.g. foo() or new foo(). See
3234 // [[Call]] and [[Construct]] description in ECMA-262, section
3235 // 8.6.2, page 27.
3236 inline Code* code();
3237 inline void set_code(Code* value);
3238
3239 // Tells whether this function is a context-independent boilerplate
3240 // function.
3241 inline bool IsBoilerplate();
3242
3243 // Tells whether this function is builtin.
3244 inline bool IsBuiltin();
3245
3246 // [literals]: Fixed array holding the materialized literals.
3247 //
3248 // If the function contains object, regexp or array literals, the
3249 // literals array prefix contains the object, regexp, and array
3250 // function to be used when creating these literals. This is
3251 // necessary so that we do not dynamically lookup the object, regexp
3252 // or array functions. Performing a dynamic lookup, we might end up
3253 // using the functions from a new context that we should not have
3254 // access to.
3255 DECL_ACCESSORS(literals, FixedArray)
3256
3257 // The initial map for an object created by this constructor.
3258 inline Map* initial_map();
3259 inline void set_initial_map(Map* value);
3260 inline bool has_initial_map();
3261
3262 // Get and set the prototype property on a JSFunction. If the
3263 // function has an initial map the prototype is set on the initial
3264 // map. Otherwise, the prototype is put in the initial map field
3265 // until an initial map is needed.
3266 inline bool has_prototype();
3267 inline bool has_instance_prototype();
3268 inline Object* prototype();
3269 inline Object* instance_prototype();
3270 Object* SetInstancePrototype(Object* value);
3271 Object* SetPrototype(Object* value);
3272
3273 // Accessor for this function's initial map's [[class]]
3274 // property. This is primarily used by ECMA native functions. This
3275 // method sets the class_name field of this function's initial map
3276 // to a given value. It creates an initial map if this function does
3277 // not have one. Note that this method does not copy the initial map
3278 // if it has one already, but simply replaces it with the new value.
3279 // Instances created afterwards will have a map whose [[class]] is
3280 // set to 'value', but there is no guarantees on instances created
3281 // before.
3282 Object* SetInstanceClassName(String* name);
3283
3284 // Returns if this function has been compiled to native code yet.
3285 inline bool is_compiled();
3286
3287 // Casting.
3288 static inline JSFunction* cast(Object* obj);
3289
3290 // Dispatched behavior.
3291#ifdef DEBUG
3292 void JSFunctionPrint();
3293 void JSFunctionVerify();
3294#endif
3295
3296 // Returns the number of allocated literals.
3297 inline int NumberOfLiterals();
3298
3299 // Retrieve the global context from a function's literal array.
3300 static Context* GlobalContextFromLiterals(FixedArray* literals);
3301
3302 // Layout descriptors.
3303 static const int kPrototypeOrInitialMapOffset = JSObject::kHeaderSize;
3304 static const int kSharedFunctionInfoOffset =
3305 kPrototypeOrInitialMapOffset + kPointerSize;
3306 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
3307 static const int kLiteralsOffset = kContextOffset + kPointerSize;
3308 static const int kSize = kLiteralsOffset + kPointerSize;
3309
3310 // Layout of the literals array.
3311 static const int kLiteralsPrefixSize = 1;
3312 static const int kLiteralGlobalContextIndex = 0;
3313 private:
3314 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
3315};
3316
3317
3318// JSGlobalProxy's prototype must be a JSGlobalObject or null,
3319// and the prototype is hidden. JSGlobalProxy always delegates
3320// property accesses to its prototype if the prototype is not null.
3321//
3322// A JSGlobalProxy can be reinitialized which will preserve its identity.
3323//
3324// Accessing a JSGlobalProxy requires security check.
3325
3326class JSGlobalProxy : public JSObject {
3327 public:
3328 // [context]: the owner global context of this proxy object.
3329 // It is null value if this object is not used by any context.
3330 DECL_ACCESSORS(context, Object)
3331
3332 // Casting.
3333 static inline JSGlobalProxy* cast(Object* obj);
3334
3335 // Dispatched behavior.
3336#ifdef DEBUG
3337 void JSGlobalProxyPrint();
3338 void JSGlobalProxyVerify();
3339#endif
3340
3341 // Layout description.
3342 static const int kContextOffset = JSObject::kHeaderSize;
3343 static const int kSize = kContextOffset + kPointerSize;
3344
3345 private:
3346
3347 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
3348};
3349
3350
3351// Forward declaration.
3352class JSBuiltinsObject;
3353
3354// Common super class for JavaScript global objects and the special
3355// builtins global objects.
3356class GlobalObject: public JSObject {
3357 public:
3358 // [builtins]: the object holding the runtime routines written in JS.
3359 DECL_ACCESSORS(builtins, JSBuiltinsObject)
3360
3361 // [global context]: the global context corresponding to this global object.
3362 DECL_ACCESSORS(global_context, Context)
3363
3364 // [global receiver]: the global receiver object of the context
3365 DECL_ACCESSORS(global_receiver, JSObject)
3366
3367 // Retrieve the property cell used to store a property.
3368 Object* GetPropertyCell(LookupResult* result);
3369
3370 // Ensure that the global object has a cell for the given property name.
3371 Object* EnsurePropertyCell(String* name);
3372
3373 // Casting.
3374 static inline GlobalObject* cast(Object* obj);
3375
3376 // Layout description.
3377 static const int kBuiltinsOffset = JSObject::kHeaderSize;
3378 static const int kGlobalContextOffset = kBuiltinsOffset + kPointerSize;
3379 static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
3380 static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
3381
3382 private:
3383 friend class AGCCVersionRequiresThisClassToHaveAFriendSoHereItIs;
3384
3385 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
3386};
3387
3388
3389// JavaScript global object.
3390class JSGlobalObject: public GlobalObject {
3391 public:
3392
3393 // Casting.
3394 static inline JSGlobalObject* cast(Object* obj);
3395
3396 // Dispatched behavior.
3397#ifdef DEBUG
3398 void JSGlobalObjectPrint();
3399 void JSGlobalObjectVerify();
3400#endif
3401
3402 // Layout description.
3403 static const int kSize = GlobalObject::kHeaderSize;
3404
3405 private:
3406 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
3407};
3408
3409
3410// Builtins global object which holds the runtime routines written in
3411// JavaScript.
3412class JSBuiltinsObject: public GlobalObject {
3413 public:
3414 // Accessors for the runtime routines written in JavaScript.
3415 inline Object* javascript_builtin(Builtins::JavaScript id);
3416 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
3417
3418 // Casting.
3419 static inline JSBuiltinsObject* cast(Object* obj);
3420
3421 // Dispatched behavior.
3422#ifdef DEBUG
3423 void JSBuiltinsObjectPrint();
3424 void JSBuiltinsObjectVerify();
3425#endif
3426
3427 // Layout description. The size of the builtins object includes
3428 // room for one pointer per runtime routine written in javascript.
3429 static const int kJSBuiltinsCount = Builtins::id_count;
3430 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
3431 static const int kSize =
3432 kJSBuiltinsOffset + (kJSBuiltinsCount * kPointerSize);
3433 private:
3434 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
3435};
3436
3437
3438// Representation for JS Wrapper objects, String, Number, Boolean, Date, etc.
3439class JSValue: public JSObject {
3440 public:
3441 // [value]: the object being wrapped.
3442 DECL_ACCESSORS(value, Object)
3443
3444 // Casting.
3445 static inline JSValue* cast(Object* obj);
3446
3447 // Dispatched behavior.
3448#ifdef DEBUG
3449 void JSValuePrint();
3450 void JSValueVerify();
3451#endif
3452
3453 // Layout description.
3454 static const int kValueOffset = JSObject::kHeaderSize;
3455 static const int kSize = kValueOffset + kPointerSize;
3456
3457 private:
3458 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
3459};
3460
3461// Regular expressions
3462// The regular expression holds a single reference to a FixedArray in
3463// the kDataOffset field.
3464// The FixedArray contains the following data:
3465// - tag : type of regexp implementation (not compiled yet, atom or irregexp)
3466// - reference to the original source string
3467// - reference to the original flag string
3468// If it is an atom regexp
3469// - a reference to a literal string to search for
3470// If it is an irregexp regexp:
3471// - a reference to code for ASCII inputs (bytecode or compiled).
3472// - a reference to code for UC16 inputs (bytecode or compiled).
3473// - max number of registers used by irregexp implementations.
3474// - number of capture registers (output values) of the regexp.
3475class JSRegExp: public JSObject {
3476 public:
3477 // Meaning of Type:
3478 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
3479 // ATOM: A simple string to match against using an indexOf operation.
3480 // IRREGEXP: Compiled with Irregexp.
3481 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
3482 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
3483 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
3484
3485 class Flags {
3486 public:
3487 explicit Flags(uint32_t value) : value_(value) { }
3488 bool is_global() { return (value_ & GLOBAL) != 0; }
3489 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
3490 bool is_multiline() { return (value_ & MULTILINE) != 0; }
3491 uint32_t value() { return value_; }
3492 private:
3493 uint32_t value_;
3494 };
3495
3496 DECL_ACCESSORS(data, Object)
3497
3498 inline Type TypeTag();
3499 inline int CaptureCount();
3500 inline Flags GetFlags();
3501 inline String* Pattern();
3502 inline Object* DataAt(int index);
3503 // Set implementation data after the object has been prepared.
3504 inline void SetDataAt(int index, Object* value);
3505 static int code_index(bool is_ascii) {
3506 if (is_ascii) {
3507 return kIrregexpASCIICodeIndex;
3508 } else {
3509 return kIrregexpUC16CodeIndex;
3510 }
3511 }
3512
3513 static inline JSRegExp* cast(Object* obj);
3514
3515 // Dispatched behavior.
3516#ifdef DEBUG
3517 void JSRegExpVerify();
3518#endif
3519
3520 static const int kDataOffset = JSObject::kHeaderSize;
3521 static const int kSize = kDataOffset + kPointerSize;
3522
3523 // Indices in the data array.
3524 static const int kTagIndex = 0;
3525 static const int kSourceIndex = kTagIndex + 1;
3526 static const int kFlagsIndex = kSourceIndex + 1;
3527 static const int kDataIndex = kFlagsIndex + 1;
3528 // The data fields are used in different ways depending on the
3529 // value of the tag.
3530 // Atom regexps (literal strings).
3531 static const int kAtomPatternIndex = kDataIndex;
3532
3533 static const int kAtomDataSize = kAtomPatternIndex + 1;
3534
3535 // Irregexp compiled code or bytecode for ASCII. If compilation
3536 // fails, this fields hold an exception object that should be
3537 // thrown if the regexp is used again.
3538 static const int kIrregexpASCIICodeIndex = kDataIndex;
3539 // Irregexp compiled code or bytecode for UC16. If compilation
3540 // fails, this fields hold an exception object that should be
3541 // thrown if the regexp is used again.
3542 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
3543 // Maximal number of registers used by either ASCII or UC16.
3544 // Only used to check that there is enough stack space
3545 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 2;
3546 // Number of captures in the compiled regexp.
3547 static const int kIrregexpCaptureCountIndex = kDataIndex + 3;
3548
3549 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
3550};
3551
3552
3553class CompilationCacheShape {
3554 public:
3555 static inline bool IsMatch(HashTableKey* key, Object* value) {
3556 return key->IsMatch(value);
3557 }
3558
3559 static inline uint32_t Hash(HashTableKey* key) {
3560 return key->Hash();
3561 }
3562
3563 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3564 return key->HashForObject(object);
3565 }
3566
3567 static Object* AsObject(HashTableKey* key) {
3568 return key->AsObject();
3569 }
3570
3571 static const int kPrefixSize = 0;
3572 static const int kEntrySize = 2;
3573};
3574
3575class CompilationCacheTable: public HashTable<CompilationCacheShape,
3576 HashTableKey*> {
3577 public:
3578 // Find cached value for a string key, otherwise return null.
3579 Object* Lookup(String* src);
3580 Object* LookupEval(String* src, Context* context);
3581 Object* LookupRegExp(String* source, JSRegExp::Flags flags);
3582 Object* Put(String* src, Object* value);
3583 Object* PutEval(String* src, Context* context, Object* value);
3584 Object* PutRegExp(String* src, JSRegExp::Flags flags, FixedArray* value);
3585
3586 static inline CompilationCacheTable* cast(Object* obj);
3587
3588 private:
3589 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
3590};
3591
3592
3593enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
3594enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
3595
3596
3597class StringHasher {
3598 public:
3599 inline StringHasher(int length);
3600
3601 // Returns true if the hash of this string can be computed without
3602 // looking at the contents.
3603 inline bool has_trivial_hash();
3604
3605 // Add a character to the hash and update the array index calculation.
3606 inline void AddCharacter(uc32 c);
3607
3608 // Adds a character to the hash but does not update the array index
3609 // calculation. This can only be called when it has been verified
3610 // that the input is not an array index.
3611 inline void AddCharacterNoIndex(uc32 c);
3612
3613 // Returns the value to store in the hash field of a string with
3614 // the given length and contents.
3615 uint32_t GetHashField();
3616
3617 // Returns true if the characters seen so far make up a legal array
3618 // index.
3619 bool is_array_index() { return is_array_index_; }
3620
3621 bool is_valid() { return is_valid_; }
3622
3623 void invalidate() { is_valid_ = false; }
3624
3625 private:
3626
3627 uint32_t array_index() {
3628 ASSERT(is_array_index());
3629 return array_index_;
3630 }
3631
3632 inline uint32_t GetHash();
3633
3634 int length_;
3635 uint32_t raw_running_hash_;
3636 uint32_t array_index_;
3637 bool is_array_index_;
3638 bool is_first_char_;
3639 bool is_valid_;
3640};
3641
3642
3643// The characteristics of a string are stored in its map. Retrieving these
3644// few bits of information is moderately expensive, involving two memory
3645// loads where the second is dependent on the first. To improve efficiency
3646// the shape of the string is given its own class so that it can be retrieved
3647// once and used for several string operations. A StringShape is small enough
3648// to be passed by value and is immutable, but be aware that flattening a
3649// string can potentially alter its shape. Also be aware that a GC caused by
3650// something else can alter the shape of a string due to ConsString
3651// shortcutting. Keeping these restrictions in mind has proven to be error-
3652// prone and so we no longer put StringShapes in variables unless there is a
3653// concrete performance benefit at that particular point in the code.
3654class StringShape BASE_EMBEDDED {
3655 public:
3656 inline explicit StringShape(String* s);
3657 inline explicit StringShape(Map* s);
3658 inline explicit StringShape(InstanceType t);
3659 inline bool IsSequential();
3660 inline bool IsExternal();
3661 inline bool IsCons();
3662 inline bool IsSliced();
3663 inline bool IsExternalAscii();
3664 inline bool IsExternalTwoByte();
3665 inline bool IsSequentialAscii();
3666 inline bool IsSequentialTwoByte();
3667 inline bool IsSymbol();
3668 inline StringRepresentationTag representation_tag();
3669 inline uint32_t full_representation_tag();
3670 inline uint32_t size_tag();
3671#ifdef DEBUG
3672 inline uint32_t type() { return type_; }
3673 inline void invalidate() { valid_ = false; }
3674 inline bool valid() { return valid_; }
3675#else
3676 inline void invalidate() { }
3677#endif
3678 private:
3679 uint32_t type_;
3680#ifdef DEBUG
3681 inline void set_valid() { valid_ = true; }
3682 bool valid_;
3683#else
3684 inline void set_valid() { }
3685#endif
3686};
3687
3688
3689// The String abstract class captures JavaScript string values:
3690//
3691// Ecma-262:
3692// 4.3.16 String Value
3693// A string value is a member of the type String and is a finite
3694// ordered sequence of zero or more 16-bit unsigned integer values.
3695//
3696// All string values have a length field.
3697class String: public HeapObject {
3698 public:
3699 // Get and set the length of the string.
3700 inline int length();
3701 inline void set_length(int value);
3702
3703 // Get and set the uninterpreted length field of the string. Notice
3704 // that the length field is also used to cache the hash value of
3705 // strings. In order to get or set the actual length of the string
3706 // use the length() and set_length methods.
3707 inline uint32_t length_field();
3708 inline void set_length_field(uint32_t value);
3709
3710 inline bool IsAsciiRepresentation();
3711 inline bool IsTwoByteRepresentation();
3712
3713 // Get and set individual two byte chars in the string.
3714 inline void Set(int index, uint16_t value);
3715 // Get individual two byte char in the string. Repeated calls
3716 // to this method are not efficient unless the string is flat.
3717 inline uint16_t Get(int index);
3718
3719 // Try to flatten the top level ConsString that is hiding behind this
3720 // string. This is a no-op unless the string is a ConsString or a
3721 // SlicedString. Flatten mutates the ConsString and might return a
3722 // failure.
3723 Object* TryFlatten();
3724
3725 // Try to flatten the string. Checks first inline to see if it is necessary.
3726 // Do not handle allocation failures. After calling TryFlattenIfNotFlat, the
3727 // string could still be a ConsString, in which case a failure is returned.
3728 // Use FlattenString from Handles.cc to be sure to flatten.
3729 inline Object* TryFlattenIfNotFlat();
3730
3731 Vector<const char> ToAsciiVector();
3732 Vector<const uc16> ToUC16Vector();
3733
3734 // Mark the string as an undetectable object. It only applies to
3735 // ascii and two byte string types.
3736 bool MarkAsUndetectable();
3737
3738 // Slice the string and return a substring.
3739 Object* Slice(int from, int to);
3740
3741 // String equality operations.
3742 inline bool Equals(String* other);
3743 bool IsEqualTo(Vector<const char> str);
3744
3745 // Return a UTF8 representation of the string. The string is null
3746 // terminated but may optionally contain nulls. Length is returned
3747 // in length_output if length_output is not a null pointer The string
3748 // should be nearly flat, otherwise the performance of this method may
3749 // be very slow (quadratic in the length). Setting robustness_flag to
3750 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
3751 // handles unexpected data without causing assert failures and it does not
3752 // do any heap allocations. This is useful when printing stack traces.
3753 SmartPointer<char> ToCString(AllowNullsFlag allow_nulls,
3754 RobustnessFlag robustness_flag,
3755 int offset,
3756 int length,
3757 int* length_output = 0);
3758 SmartPointer<char> ToCString(
3759 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
3760 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
3761 int* length_output = 0);
3762
3763 int Utf8Length();
3764
3765 // Return a 16 bit Unicode representation of the string.
3766 // The string should be nearly flat, otherwise the performance of
3767 // of this method may be very bad. Setting robustness_flag to
3768 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
3769 // handles unexpected data without causing assert failures and it does not
3770 // do any heap allocations. This is useful when printing stack traces.
3771 SmartPointer<uc16> ToWideCString(
3772 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
3773
3774 // Tells whether the hash code has been computed.
3775 inline bool HasHashCode();
3776
3777 // Returns a hash value used for the property table
3778 inline uint32_t Hash();
3779
3780 static uint32_t ComputeLengthAndHashField(unibrow::CharacterStream* buffer,
3781 int length);
3782
3783 static bool ComputeArrayIndex(unibrow::CharacterStream* buffer,
3784 uint32_t* index,
3785 int length);
3786
3787 // Externalization.
3788 bool MakeExternal(v8::String::ExternalStringResource* resource);
3789 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
3790
3791 // Conversion.
3792 inline bool AsArrayIndex(uint32_t* index);
3793
3794 // Casting.
3795 static inline String* cast(Object* obj);
3796
3797 void PrintOn(FILE* out);
3798
3799 // For use during stack traces. Performs rudimentary sanity check.
3800 bool LooksValid();
3801
3802 // Dispatched behavior.
3803 void StringShortPrint(StringStream* accumulator);
3804#ifdef DEBUG
3805 void StringPrint();
3806 void StringVerify();
3807#endif
3808 inline bool IsFlat();
3809
3810 // Layout description.
3811 static const int kLengthOffset = HeapObject::kHeaderSize;
3812 static const int kSize = kLengthOffset + kIntSize;
3813 // Notice: kSize is not pointer-size aligned if pointers are 64-bit.
3814
3815 // Limits on sizes of different types of strings.
3816 static const int kMaxShortStringSize = 63;
3817 static const int kMaxMediumStringSize = 16383;
3818
3819 static const int kMaxArrayIndexSize = 10;
3820
3821 // Max ascii char code.
3822 static const int kMaxAsciiCharCode = unibrow::Utf8::kMaxOneByteChar;
3823 static const unsigned kMaxAsciiCharCodeU = unibrow::Utf8::kMaxOneByteChar;
3824 static const int kMaxUC16CharCode = 0xffff;
3825
3826 // Minimum length for a cons or sliced string.
3827 static const int kMinNonFlatLength = 13;
3828
3829 // Mask constant for checking if a string has a computed hash code
3830 // and if it is an array index. The least significant bit indicates
3831 // whether a hash code has been computed. If the hash code has been
3832 // computed the 2nd bit tells whether the string can be used as an
3833 // array index.
3834 static const int kHashComputedMask = 1;
3835 static const int kIsArrayIndexMask = 1 << 1;
3836 static const int kNofLengthBitFields = 2;
3837
3838 // Array index strings this short can keep their index in the hash
3839 // field.
3840 static const int kMaxCachedArrayIndexLength = 7;
3841
3842 // Shift constants for retriving length and hash code from
3843 // length/hash field.
3844 static const int kHashShift = kNofLengthBitFields;
3845 static const int kShortLengthShift = kHashShift + kShortStringTag;
3846 static const int kMediumLengthShift = kHashShift + kMediumStringTag;
3847 static const int kLongLengthShift = kHashShift + kLongStringTag;
3848
3849 // Limit for truncation in short printing.
3850 static const int kMaxShortPrintLength = 1024;
3851
3852 // Support for regular expressions.
3853 const uc16* GetTwoByteData();
3854 const uc16* GetTwoByteData(unsigned start);
3855
3856 // Support for StringInputBuffer
3857 static const unibrow::byte* ReadBlock(String* input,
3858 unibrow::byte* util_buffer,
3859 unsigned capacity,
3860 unsigned* remaining,
3861 unsigned* offset);
3862 static const unibrow::byte* ReadBlock(String** input,
3863 unibrow::byte* util_buffer,
3864 unsigned capacity,
3865 unsigned* remaining,
3866 unsigned* offset);
3867
3868 // Helper function for flattening strings.
3869 template <typename sinkchar>
3870 static void WriteToFlat(String* source,
3871 sinkchar* sink,
3872 int from,
3873 int to);
3874
3875 protected:
3876 class ReadBlockBuffer {
3877 public:
3878 ReadBlockBuffer(unibrow::byte* util_buffer_,
3879 unsigned cursor_,
3880 unsigned capacity_,
3881 unsigned remaining_) :
3882 util_buffer(util_buffer_),
3883 cursor(cursor_),
3884 capacity(capacity_),
3885 remaining(remaining_) {
3886 }
3887 unibrow::byte* util_buffer;
3888 unsigned cursor;
3889 unsigned capacity;
3890 unsigned remaining;
3891 };
3892
3893 // NOTE: If you call StringInputBuffer routines on strings that are
3894 // too deeply nested trees of cons and slice strings, then this
3895 // routine will overflow the stack. Strings that are merely deeply
3896 // nested trees of cons strings do not have a problem apart from
3897 // performance.
3898
3899 static inline const unibrow::byte* ReadBlock(String* input,
3900 ReadBlockBuffer* buffer,
3901 unsigned* offset,
3902 unsigned max_chars);
3903 static void ReadBlockIntoBuffer(String* input,
3904 ReadBlockBuffer* buffer,
3905 unsigned* offset_ptr,
3906 unsigned max_chars);
3907
3908 private:
3909 // Slow case of String::Equals. This implementation works on any strings
3910 // but it is most efficient on strings that are almost flat.
3911 bool SlowEquals(String* other);
3912
3913 // Slow case of AsArrayIndex.
3914 bool SlowAsArrayIndex(uint32_t* index);
3915
3916 // Compute and set the hash code.
3917 uint32_t ComputeAndSetHash();
3918
3919 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
3920};
3921
3922
3923// The SeqString abstract class captures sequential string values.
3924class SeqString: public String {
3925 public:
3926
3927 // Casting.
3928 static inline SeqString* cast(Object* obj);
3929
3930 // Dispatched behaviour.
3931 // For regexp code.
3932 uint16_t* SeqStringGetTwoByteAddress();
3933
3934 private:
3935 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
3936};
3937
3938
3939// The AsciiString class captures sequential ascii string objects.
3940// Each character in the AsciiString is an ascii character.
3941class SeqAsciiString: public SeqString {
3942 public:
3943 // Dispatched behavior.
3944 inline uint16_t SeqAsciiStringGet(int index);
3945 inline void SeqAsciiStringSet(int index, uint16_t value);
3946
3947 // Get the address of the characters in this string.
3948 inline Address GetCharsAddress();
3949
3950 inline char* GetChars();
3951
3952 // Casting
3953 static inline SeqAsciiString* cast(Object* obj);
3954
3955 // Garbage collection support. This method is called by the
3956 // garbage collector to compute the actual size of an AsciiString
3957 // instance.
3958 inline int SeqAsciiStringSize(InstanceType instance_type);
3959
3960 // Computes the size for an AsciiString instance of a given length.
3961 static int SizeFor(int length) {
3962 return OBJECT_SIZE_ALIGN(kHeaderSize + length * kCharSize);
3963 }
3964
3965 // Layout description.
3966 static const int kHeaderSize = String::kSize;
3967 static const int kAlignedSize = POINTER_SIZE_ALIGN(kHeaderSize);
3968
3969 // Support for StringInputBuffer.
3970 inline void SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
3971 unsigned* offset,
3972 unsigned chars);
3973 inline const unibrow::byte* SeqAsciiStringReadBlock(unsigned* remaining,
3974 unsigned* offset,
3975 unsigned chars);
3976
3977 private:
3978 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqAsciiString);
3979};
3980
3981
3982// The TwoByteString class captures sequential unicode string objects.
3983// Each character in the TwoByteString is a two-byte uint16_t.
3984class SeqTwoByteString: public SeqString {
3985 public:
3986 // Dispatched behavior.
3987 inline uint16_t SeqTwoByteStringGet(int index);
3988 inline void SeqTwoByteStringSet(int index, uint16_t value);
3989
3990 // Get the address of the characters in this string.
3991 inline Address GetCharsAddress();
3992
3993 inline uc16* GetChars();
3994
3995 // For regexp code.
3996 const uint16_t* SeqTwoByteStringGetData(unsigned start);
3997
3998 // Casting
3999 static inline SeqTwoByteString* cast(Object* obj);
4000
4001 // Garbage collection support. This method is called by the
4002 // garbage collector to compute the actual size of a TwoByteString
4003 // instance.
4004 inline int SeqTwoByteStringSize(InstanceType instance_type);
4005
4006 // Computes the size for a TwoByteString instance of a given length.
4007 static int SizeFor(int length) {
4008 return OBJECT_SIZE_ALIGN(kHeaderSize + length * kShortSize);
4009 }
4010
4011 // Layout description.
4012 static const int kHeaderSize = String::kSize;
4013 static const int kAlignedSize = POINTER_SIZE_ALIGN(kHeaderSize);
4014
4015 // Support for StringInputBuffer.
4016 inline void SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
4017 unsigned* offset_ptr,
4018 unsigned chars);
4019
4020 private:
4021 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
4022};
4023
4024
4025// The ConsString class describes string values built by using the
4026// addition operator on strings. A ConsString is a pair where the
4027// first and second components are pointers to other string values.
4028// One or both components of a ConsString can be pointers to other
4029// ConsStrings, creating a binary tree of ConsStrings where the leaves
4030// are non-ConsString string values. The string value represented by
4031// a ConsString can be obtained by concatenating the leaf string
4032// values in a left-to-right depth-first traversal of the tree.
4033class ConsString: public String {
4034 public:
4035 // First string of the cons cell.
4036 inline String* first();
4037 // Doesn't check that the result is a string, even in debug mode. This is
4038 // useful during GC where the mark bits confuse the checks.
4039 inline Object* unchecked_first();
4040 inline void set_first(String* first,
4041 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4042
4043 // Second string of the cons cell.
4044 inline String* second();
4045 // Doesn't check that the result is a string, even in debug mode. This is
4046 // useful during GC where the mark bits confuse the checks.
4047 inline Object* unchecked_second();
4048 inline void set_second(String* second,
4049 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4050
4051 // Dispatched behavior.
4052 uint16_t ConsStringGet(int index);
4053
4054 // Casting.
4055 static inline ConsString* cast(Object* obj);
4056
4057 // Garbage collection support. This method is called during garbage
4058 // collection to iterate through the heap pointers in the body of
4059 // the ConsString.
4060 void ConsStringIterateBody(ObjectVisitor* v);
4061
4062 // Layout description.
4063 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
4064 static const int kSecondOffset = kFirstOffset + kPointerSize;
4065 static const int kSize = kSecondOffset + kPointerSize;
4066
4067 // Support for StringInputBuffer.
4068 inline const unibrow::byte* ConsStringReadBlock(ReadBlockBuffer* buffer,
4069 unsigned* offset_ptr,
4070 unsigned chars);
4071 inline void ConsStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
4072 unsigned* offset_ptr,
4073 unsigned chars);
4074
4075 // Minimum length for a cons string.
4076 static const int kMinLength = 13;
4077
4078 private:
4079 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
4080};
4081
4082
4083// The SlicedString class describes string values that are slices of
4084// some other string. SlicedStrings consist of a reference to an
4085// underlying heap-allocated string value, a start index, and the
4086// length field common to all strings.
4087class SlicedString: public String {
4088 public:
4089 // The underlying string buffer.
4090 inline String* buffer();
4091 inline void set_buffer(String* buffer);
4092
4093 // The start index of the slice.
4094 inline int start();
4095 inline void set_start(int start);
4096
4097 // Dispatched behavior.
4098 uint16_t SlicedStringGet(int index);
4099
4100 // Casting.
4101 static inline SlicedString* cast(Object* obj);
4102
4103 // Garbage collection support.
4104 void SlicedStringIterateBody(ObjectVisitor* v);
4105
4106 // Layout description
4107#if V8_HOST_ARCH_64_BIT
4108 // Optimizations expect buffer to be located at same offset as a ConsString's
4109 // first substring. In 64 bit mode we have room for the start offset before
4110 // the buffer.
4111 static const int kStartOffset = String::kSize;
4112 static const int kBufferOffset = kStartOffset + kIntSize;
4113 static const int kSize = kBufferOffset + kPointerSize;
4114#else
4115 static const int kBufferOffset = String::kSize;
4116 static const int kStartOffset = kBufferOffset + kPointerSize;
4117 static const int kSize = kStartOffset + kIntSize;
4118#endif
4119
4120 // Support for StringInputBuffer.
4121 inline const unibrow::byte* SlicedStringReadBlock(ReadBlockBuffer* buffer,
4122 unsigned* offset_ptr,
4123 unsigned chars);
4124 inline void SlicedStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
4125 unsigned* offset_ptr,
4126 unsigned chars);
4127
4128 private:
4129 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
4130};
4131
4132
4133// The ExternalString class describes string values that are backed by
4134// a string resource that lies outside the V8 heap. ExternalStrings
4135// consist of the length field common to all strings, a pointer to the
4136// external resource. It is important to ensure (externally) that the
4137// resource is not deallocated while the ExternalString is live in the
4138// V8 heap.
4139//
4140// The API expects that all ExternalStrings are created through the
4141// API. Therefore, ExternalStrings should not be used internally.
4142class ExternalString: public String {
4143 public:
4144 // Casting
4145 static inline ExternalString* cast(Object* obj);
4146
4147 // Layout description.
4148 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
4149 static const int kSize = kResourceOffset + kPointerSize;
4150
4151 STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
4152
4153 private:
4154 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
4155};
4156
4157
4158// The ExternalAsciiString class is an external string backed by an
4159// ASCII string.
4160class ExternalAsciiString: public ExternalString {
4161 public:
4162 typedef v8::String::ExternalAsciiStringResource Resource;
4163
4164 // The underlying resource.
4165 inline Resource* resource();
4166 inline void set_resource(Resource* buffer);
4167
4168 // Dispatched behavior.
4169 uint16_t ExternalAsciiStringGet(int index);
4170
4171 // Casting.
4172 static inline ExternalAsciiString* cast(Object* obj);
4173
4174 // Support for StringInputBuffer.
4175 const unibrow::byte* ExternalAsciiStringReadBlock(unsigned* remaining,
4176 unsigned* offset,
4177 unsigned chars);
4178 inline void ExternalAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
4179 unsigned* offset,
4180 unsigned chars);
4181
4182 // Identify the map for the external string/symbol with a particular length.
4183 static inline Map* StringMap(int length);
4184 static inline Map* SymbolMap(int length);
4185 private:
4186 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
4187};
4188
4189
4190// The ExternalTwoByteString class is an external string backed by a UTF-16
4191// encoded string.
4192class ExternalTwoByteString: public ExternalString {
4193 public:
4194 typedef v8::String::ExternalStringResource Resource;
4195
4196 // The underlying string resource.
4197 inline Resource* resource();
4198 inline void set_resource(Resource* buffer);
4199
4200 // Dispatched behavior.
4201 uint16_t ExternalTwoByteStringGet(int index);
4202
4203 // For regexp code.
4204 const uint16_t* ExternalTwoByteStringGetData(unsigned start);
4205
4206 // Casting.
4207 static inline ExternalTwoByteString* cast(Object* obj);
4208
4209 // Support for StringInputBuffer.
4210 void ExternalTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
4211 unsigned* offset_ptr,
4212 unsigned chars);
4213
4214 // Identify the map for the external string/symbol with a particular length.
4215 static inline Map* StringMap(int length);
4216 static inline Map* SymbolMap(int length);
4217 private:
4218 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
4219};
4220
4221
4222// Utility superclass for stack-allocated objects that must be updated
4223// on gc. It provides two ways for the gc to update instances, either
4224// iterating or updating after gc.
4225class Relocatable BASE_EMBEDDED {
4226 public:
4227 inline Relocatable() : prev_(top_) { top_ = this; }
4228 virtual ~Relocatable() {
4229 ASSERT_EQ(top_, this);
4230 top_ = prev_;
4231 }
4232 virtual void IterateInstance(ObjectVisitor* v) { }
4233 virtual void PostGarbageCollection() { }
4234
4235 static void PostGarbageCollectionProcessing();
4236 static int ArchiveSpacePerThread();
4237 static char* ArchiveState(char* to);
4238 static char* RestoreState(char* from);
4239 static void Iterate(ObjectVisitor* v);
4240 static void Iterate(ObjectVisitor* v, Relocatable* top);
4241 static char* Iterate(ObjectVisitor* v, char* t);
4242 private:
4243 static Relocatable* top_;
4244 Relocatable* prev_;
4245};
4246
4247
4248// A flat string reader provides random access to the contents of a
4249// string independent of the character width of the string. The handle
4250// must be valid as long as the reader is being used.
4251class FlatStringReader : public Relocatable {
4252 public:
4253 explicit FlatStringReader(Handle<String> str);
4254 explicit FlatStringReader(Vector<const char> input);
4255 void PostGarbageCollection();
4256 inline uc32 Get(int index);
4257 int length() { return length_; }
4258 private:
4259 String** str_;
4260 bool is_ascii_;
4261 int length_;
4262 const void* start_;
4263};
4264
4265
4266// Note that StringInputBuffers are not valid across a GC! To fix this
4267// it would have to store a String Handle instead of a String* and
4268// AsciiStringReadBlock would have to be modified to use memcpy.
4269//
4270// StringInputBuffer is able to traverse any string regardless of how
4271// deeply nested a sequence of ConsStrings it is made of. However,
4272// performance will be better if deep strings are flattened before they
4273// are traversed. Since flattening requires memory allocation this is
4274// not always desirable, however (esp. in debugging situations).
4275class StringInputBuffer: public unibrow::InputBuffer<String, String*, 1024> {
4276 public:
4277 virtual void Seek(unsigned pos);
4278 inline StringInputBuffer(): unibrow::InputBuffer<String, String*, 1024>() {}
4279 inline StringInputBuffer(String* backing):
4280 unibrow::InputBuffer<String, String*, 1024>(backing) {}
4281};
4282
4283
4284class SafeStringInputBuffer
4285 : public unibrow::InputBuffer<String, String**, 256> {
4286 public:
4287 virtual void Seek(unsigned pos);
4288 inline SafeStringInputBuffer()
4289 : unibrow::InputBuffer<String, String**, 256>() {}
4290 inline SafeStringInputBuffer(String** backing)
4291 : unibrow::InputBuffer<String, String**, 256>(backing) {}
4292};
4293
4294
4295template <typename T>
4296class VectorIterator {
4297 public:
4298 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
4299 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
4300 T GetNext() { return data_[index_++]; }
4301 bool has_more() { return index_ < data_.length(); }
4302 private:
4303 Vector<const T> data_;
4304 int index_;
4305};
4306
4307
4308// The Oddball describes objects null, undefined, true, and false.
4309class Oddball: public HeapObject {
4310 public:
4311 // [to_string]: Cached to_string computed at startup.
4312 DECL_ACCESSORS(to_string, String)
4313
4314 // [to_number]: Cached to_number computed at startup.
4315 DECL_ACCESSORS(to_number, Object)
4316
4317 // Casting.
4318 static inline Oddball* cast(Object* obj);
4319
4320 // Dispatched behavior.
4321 void OddballIterateBody(ObjectVisitor* v);
4322#ifdef DEBUG
4323 void OddballVerify();
4324#endif
4325
4326 // Initialize the fields.
4327 Object* Initialize(const char* to_string, Object* to_number);
4328
4329 // Layout description.
4330 static const int kToStringOffset = HeapObject::kHeaderSize;
4331 static const int kToNumberOffset = kToStringOffset + kPointerSize;
4332 static const int kSize = kToNumberOffset + kPointerSize;
4333
4334 private:
4335 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
4336};
4337
4338
4339class JSGlobalPropertyCell: public HeapObject {
4340 public:
4341 // [value]: value of the global property.
4342 DECL_ACCESSORS(value, Object)
4343
4344 // Casting.
4345 static inline JSGlobalPropertyCell* cast(Object* obj);
4346
4347 // Dispatched behavior.
4348 void JSGlobalPropertyCellIterateBody(ObjectVisitor* v);
4349#ifdef DEBUG
4350 void JSGlobalPropertyCellVerify();
4351 void JSGlobalPropertyCellPrint();
4352#endif
4353
4354 // Layout description.
4355 static const int kValueOffset = HeapObject::kHeaderSize;
4356 static const int kSize = kValueOffset + kPointerSize;
4357
4358 private:
4359 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalPropertyCell);
4360};
4361
4362
4363
4364// Proxy describes objects pointing from JavaScript to C structures.
4365// Since they cannot contain references to JS HeapObjects they can be
4366// placed in old_data_space.
4367class Proxy: public HeapObject {
4368 public:
4369 // [proxy]: field containing the address.
4370 inline Address proxy();
4371 inline void set_proxy(Address value);
4372
4373 // Casting.
4374 static inline Proxy* cast(Object* obj);
4375
4376 // Dispatched behavior.
4377 inline void ProxyIterateBody(ObjectVisitor* v);
4378#ifdef DEBUG
4379 void ProxyPrint();
4380 void ProxyVerify();
4381#endif
4382
4383 // Layout description.
4384
4385 static const int kProxyOffset = HeapObject::kHeaderSize;
4386 static const int kSize = kProxyOffset + kPointerSize;
4387
4388 STATIC_CHECK(kProxyOffset == Internals::kProxyProxyOffset);
4389
4390 private:
4391 DISALLOW_IMPLICIT_CONSTRUCTORS(Proxy);
4392};
4393
4394
4395// The JSArray describes JavaScript Arrays
4396// Such an array can be in one of two modes:
4397// - fast, backing storage is a FixedArray and length <= elements.length();
4398// Please note: push and pop can be used to grow and shrink the array.
4399// - slow, backing storage is a HashTable with numbers as keys.
4400class JSArray: public JSObject {
4401 public:
4402 // [length]: The length property.
4403 DECL_ACCESSORS(length, Object)
4404
4405 Object* JSArrayUpdateLengthFromIndex(uint32_t index, Object* value);
4406
4407 // Initialize the array with the given capacity. The function may
4408 // fail due to out-of-memory situations, but only if the requested
4409 // capacity is non-zero.
4410 Object* Initialize(int capacity);
4411
4412 // Set the content of the array to the content of storage.
4413 inline void SetContent(FixedArray* storage);
4414
4415 // Casting.
4416 static inline JSArray* cast(Object* obj);
4417
4418 // Uses handles. Ensures that the fixed array backing the JSArray has at
4419 // least the stated size.
4420 inline void EnsureSize(int minimum_size_of_backing_fixed_array);
4421
4422 // Dispatched behavior.
4423#ifdef DEBUG
4424 void JSArrayPrint();
4425 void JSArrayVerify();
4426#endif
4427
4428 // Number of element slots to pre-allocate for an empty array.
4429 static const int kPreallocatedArrayElements = 4;
4430
4431 // Layout description.
4432 static const int kLengthOffset = JSObject::kHeaderSize;
4433 static const int kSize = kLengthOffset + kPointerSize;
4434
4435 private:
4436 // Expand the fixed array backing of a fast-case JSArray to at least
4437 // the requested size.
4438 void Expand(int minimum_size_of_backing_fixed_array);
4439
4440 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
4441};
4442
4443
4444// An accessor must have a getter, but can have no setter.
4445//
4446// When setting a property, V8 searches accessors in prototypes.
4447// If an accessor was found and it does not have a setter,
4448// the request is ignored.
4449//
4450// If the accessor in the prototype has the READ_ONLY property attribute, then
4451// a new value is added to the local object when the property is set.
4452// This shadows the accessor in the prototype.
4453class AccessorInfo: public Struct {
4454 public:
4455 DECL_ACCESSORS(getter, Object)
4456 DECL_ACCESSORS(setter, Object)
4457 DECL_ACCESSORS(data, Object)
4458 DECL_ACCESSORS(name, Object)
4459 DECL_ACCESSORS(flag, Smi)
4460
4461 inline bool all_can_read();
4462 inline void set_all_can_read(bool value);
4463
4464 inline bool all_can_write();
4465 inline void set_all_can_write(bool value);
4466
4467 inline bool prohibits_overwriting();
4468 inline void set_prohibits_overwriting(bool value);
4469
4470 inline PropertyAttributes property_attributes();
4471 inline void set_property_attributes(PropertyAttributes attributes);
4472
4473 static inline AccessorInfo* cast(Object* obj);
4474
4475#ifdef DEBUG
4476 void AccessorInfoPrint();
4477 void AccessorInfoVerify();
4478#endif
4479
4480 static const int kGetterOffset = HeapObject::kHeaderSize;
4481 static const int kSetterOffset = kGetterOffset + kPointerSize;
4482 static const int kDataOffset = kSetterOffset + kPointerSize;
4483 static const int kNameOffset = kDataOffset + kPointerSize;
4484 static const int kFlagOffset = kNameOffset + kPointerSize;
4485 static const int kSize = kFlagOffset + kPointerSize;
4486
4487 private:
4488 // Bit positions in flag.
4489 static const int kAllCanReadBit = 0;
4490 static const int kAllCanWriteBit = 1;
4491 static const int kProhibitsOverwritingBit = 2;
4492 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
4493
4494 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
4495};
4496
4497
4498class AccessCheckInfo: public Struct {
4499 public:
4500 DECL_ACCESSORS(named_callback, Object)
4501 DECL_ACCESSORS(indexed_callback, Object)
4502 DECL_ACCESSORS(data, Object)
4503
4504 static inline AccessCheckInfo* cast(Object* obj);
4505
4506#ifdef DEBUG
4507 void AccessCheckInfoPrint();
4508 void AccessCheckInfoVerify();
4509#endif
4510
4511 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
4512 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
4513 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
4514 static const int kSize = kDataOffset + kPointerSize;
4515
4516 private:
4517 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
4518};
4519
4520
4521class InterceptorInfo: public Struct {
4522 public:
4523 DECL_ACCESSORS(getter, Object)
4524 DECL_ACCESSORS(setter, Object)
4525 DECL_ACCESSORS(query, Object)
4526 DECL_ACCESSORS(deleter, Object)
4527 DECL_ACCESSORS(enumerator, Object)
4528 DECL_ACCESSORS(data, Object)
4529
4530 static inline InterceptorInfo* cast(Object* obj);
4531
4532#ifdef DEBUG
4533 void InterceptorInfoPrint();
4534 void InterceptorInfoVerify();
4535#endif
4536
4537 static const int kGetterOffset = HeapObject::kHeaderSize;
4538 static const int kSetterOffset = kGetterOffset + kPointerSize;
4539 static const int kQueryOffset = kSetterOffset + kPointerSize;
4540 static const int kDeleterOffset = kQueryOffset + kPointerSize;
4541 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
4542 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
4543 static const int kSize = kDataOffset + kPointerSize;
4544
4545 private:
4546 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
4547};
4548
4549
4550class CallHandlerInfo: public Struct {
4551 public:
4552 DECL_ACCESSORS(callback, Object)
4553 DECL_ACCESSORS(data, Object)
4554
4555 static inline CallHandlerInfo* cast(Object* obj);
4556
4557#ifdef DEBUG
4558 void CallHandlerInfoPrint();
4559 void CallHandlerInfoVerify();
4560#endif
4561
4562 static const int kCallbackOffset = HeapObject::kHeaderSize;
4563 static const int kDataOffset = kCallbackOffset + kPointerSize;
4564 static const int kSize = kDataOffset + kPointerSize;
4565
4566 private:
4567 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
4568};
4569
4570
4571class TemplateInfo: public Struct {
4572 public:
4573 DECL_ACCESSORS(tag, Object)
4574 DECL_ACCESSORS(property_list, Object)
4575
4576#ifdef DEBUG
4577 void TemplateInfoVerify();
4578#endif
4579
4580 static const int kTagOffset = HeapObject::kHeaderSize;
4581 static const int kPropertyListOffset = kTagOffset + kPointerSize;
4582 static const int kHeaderSize = kPropertyListOffset + kPointerSize;
4583 protected:
4584 friend class AGCCVersionRequiresThisClassToHaveAFriendSoHereItIs;
4585 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
4586};
4587
4588
4589class FunctionTemplateInfo: public TemplateInfo {
4590 public:
4591 DECL_ACCESSORS(serial_number, Object)
4592 DECL_ACCESSORS(call_code, Object)
4593 DECL_ACCESSORS(property_accessors, Object)
4594 DECL_ACCESSORS(prototype_template, Object)
4595 DECL_ACCESSORS(parent_template, Object)
4596 DECL_ACCESSORS(named_property_handler, Object)
4597 DECL_ACCESSORS(indexed_property_handler, Object)
4598 DECL_ACCESSORS(instance_template, Object)
4599 DECL_ACCESSORS(class_name, Object)
4600 DECL_ACCESSORS(signature, Object)
4601 DECL_ACCESSORS(instance_call_handler, Object)
4602 DECL_ACCESSORS(access_check_info, Object)
4603 DECL_ACCESSORS(flag, Smi)
4604
4605 // Following properties use flag bits.
4606 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
4607 DECL_BOOLEAN_ACCESSORS(undetectable)
4608 // If the bit is set, object instances created by this function
4609 // requires access check.
4610 DECL_BOOLEAN_ACCESSORS(needs_access_check)
4611
4612 static inline FunctionTemplateInfo* cast(Object* obj);
4613
4614#ifdef DEBUG
4615 void FunctionTemplateInfoPrint();
4616 void FunctionTemplateInfoVerify();
4617#endif
4618
4619 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
4620 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
4621 static const int kPropertyAccessorsOffset = kCallCodeOffset + kPointerSize;
4622 static const int kPrototypeTemplateOffset =
4623 kPropertyAccessorsOffset + kPointerSize;
4624 static const int kParentTemplateOffset =
4625 kPrototypeTemplateOffset + kPointerSize;
4626 static const int kNamedPropertyHandlerOffset =
4627 kParentTemplateOffset + kPointerSize;
4628 static const int kIndexedPropertyHandlerOffset =
4629 kNamedPropertyHandlerOffset + kPointerSize;
4630 static const int kInstanceTemplateOffset =
4631 kIndexedPropertyHandlerOffset + kPointerSize;
4632 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
4633 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
4634 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
4635 static const int kAccessCheckInfoOffset =
4636 kInstanceCallHandlerOffset + kPointerSize;
4637 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
4638 static const int kSize = kFlagOffset + kPointerSize;
4639
4640 private:
4641 // Bit position in the flag, from least significant bit position.
4642 static const int kHiddenPrototypeBit = 0;
4643 static const int kUndetectableBit = 1;
4644 static const int kNeedsAccessCheckBit = 2;
4645
4646 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
4647};
4648
4649
4650class ObjectTemplateInfo: public TemplateInfo {
4651 public:
4652 DECL_ACCESSORS(constructor, Object)
4653 DECL_ACCESSORS(internal_field_count, Object)
4654
4655 static inline ObjectTemplateInfo* cast(Object* obj);
4656
4657#ifdef DEBUG
4658 void ObjectTemplateInfoPrint();
4659 void ObjectTemplateInfoVerify();
4660#endif
4661
4662 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
4663 static const int kInternalFieldCountOffset =
4664 kConstructorOffset + kPointerSize;
4665 static const int kSize = kInternalFieldCountOffset + kPointerSize;
4666};
4667
4668
4669class SignatureInfo: public Struct {
4670 public:
4671 DECL_ACCESSORS(receiver, Object)
4672 DECL_ACCESSORS(args, Object)
4673
4674 static inline SignatureInfo* cast(Object* obj);
4675
4676#ifdef DEBUG
4677 void SignatureInfoPrint();
4678 void SignatureInfoVerify();
4679#endif
4680
4681 static const int kReceiverOffset = Struct::kHeaderSize;
4682 static const int kArgsOffset = kReceiverOffset + kPointerSize;
4683 static const int kSize = kArgsOffset + kPointerSize;
4684
4685 private:
4686 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
4687};
4688
4689
4690class TypeSwitchInfo: public Struct {
4691 public:
4692 DECL_ACCESSORS(types, Object)
4693
4694 static inline TypeSwitchInfo* cast(Object* obj);
4695
4696#ifdef DEBUG
4697 void TypeSwitchInfoPrint();
4698 void TypeSwitchInfoVerify();
4699#endif
4700
4701 static const int kTypesOffset = Struct::kHeaderSize;
4702 static const int kSize = kTypesOffset + kPointerSize;
4703};
4704
4705
4706#ifdef ENABLE_DEBUGGER_SUPPORT
4707// The DebugInfo class holds additional information for a function being
4708// debugged.
4709class DebugInfo: public Struct {
4710 public:
4711 // The shared function info for the source being debugged.
4712 DECL_ACCESSORS(shared, SharedFunctionInfo)
4713 // Code object for the original code.
4714 DECL_ACCESSORS(original_code, Code)
4715 // Code object for the patched code. This code object is the code object
4716 // currently active for the function.
4717 DECL_ACCESSORS(code, Code)
4718 // Fixed array holding status information for each active break point.
4719 DECL_ACCESSORS(break_points, FixedArray)
4720
4721 // Check if there is a break point at a code position.
4722 bool HasBreakPoint(int code_position);
4723 // Get the break point info object for a code position.
4724 Object* GetBreakPointInfo(int code_position);
4725 // Clear a break point.
4726 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
4727 int code_position,
4728 Handle<Object> break_point_object);
4729 // Set a break point.
4730 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
4731 int source_position, int statement_position,
4732 Handle<Object> break_point_object);
4733 // Get the break point objects for a code position.
4734 Object* GetBreakPointObjects(int code_position);
4735 // Find the break point info holding this break point object.
4736 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
4737 Handle<Object> break_point_object);
4738 // Get the number of break points for this function.
4739 int GetBreakPointCount();
4740
4741 static inline DebugInfo* cast(Object* obj);
4742
4743#ifdef DEBUG
4744 void DebugInfoPrint();
4745 void DebugInfoVerify();
4746#endif
4747
4748 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
4749 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
4750 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
4751 static const int kActiveBreakPointsCountIndex =
4752 kPatchedCodeIndex + kPointerSize;
4753 static const int kBreakPointsStateIndex =
4754 kActiveBreakPointsCountIndex + kPointerSize;
4755 static const int kSize = kBreakPointsStateIndex + kPointerSize;
4756
4757 private:
4758 static const int kNoBreakPointInfo = -1;
4759
4760 // Lookup the index in the break_points array for a code position.
4761 int GetBreakPointInfoIndex(int code_position);
4762
4763 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
4764};
4765
4766
4767// The BreakPointInfo class holds information for break points set in a
4768// function. The DebugInfo object holds a BreakPointInfo object for each code
4769// position with one or more break points.
4770class BreakPointInfo: public Struct {
4771 public:
4772 // The position in the code for the break point.
4773 DECL_ACCESSORS(code_position, Smi)
4774 // The position in the source for the break position.
4775 DECL_ACCESSORS(source_position, Smi)
4776 // The position in the source for the last statement before this break
4777 // position.
4778 DECL_ACCESSORS(statement_position, Smi)
4779 // List of related JavaScript break points.
4780 DECL_ACCESSORS(break_point_objects, Object)
4781
4782 // Removes a break point.
4783 static void ClearBreakPoint(Handle<BreakPointInfo> info,
4784 Handle<Object> break_point_object);
4785 // Set a break point.
4786 static void SetBreakPoint(Handle<BreakPointInfo> info,
4787 Handle<Object> break_point_object);
4788 // Check if break point info has this break point object.
4789 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
4790 Handle<Object> break_point_object);
4791 // Get the number of break points for this code position.
4792 int GetBreakPointCount();
4793
4794 static inline BreakPointInfo* cast(Object* obj);
4795
4796#ifdef DEBUG
4797 void BreakPointInfoPrint();
4798 void BreakPointInfoVerify();
4799#endif
4800
4801 static const int kCodePositionIndex = Struct::kHeaderSize;
4802 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
4803 static const int kStatementPositionIndex =
4804 kSourcePositionIndex + kPointerSize;
4805 static const int kBreakPointObjectsIndex =
4806 kStatementPositionIndex + kPointerSize;
4807 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
4808
4809 private:
4810 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
4811};
4812#endif // ENABLE_DEBUGGER_SUPPORT
4813
4814
4815#undef DECL_BOOLEAN_ACCESSORS
4816#undef DECL_ACCESSORS
4817
4818
4819// Abstract base class for visiting, and optionally modifying, the
4820// pointers contained in Objects. Used in GC and serialization/deserialization.
4821class ObjectVisitor BASE_EMBEDDED {
4822 public:
4823 virtual ~ObjectVisitor() {}
4824
4825 // Visits a contiguous arrays of pointers in the half-open range
4826 // [start, end). Any or all of the values may be modified on return.
4827 virtual void VisitPointers(Object** start, Object** end) = 0;
4828
4829 // To allow lazy clearing of inline caches the visitor has
4830 // a rich interface for iterating over Code objects..
4831
4832 // Visits a code target in the instruction stream.
4833 virtual void VisitCodeTarget(RelocInfo* rinfo);
4834
4835 // Visits a runtime entry in the instruction stream.
4836 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
4837
4838 // Visits a debug call target in the instruction stream.
4839 virtual void VisitDebugTarget(RelocInfo* rinfo);
4840
4841 // Handy shorthand for visiting a single pointer.
4842 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
4843
4844 // Visits a contiguous arrays of external references (references to the C++
4845 // heap) in the half-open range [start, end). Any or all of the values
4846 // may be modified on return.
4847 virtual void VisitExternalReferences(Address* start, Address* end) {}
4848
4849 inline void VisitExternalReference(Address* p) {
4850 VisitExternalReferences(p, p + 1);
4851 }
4852
4853#ifdef DEBUG
4854 // Intended for serialization/deserialization checking: insert, or
4855 // check for the presence of, a tag at this position in the stream.
4856 virtual void Synchronize(const char* tag) {}
4857#endif
4858};
4859
4860
4861// BooleanBit is a helper class for setting and getting a bit in an
4862// integer or Smi.
4863class BooleanBit : public AllStatic {
4864 public:
4865 static inline bool get(Smi* smi, int bit_position) {
4866 return get(smi->value(), bit_position);
4867 }
4868
4869 static inline bool get(int value, int bit_position) {
4870 return (value & (1 << bit_position)) != 0;
4871 }
4872
4873 static inline Smi* set(Smi* smi, int bit_position, bool v) {
4874 return Smi::FromInt(set(smi->value(), bit_position, v));
4875 }
4876
4877 static inline int set(int value, int bit_position, bool v) {
4878 if (v) {
4879 value |= (1 << bit_position);
4880 } else {
4881 value &= ~(1 << bit_position);
4882 }
4883 return value;
4884 }
4885};
4886
4887} } // namespace v8::internal
4888
4889#endif // V8_OBJECTS_H_