blob: b4af6d9c22ae9cf44c9cf1a011e651eb66fc9818 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 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_HEAP_H_
29#define V8_HEAP_H_
30
31#include <math.h>
32
Steve Block6ded16b2010-05-10 14:33:55 +010033#include "splay-tree-inl.h"
34#include "v8-counters.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000035
36namespace v8 {
37namespace internal {
38
Steve Block6ded16b2010-05-10 14:33:55 +010039// Forward declarations.
40class ZoneScopeInfo;
41
Steve Blocka7e24c12009-10-30 11:49:00 +000042// Defines all the roots in Heap.
43#define UNCONDITIONAL_STRONG_ROOT_LIST(V) \
Steve Blockd0582a62009-12-15 09:54:21 +000044 /* Put the byte array map early. We need it to be in place by the time */ \
45 /* the deserializer hits the next page, since it wants to put a byte */ \
46 /* array in the unused space at the end of the page. */ \
47 V(Map, byte_array_map, ByteArrayMap) \
48 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
49 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
50 /* Cluster the most popular ones in a few cache lines here at the top. */ \
Steve Blocka7e24c12009-10-30 11:49:00 +000051 V(Smi, stack_limit, StackLimit) \
52 V(Object, undefined_value, UndefinedValue) \
53 V(Object, the_hole_value, TheHoleValue) \
54 V(Object, null_value, NullValue) \
55 V(Object, true_value, TrueValue) \
56 V(Object, false_value, FalseValue) \
57 V(Map, heap_number_map, HeapNumberMap) \
58 V(Map, global_context_map, GlobalContextMap) \
59 V(Map, fixed_array_map, FixedArrayMap) \
60 V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
61 V(Map, meta_map, MetaMap) \
62 V(Object, termination_exception, TerminationException) \
63 V(Map, hash_table_map, HashTableMap) \
64 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
Steve Blockd0582a62009-12-15 09:54:21 +000065 V(Map, string_map, StringMap) \
66 V(Map, ascii_string_map, AsciiStringMap) \
67 V(Map, symbol_map, SymbolMap) \
68 V(Map, ascii_symbol_map, AsciiSymbolMap) \
69 V(Map, cons_symbol_map, ConsSymbolMap) \
70 V(Map, cons_ascii_symbol_map, ConsAsciiSymbolMap) \
71 V(Map, external_symbol_map, ExternalSymbolMap) \
72 V(Map, external_ascii_symbol_map, ExternalAsciiSymbolMap) \
73 V(Map, cons_string_map, ConsStringMap) \
74 V(Map, cons_ascii_string_map, ConsAsciiStringMap) \
75 V(Map, external_string_map, ExternalStringMap) \
76 V(Map, external_ascii_string_map, ExternalAsciiStringMap) \
77 V(Map, undetectable_string_map, UndetectableStringMap) \
78 V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000079 V(Map, pixel_array_map, PixelArrayMap) \
Steve Block3ce2e202009-11-05 08:53:23 +000080 V(Map, external_byte_array_map, ExternalByteArrayMap) \
81 V(Map, external_unsigned_byte_array_map, ExternalUnsignedByteArrayMap) \
82 V(Map, external_short_array_map, ExternalShortArrayMap) \
83 V(Map, external_unsigned_short_array_map, ExternalUnsignedShortArrayMap) \
84 V(Map, external_int_array_map, ExternalIntArrayMap) \
85 V(Map, external_unsigned_int_array_map, ExternalUnsignedIntArrayMap) \
86 V(Map, external_float_array_map, ExternalFloatArrayMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000087 V(Map, context_map, ContextMap) \
88 V(Map, catch_context_map, CatchContextMap) \
89 V(Map, code_map, CodeMap) \
90 V(Map, oddball_map, OddballMap) \
91 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000092 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
93 V(Map, proxy_map, ProxyMap) \
Steve Blocka7e24c12009-10-30 11:49:00 +000094 V(Object, nan_value, NanValue) \
95 V(Object, minus_zero_value, MinusZeroValue) \
Kristian Monsen25f61362010-05-21 11:50:48 +010096 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
97 V(Object, instanceof_cache_map, InstanceofCacheMap) \
98 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
Steve Blocka7e24c12009-10-30 11:49:00 +000099 V(String, empty_string, EmptyString) \
100 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
101 V(Map, neander_map, NeanderMap) \
102 V(JSObject, message_listeners, MessageListeners) \
103 V(Proxy, prototype_accessors, PrototypeAccessors) \
104 V(NumberDictionary, code_stubs, CodeStubs) \
105 V(NumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
106 V(Code, js_entry_code, JsEntryCode) \
107 V(Code, js_construct_entry_code, JsConstructEntryCode) \
108 V(Code, c_entry_code, CEntryCode) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000109 V(FixedArray, number_string_cache, NumberStringCache) \
110 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
111 V(FixedArray, natives_source_cache, NativesSourceCache) \
112 V(Object, last_script_id, LastScriptId) \
Andrei Popescu31002712010-02-23 13:46:05 +0000113 V(Script, empty_script, EmptyScript) \
Steve Blockd0582a62009-12-15 09:54:21 +0000114 V(Smi, real_stack_limit, RealStackLimit) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000115
Steve Block6ded16b2010-05-10 14:33:55 +0100116#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +0000117#define STRONG_ROOT_LIST(V) \
118 UNCONDITIONAL_STRONG_ROOT_LIST(V) \
119 V(Code, re_c_entry_code, RegExpCEntryCode)
120#else
121#define STRONG_ROOT_LIST(V) UNCONDITIONAL_STRONG_ROOT_LIST(V)
122#endif
123
124#define ROOT_LIST(V) \
125 STRONG_ROOT_LIST(V) \
126 V(SymbolTable, symbol_table, SymbolTable)
127
128#define SYMBOL_LIST(V) \
129 V(Array_symbol, "Array") \
130 V(Object_symbol, "Object") \
131 V(Proto_symbol, "__proto__") \
132 V(StringImpl_symbol, "StringImpl") \
133 V(arguments_symbol, "arguments") \
134 V(Arguments_symbol, "Arguments") \
135 V(arguments_shadow_symbol, ".arguments") \
136 V(call_symbol, "call") \
137 V(apply_symbol, "apply") \
138 V(caller_symbol, "caller") \
139 V(boolean_symbol, "boolean") \
140 V(Boolean_symbol, "Boolean") \
141 V(callee_symbol, "callee") \
142 V(constructor_symbol, "constructor") \
143 V(code_symbol, ".code") \
144 V(result_symbol, ".result") \
145 V(catch_var_symbol, ".catch-var") \
146 V(empty_symbol, "") \
147 V(eval_symbol, "eval") \
148 V(function_symbol, "function") \
149 V(length_symbol, "length") \
150 V(name_symbol, "name") \
151 V(number_symbol, "number") \
152 V(Number_symbol, "Number") \
153 V(RegExp_symbol, "RegExp") \
Steve Block6ded16b2010-05-10 14:33:55 +0100154 V(source_symbol, "source") \
155 V(global_symbol, "global") \
156 V(ignore_case_symbol, "ignoreCase") \
157 V(multiline_symbol, "multiline") \
158 V(input_symbol, "input") \
159 V(index_symbol, "index") \
160 V(last_index_symbol, "lastIndex") \
Steve Blocka7e24c12009-10-30 11:49:00 +0000161 V(object_symbol, "object") \
162 V(prototype_symbol, "prototype") \
163 V(string_symbol, "string") \
164 V(String_symbol, "String") \
165 V(Date_symbol, "Date") \
166 V(this_symbol, "this") \
167 V(to_string_symbol, "toString") \
168 V(char_at_symbol, "CharAt") \
169 V(undefined_symbol, "undefined") \
170 V(value_of_symbol, "valueOf") \
171 V(InitializeVarGlobal_symbol, "InitializeVarGlobal") \
172 V(InitializeConstGlobal_symbol, "InitializeConstGlobal") \
173 V(stack_overflow_symbol, "kStackOverflowBoilerplate") \
174 V(illegal_access_symbol, "illegal access") \
175 V(out_of_memory_symbol, "out-of-memory") \
176 V(illegal_execution_state_symbol, "illegal execution state") \
177 V(get_symbol, "get") \
178 V(set_symbol, "set") \
179 V(function_class_symbol, "Function") \
180 V(illegal_argument_symbol, "illegal argument") \
181 V(MakeReferenceError_symbol, "MakeReferenceError") \
182 V(MakeSyntaxError_symbol, "MakeSyntaxError") \
183 V(MakeTypeError_symbol, "MakeTypeError") \
184 V(invalid_lhs_in_assignment_symbol, "invalid_lhs_in_assignment") \
185 V(invalid_lhs_in_for_in_symbol, "invalid_lhs_in_for_in") \
186 V(invalid_lhs_in_postfix_op_symbol, "invalid_lhs_in_postfix_op") \
187 V(invalid_lhs_in_prefix_op_symbol, "invalid_lhs_in_prefix_op") \
188 V(illegal_return_symbol, "illegal_return") \
189 V(illegal_break_symbol, "illegal_break") \
190 V(illegal_continue_symbol, "illegal_continue") \
191 V(unknown_label_symbol, "unknown_label") \
192 V(redeclaration_symbol, "redeclaration") \
193 V(failure_symbol, "<failure>") \
194 V(space_symbol, " ") \
195 V(exec_symbol, "exec") \
196 V(zero_symbol, "0") \
197 V(global_eval_symbol, "GlobalEval") \
Steve Blockd0582a62009-12-15 09:54:21 +0000198 V(identity_hash_symbol, "v8::IdentityHash") \
199 V(closure_symbol, "(closure)")
Steve Blocka7e24c12009-10-30 11:49:00 +0000200
201
202// Forward declaration of the GCTracer class.
203class GCTracer;
Steve Blockd0582a62009-12-15 09:54:21 +0000204class HeapStats;
Steve Blocka7e24c12009-10-30 11:49:00 +0000205
206
Steve Block6ded16b2010-05-10 14:33:55 +0100207typedef String* (*ExternalStringTableUpdaterCallback)(Object** pointer);
208
209
Steve Blocka7e24c12009-10-30 11:49:00 +0000210// The all static Heap captures the interface to the global object heap.
211// All JavaScript contexts by this process share the same object heap.
212
213class Heap : public AllStatic {
214 public:
215 // Configure heap size before setup. Return false if the heap has been
216 // setup already.
Steve Block3ce2e202009-11-05 08:53:23 +0000217 static bool ConfigureHeap(int max_semispace_size, int max_old_gen_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000218 static bool ConfigureHeapDefault();
219
220 // Initializes the global object heap. If create_heap_objects is true,
221 // also creates the basic non-mutable objects.
222 // Returns whether it succeeded.
223 static bool Setup(bool create_heap_objects);
224
225 // Destroys all memory allocated by the heap.
226 static void TearDown();
227
Steve Blockd0582a62009-12-15 09:54:21 +0000228 // Set the stack limit in the roots_ array. Some architectures generate
229 // code that looks here, because it is faster than loading from the static
230 // jslimit_/real_jslimit_ variable in the StackGuard.
231 static void SetStackLimits();
Steve Blocka7e24c12009-10-30 11:49:00 +0000232
233 // Returns whether Setup has been called.
234 static bool HasBeenSetup();
235
Steve Block3ce2e202009-11-05 08:53:23 +0000236 // Returns the maximum amount of memory reserved for the heap. For
237 // the young generation, we reserve 4 times the amount needed for a
238 // semi space. The young generation consists of two semi spaces and
239 // we reserve twice the amount needed for those in order to ensure
240 // that new space can be aligned to its size.
241 static int MaxReserved() {
242 return 4 * reserved_semispace_size_ + max_old_generation_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000243 }
Steve Block3ce2e202009-11-05 08:53:23 +0000244 static int MaxSemiSpaceSize() { return max_semispace_size_; }
245 static int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000246 static int InitialSemiSpaceSize() { return initial_semispace_size_; }
Steve Block3ce2e202009-11-05 08:53:23 +0000247 static int MaxOldGenerationSize() { return max_old_generation_size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000248
249 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
250 // more spaces are needed until it reaches the limit.
251 static int Capacity();
252
Steve Block3ce2e202009-11-05 08:53:23 +0000253 // Returns the amount of memory currently committed for the heap.
254 static int CommittedMemory();
255
Steve Blocka7e24c12009-10-30 11:49:00 +0000256 // Returns the available bytes in space w/o growing.
257 // Heap doesn't guarantee that it can allocate an object that requires
258 // all available bytes. Check MaxHeapObjectSize() instead.
259 static int Available();
260
261 // Returns the maximum object size in paged space.
262 static inline int MaxObjectSizeInPagedSpace();
263
264 // Returns of size of all objects residing in the heap.
265 static int SizeOfObjects();
266
267 // Return the starting address and a mask for the new space. And-masking an
268 // address with the mask will result in the start address of the new space
269 // for all addresses in either semispace.
270 static Address NewSpaceStart() { return new_space_.start(); }
271 static uintptr_t NewSpaceMask() { return new_space_.mask(); }
272 static Address NewSpaceTop() { return new_space_.top(); }
273
274 static NewSpace* new_space() { return &new_space_; }
275 static OldSpace* old_pointer_space() { return old_pointer_space_; }
276 static OldSpace* old_data_space() { return old_data_space_; }
277 static OldSpace* code_space() { return code_space_; }
278 static MapSpace* map_space() { return map_space_; }
279 static CellSpace* cell_space() { return cell_space_; }
280 static LargeObjectSpace* lo_space() { return lo_space_; }
281
282 static bool always_allocate() { return always_allocate_scope_depth_ != 0; }
283 static Address always_allocate_scope_depth_address() {
284 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
285 }
Steve Blockd0582a62009-12-15 09:54:21 +0000286 static bool linear_allocation() {
Leon Clarkee46be812010-01-19 14:06:41 +0000287 return linear_allocation_scope_depth_ != 0;
Steve Blockd0582a62009-12-15 09:54:21 +0000288 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000289
290 static Address* NewSpaceAllocationTopAddress() {
291 return new_space_.allocation_top_address();
292 }
293 static Address* NewSpaceAllocationLimitAddress() {
294 return new_space_.allocation_limit_address();
295 }
296
297 // Uncommit unused semi space.
298 static bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
299
300#ifdef ENABLE_HEAP_PROTECTION
301 // Protect/unprotect the heap by marking all spaces read-only/writable.
302 static void Protect();
303 static void Unprotect();
304#endif
305
306 // Allocates and initializes a new JavaScript object based on a
307 // constructor.
308 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
309 // failed.
310 // Please note this does not perform a garbage collection.
311 static Object* AllocateJSObject(JSFunction* constructor,
312 PretenureFlag pretenure = NOT_TENURED);
313
314 // Allocates and initializes a new global object based on a constructor.
315 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
316 // failed.
317 // Please note this does not perform a garbage collection.
318 static Object* AllocateGlobalObject(JSFunction* constructor);
319
320 // Returns a deep copy of the JavaScript object.
321 // Properties and elements are copied too.
322 // Returns failure if allocation failed.
323 static Object* CopyJSObject(JSObject* source);
324
325 // Allocates the function prototype.
326 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
327 // failed.
328 // Please note this does not perform a garbage collection.
329 static Object* AllocateFunctionPrototype(JSFunction* function);
330
331 // Reinitialize an JSGlobalProxy based on a constructor. The object
332 // must have the same size as objects allocated using the
333 // constructor. The object is reinitialized and behaves as an
334 // object that has been freshly allocated using the constructor.
335 static Object* ReinitializeJSGlobalProxy(JSFunction* constructor,
336 JSGlobalProxy* global);
337
338 // Allocates and initializes a new JavaScript object based on a map.
339 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
340 // failed.
341 // Please note this does not perform a garbage collection.
342 static Object* AllocateJSObjectFromMap(Map* map,
343 PretenureFlag pretenure = NOT_TENURED);
344
345 // Allocates a heap object based on the map.
346 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
347 // failed.
348 // Please note this function does not perform a garbage collection.
349 static Object* Allocate(Map* map, AllocationSpace space);
350
351 // Allocates a JS Map in the heap.
352 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
353 // failed.
354 // Please note this function does not perform a garbage collection.
355 static Object* AllocateMap(InstanceType instance_type, int instance_size);
356
357 // Allocates a partial map for bootstrapping.
358 static Object* AllocatePartialMap(InstanceType instance_type,
359 int instance_size);
360
361 // Allocate a map for the specified function
362 static Object* AllocateInitialMap(JSFunction* fun);
363
Steve Block6ded16b2010-05-10 14:33:55 +0100364 // Allocates an empty code cache.
365 static Object* AllocateCodeCache();
366
Kristian Monsen25f61362010-05-21 11:50:48 +0100367 // Clear the Instanceof cache (used when a prototype changes).
368 static void ClearInstanceofCache() {
369 set_instanceof_cache_function(the_hole_value());
370 }
371
Steve Blocka7e24c12009-10-30 11:49:00 +0000372 // Allocates and fully initializes a String. There are two String
373 // encodings: ASCII and two byte. One should choose between the three string
374 // allocation functions based on the encoding of the string buffer used to
375 // initialized the string.
376 // - ...FromAscii initializes the string from a buffer that is ASCII
377 // encoded (it does not check that the buffer is ASCII encoded) and the
378 // result will be ASCII encoded.
379 // - ...FromUTF8 initializes the string from a buffer that is UTF-8
380 // encoded. If the characters are all single-byte characters, the
381 // result will be ASCII encoded, otherwise it will converted to two
382 // byte.
383 // - ...FromTwoByte initializes the string from a buffer that is two-byte
384 // encoded. If the characters are all single-byte characters, the
385 // result will be converted to ASCII, otherwise it will be left as
386 // two-byte.
387 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
388 // failed.
389 // Please note this does not perform a garbage collection.
390 static Object* AllocateStringFromAscii(
391 Vector<const char> str,
392 PretenureFlag pretenure = NOT_TENURED);
393 static Object* AllocateStringFromUtf8(
394 Vector<const char> str,
395 PretenureFlag pretenure = NOT_TENURED);
396 static Object* AllocateStringFromTwoByte(
397 Vector<const uc16> str,
398 PretenureFlag pretenure = NOT_TENURED);
399
400 // Allocates a symbol in old space based on the character stream.
401 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
402 // failed.
403 // Please note this function does not perform a garbage collection.
404 static inline Object* AllocateSymbol(Vector<const char> str,
405 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +0000406 uint32_t hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000407
408 static Object* AllocateInternalSymbol(unibrow::CharacterStream* buffer,
409 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +0000410 uint32_t hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000411
412 static Object* AllocateExternalSymbol(Vector<const char> str,
413 int chars);
414
415
416 // Allocates and partially initializes a String. There are two String
417 // encodings: ASCII and two byte. These functions allocate a string of the
418 // given length and set its map and length fields. The characters of the
419 // string are uninitialized.
420 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
421 // failed.
422 // Please note this does not perform a garbage collection.
423 static Object* AllocateRawAsciiString(
424 int length,
425 PretenureFlag pretenure = NOT_TENURED);
426 static Object* AllocateRawTwoByteString(
427 int length,
428 PretenureFlag pretenure = NOT_TENURED);
429
430 // Computes a single character string where the character has code.
431 // A cache is used for ascii codes.
432 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
433 // failed. Please note this does not perform a garbage collection.
434 static Object* LookupSingleCharacterStringFromCode(uint16_t code);
435
436 // Allocate a byte array of the specified length
437 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
438 // failed.
439 // Please note this does not perform a garbage collection.
440 static Object* AllocateByteArray(int length, PretenureFlag pretenure);
441
442 // Allocate a non-tenured byte array of the specified length
443 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
444 // failed.
445 // Please note this does not perform a garbage collection.
446 static Object* AllocateByteArray(int length);
447
448 // Allocate a pixel array of the specified length
449 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
450 // failed.
451 // Please note this does not perform a garbage collection.
452 static Object* AllocatePixelArray(int length,
453 uint8_t* external_pointer,
454 PretenureFlag pretenure);
455
Steve Block3ce2e202009-11-05 08:53:23 +0000456 // Allocates an external array of the specified length and type.
457 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
458 // failed.
459 // Please note this does not perform a garbage collection.
460 static Object* AllocateExternalArray(int length,
461 ExternalArrayType array_type,
462 void* external_pointer,
463 PretenureFlag pretenure);
464
Steve Blocka7e24c12009-10-30 11:49:00 +0000465 // Allocate a tenured JS global property cell.
466 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
467 // failed.
468 // Please note this does not perform a garbage collection.
469 static Object* AllocateJSGlobalPropertyCell(Object* value);
470
471 // Allocates a fixed array initialized with undefined values
472 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
473 // failed.
474 // Please note this does not perform a garbage collection.
475 static Object* AllocateFixedArray(int length, PretenureFlag pretenure);
Steve Block6ded16b2010-05-10 14:33:55 +0100476 // Allocates a fixed array initialized with undefined values
Steve Blocka7e24c12009-10-30 11:49:00 +0000477 static Object* AllocateFixedArray(int length);
478
Steve Block6ded16b2010-05-10 14:33:55 +0100479 // Allocates an uninitialized fixed array. It must be filled by the caller.
480 //
481 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
482 // failed.
483 // Please note this does not perform a garbage collection.
484 static Object* AllocateUninitializedFixedArray(int length);
485
Steve Blocka7e24c12009-10-30 11:49:00 +0000486 // Make a copy of src and return it. Returns
487 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
488 static Object* CopyFixedArray(FixedArray* src);
489
490 // Allocates a fixed array initialized with the hole values.
491 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
492 // failed.
493 // Please note this does not perform a garbage collection.
Steve Block6ded16b2010-05-10 14:33:55 +0100494 static Object* AllocateFixedArrayWithHoles(
495 int length,
496 PretenureFlag pretenure = NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000497
498 // AllocateHashTable is identical to AllocateFixedArray except
499 // that the resulting object has hash_table_map as map.
Steve Block6ded16b2010-05-10 14:33:55 +0100500 static Object* AllocateHashTable(int length,
501 PretenureFlag pretenure = NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000502
503 // Allocate a global (but otherwise uninitialized) context.
504 static Object* AllocateGlobalContext();
505
506 // Allocate a function context.
507 static Object* AllocateFunctionContext(int length, JSFunction* closure);
508
509 // Allocate a 'with' context.
510 static Object* AllocateWithContext(Context* previous,
511 JSObject* extension,
512 bool is_catch_context);
513
514 // Allocates a new utility object in the old generation.
515 static Object* AllocateStruct(InstanceType type);
516
517 // Allocates a function initialized with a shared part.
518 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
519 // failed.
520 // Please note this does not perform a garbage collection.
521 static Object* AllocateFunction(Map* function_map,
522 SharedFunctionInfo* shared,
Leon Clarkee46be812010-01-19 14:06:41 +0000523 Object* prototype,
524 PretenureFlag pretenure = TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000525
526 // Indicies for direct access into argument objects.
Leon Clarkee46be812010-01-19 14:06:41 +0000527 static const int kArgumentsObjectSize =
528 JSObject::kHeaderSize + 2 * kPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000529 static const int arguments_callee_index = 0;
530 static const int arguments_length_index = 1;
531
532 // Allocates an arguments object - optionally with an elements array.
533 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
534 // failed.
535 // Please note this does not perform a garbage collection.
536 static Object* AllocateArgumentsObject(Object* callee, int length);
537
Steve Blocka7e24c12009-10-30 11:49:00 +0000538 // Same as NewNumberFromDouble, but may return a preallocated/immutable
539 // number object (e.g., minus_zero_value_, nan_value_)
540 static Object* NumberFromDouble(double value,
541 PretenureFlag pretenure = NOT_TENURED);
542
543 // Allocated a HeapNumber from value.
544 static Object* AllocateHeapNumber(double value, PretenureFlag pretenure);
545 static Object* AllocateHeapNumber(double value); // pretenure = NOT_TENURED
546
547 // Converts an int into either a Smi or a HeapNumber object.
548 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
549 // failed.
550 // Please note this does not perform a garbage collection.
551 static inline Object* NumberFromInt32(int32_t value);
552
553 // Converts an int into either a Smi or a HeapNumber object.
554 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
555 // failed.
556 // Please note this does not perform a garbage collection.
557 static inline Object* NumberFromUint32(uint32_t value);
558
559 // Allocates a new proxy object.
560 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
561 // failed.
562 // Please note this does not perform a garbage collection.
563 static Object* AllocateProxy(Address proxy,
564 PretenureFlag pretenure = NOT_TENURED);
565
566 // Allocates a new SharedFunctionInfo object.
567 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
568 // failed.
569 // Please note this does not perform a garbage collection.
570 static Object* AllocateSharedFunctionInfo(Object* name);
571
572 // Allocates a new cons string object.
573 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
574 // failed.
575 // Please note this does not perform a garbage collection.
576 static Object* AllocateConsString(String* first, String* second);
577
Steve Blocka7e24c12009-10-30 11:49:00 +0000578 // Allocates a new sub string object which is a substring of an underlying
579 // string buffer stretching from the index start (inclusive) to the index
580 // end (exclusive).
581 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
582 // failed.
583 // Please note this does not perform a garbage collection.
584 static Object* AllocateSubString(String* buffer,
585 int start,
Steve Block6ded16b2010-05-10 14:33:55 +0100586 int end,
587 PretenureFlag pretenure = NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +0000588
589 // Allocate a new external string object, which is backed by a string
590 // resource that resides outside the V8 heap.
591 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
592 // failed.
593 // Please note this does not perform a garbage collection.
594 static Object* AllocateExternalStringFromAscii(
595 ExternalAsciiString::Resource* resource);
596 static Object* AllocateExternalStringFromTwoByte(
597 ExternalTwoByteString::Resource* resource);
598
Leon Clarkee46be812010-01-19 14:06:41 +0000599 // Finalizes an external string by deleting the associated external
600 // data and clearing the resource pointer.
601 static inline void FinalizeExternalString(String* string);
602
Steve Blocka7e24c12009-10-30 11:49:00 +0000603 // Allocates an uninitialized object. The memory is non-executable if the
604 // hardware and OS allow.
605 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
606 // failed.
607 // Please note this function does not perform a garbage collection.
608 static inline Object* AllocateRaw(int size_in_bytes,
609 AllocationSpace space,
610 AllocationSpace retry_space);
611
612 // Initialize a filler object to keep the ability to iterate over the heap
613 // when shortening objects.
614 static void CreateFillerObjectAt(Address addr, int size);
615
616 // Makes a new native code object
617 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
618 // failed. On success, the pointer to the Code object is stored in the
619 // self_reference. This allows generated code to reference its own Code
620 // object by containing this pointer.
621 // Please note this function does not perform a garbage collection.
622 static Object* CreateCode(const CodeDesc& desc,
623 ZoneScopeInfo* sinfo,
624 Code::Flags flags,
625 Handle<Object> self_reference);
626
627 static Object* CopyCode(Code* code);
Steve Block6ded16b2010-05-10 14:33:55 +0100628
629 // Copy the code and scope info part of the code object, but insert
630 // the provided data as the relocation information.
631 static Object* CopyCode(Code* code, Vector<byte> reloc_info);
632
Steve Blocka7e24c12009-10-30 11:49:00 +0000633 // Finds the symbol for string in the symbol table.
634 // If not found, a new symbol is added to the table and returned.
635 // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
636 // failed.
637 // Please note this function does not perform a garbage collection.
638 static Object* LookupSymbol(Vector<const char> str);
639 static Object* LookupAsciiSymbol(const char* str) {
640 return LookupSymbol(CStrVector(str));
641 }
642 static Object* LookupSymbol(String* str);
643 static bool LookupSymbolIfExists(String* str, String** symbol);
Steve Blockd0582a62009-12-15 09:54:21 +0000644 static bool LookupTwoCharsSymbolIfExists(String* str, String** symbol);
Steve Blocka7e24c12009-10-30 11:49:00 +0000645
646 // Compute the matching symbol map for a string if possible.
647 // NULL is returned if string is in new space or not flattened.
648 static Map* SymbolMapForString(String* str);
649
Steve Block6ded16b2010-05-10 14:33:55 +0100650 // Tries to flatten a string before compare operation.
651 //
652 // Returns a failure in case it was decided that flattening was
653 // necessary and failed. Note, if flattening is not necessary the
654 // string might stay non-flat even when not a failure is returned.
655 //
656 // Please note this function does not perform a garbage collection.
657 static inline Object* PrepareForCompare(String* str);
658
Steve Blocka7e24c12009-10-30 11:49:00 +0000659 // Converts the given boolean condition to JavaScript boolean value.
660 static Object* ToBoolean(bool condition) {
661 return condition ? true_value() : false_value();
662 }
663
664 // Code that should be run before and after each GC. Includes some
665 // reporting/verification activities when compiled with DEBUG set.
666 static void GarbageCollectionPrologue();
667 static void GarbageCollectionEpilogue();
668
Steve Blocka7e24c12009-10-30 11:49:00 +0000669 // Performs garbage collection operation.
670 // Returns whether required_space bytes are available after the collection.
671 static bool CollectGarbage(int required_space, AllocationSpace space);
672
673 // Performs a full garbage collection. Force compaction if the
674 // parameter is true.
675 static void CollectAllGarbage(bool force_compaction);
676
Steve Blocka7e24c12009-10-30 11:49:00 +0000677 // Notify the heap that a context has been disposed.
Steve Block6ded16b2010-05-10 14:33:55 +0100678 static int NotifyContextDisposed() { return ++contexts_disposed_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000679
680 // Utility to invoke the scavenger. This is needed in test code to
681 // ensure correct callback for weak global handles.
682 static void PerformScavenge();
683
684#ifdef DEBUG
685 // Utility used with flag gc-greedy.
686 static bool GarbageCollectionGreedyCheck();
687#endif
688
Steve Block6ded16b2010-05-10 14:33:55 +0100689 static void AddGCPrologueCallback(
690 GCEpilogueCallback callback, GCType gc_type_filter);
691 static void RemoveGCPrologueCallback(GCEpilogueCallback callback);
692
693 static void AddGCEpilogueCallback(
694 GCEpilogueCallback callback, GCType gc_type_filter);
695 static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
696
Steve Blocka7e24c12009-10-30 11:49:00 +0000697 static void SetGlobalGCPrologueCallback(GCCallback callback) {
Steve Block6ded16b2010-05-10 14:33:55 +0100698 ASSERT((callback == NULL) ^ (global_gc_prologue_callback_ == NULL));
Steve Blocka7e24c12009-10-30 11:49:00 +0000699 global_gc_prologue_callback_ = callback;
700 }
701 static void SetGlobalGCEpilogueCallback(GCCallback callback) {
Steve Block6ded16b2010-05-10 14:33:55 +0100702 ASSERT((callback == NULL) ^ (global_gc_epilogue_callback_ == NULL));
Steve Blocka7e24c12009-10-30 11:49:00 +0000703 global_gc_epilogue_callback_ = callback;
704 }
705
706 // Heap root getters. We have versions with and without type::cast() here.
707 // You can't use type::cast during GC because the assert fails.
708#define ROOT_ACCESSOR(type, name, camel_name) \
709 static inline type* name() { \
710 return type::cast(roots_[k##camel_name##RootIndex]); \
711 } \
712 static inline type* raw_unchecked_##name() { \
713 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
714 }
715 ROOT_LIST(ROOT_ACCESSOR)
716#undef ROOT_ACCESSOR
717
718// Utility type maps
719#define STRUCT_MAP_ACCESSOR(NAME, Name, name) \
720 static inline Map* name##_map() { \
721 return Map::cast(roots_[k##Name##MapRootIndex]); \
722 }
723 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
724#undef STRUCT_MAP_ACCESSOR
725
726#define SYMBOL_ACCESSOR(name, str) static inline String* name() { \
727 return String::cast(roots_[k##name##RootIndex]); \
728 }
729 SYMBOL_LIST(SYMBOL_ACCESSOR)
730#undef SYMBOL_ACCESSOR
731
732 // The hidden_symbol is special because it is the empty string, but does
733 // not match the empty string.
734 static String* hidden_symbol() { return hidden_symbol_; }
735
736 // Iterates over all roots in the heap.
Steve Blockd0582a62009-12-15 09:54:21 +0000737 static void IterateRoots(ObjectVisitor* v, VisitMode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000738 // Iterates over all strong roots in the heap.
Steve Blockd0582a62009-12-15 09:54:21 +0000739 static void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
Leon Clarked91b9f72010-01-27 17:25:45 +0000740 // Iterates over all the other roots in the heap.
741 static void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000742
743 // Iterates remembered set of an old space.
744 static void IterateRSet(PagedSpace* space, ObjectSlotCallback callback);
745
746 // Iterates a range of remembered set addresses starting with rset_start
747 // corresponding to the range of allocated pointers
748 // [object_start, object_end).
749 // Returns the number of bits that were set.
750 static int IterateRSetRange(Address object_start,
751 Address object_end,
752 Address rset_start,
753 ObjectSlotCallback copy_object_func);
754
755 // Returns whether the object resides in new space.
756 static inline bool InNewSpace(Object* object);
757 static inline bool InFromSpace(Object* object);
758 static inline bool InToSpace(Object* object);
759
760 // Checks whether an address/object in the heap (including auxiliary
761 // area and unused area).
762 static bool Contains(Address addr);
763 static bool Contains(HeapObject* value);
764
765 // Checks whether an address/object in a space.
Steve Blockd0582a62009-12-15 09:54:21 +0000766 // Currently used by tests, serialization and heap verification only.
Steve Blocka7e24c12009-10-30 11:49:00 +0000767 static bool InSpace(Address addr, AllocationSpace space);
768 static bool InSpace(HeapObject* value, AllocationSpace space);
769
770 // Finds out which space an object should get promoted to based on its type.
771 static inline OldSpace* TargetSpace(HeapObject* object);
772 static inline AllocationSpace TargetSpaceId(InstanceType type);
773
774 // Sets the stub_cache_ (only used when expanding the dictionary).
775 static void public_set_code_stubs(NumberDictionary* value) {
776 roots_[kCodeStubsRootIndex] = value;
777 }
778
779 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
780 static void public_set_non_monomorphic_cache(NumberDictionary* value) {
781 roots_[kNonMonomorphicCacheRootIndex] = value;
782 }
783
Andrei Popescu31002712010-02-23 13:46:05 +0000784 static void public_set_empty_script(Script* script) {
785 roots_[kEmptyScriptRootIndex] = script;
786 }
787
Steve Blocka7e24c12009-10-30 11:49:00 +0000788 // Update the next script id.
789 static inline void SetLastScriptId(Object* last_script_id);
790
791 // Generated code can embed this address to get access to the roots.
792 static Object** roots_address() { return roots_; }
793
794#ifdef DEBUG
795 static void Print();
796 static void PrintHandles();
797
798 // Verify the heap is in its normal state before or after a GC.
799 static void Verify();
800
801 // Report heap statistics.
802 static void ReportHeapStatistics(const char* title);
803 static void ReportCodeStatistics(const char* title);
804
805 // Fill in bogus values in from space
806 static void ZapFromSpace();
807#endif
808
809#if defined(ENABLE_LOGGING_AND_PROFILING)
810 // Print short heap statistics.
811 static void PrintShortHeapStatistics();
812#endif
813
814 // Makes a new symbol object
815 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
816 // failed.
817 // Please note this function does not perform a garbage collection.
818 static Object* CreateSymbol(const char* str, int length, int hash);
819 static Object* CreateSymbol(String* str);
820
821 // Write barrier support for address[offset] = o.
822 static inline void RecordWrite(Address address, int offset);
823
Steve Block6ded16b2010-05-10 14:33:55 +0100824 // Write barrier support for address[start : start + len[ = o.
825 static inline void RecordWrites(Address address, int start, int len);
826
Steve Blocka7e24c12009-10-30 11:49:00 +0000827 // Given an address occupied by a live code object, return that object.
828 static Object* FindCodeObject(Address a);
829
830 // Invoke Shrink on shrinkable spaces.
831 static void Shrink();
832
833 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
834 static inline HeapState gc_state() { return gc_state_; }
835
836#ifdef DEBUG
837 static bool IsAllocationAllowed() { return allocation_allowed_; }
838 static inline bool allow_allocation(bool enable);
839
840 static bool disallow_allocation_failure() {
841 return disallow_allocation_failure_;
842 }
843
Leon Clarkee46be812010-01-19 14:06:41 +0000844 static void TracePathToObject(Object* target);
Steve Blocka7e24c12009-10-30 11:49:00 +0000845 static void TracePathToGlobal();
846#endif
847
848 // Callback function passed to Heap::Iterate etc. Copies an object if
849 // necessary, the object might be promoted to an old space. The caller must
850 // ensure the precondition that the object is (a) a heap object and (b) in
851 // the heap's from space.
852 static void ScavengePointer(HeapObject** p);
853 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
854
855 // Clear a range of remembered set addresses corresponding to the object
856 // area address 'start' with size 'size_in_bytes', eg, when adding blocks
857 // to the free list.
858 static void ClearRSetRange(Address start, int size_in_bytes);
859
860 // Rebuild remembered set in old and map spaces.
861 static void RebuildRSets();
862
Leon Clarkee46be812010-01-19 14:06:41 +0000863 // Update an old object's remembered set
864 static int UpdateRSet(HeapObject* obj);
865
Steve Blocka7e24c12009-10-30 11:49:00 +0000866 // Commits from space if it is uncommitted.
867 static void EnsureFromSpaceIsCommitted();
868
Leon Clarkee46be812010-01-19 14:06:41 +0000869 // Support for partial snapshots. After calling this we can allocate a
870 // certain number of bytes using only linear allocation (with a
871 // LinearAllocationScope and an AlwaysAllocateScope) without using freelists
872 // or causing a GC. It returns true of space was reserved or false if a GC is
873 // needed. For paged spaces the space requested must include the space wasted
874 // at the end of each page when allocating linearly.
875 static void ReserveSpace(
876 int new_space_size,
877 int pointer_space_size,
878 int data_space_size,
879 int code_space_size,
880 int map_space_size,
881 int cell_space_size,
882 int large_object_size);
883
Steve Blocka7e24c12009-10-30 11:49:00 +0000884 //
885 // Support for the API.
886 //
887
888 static bool CreateApiObjects();
889
890 // Attempt to find the number in a small cache. If we finds it, return
891 // the string representation of the number. Otherwise return undefined.
892 static Object* GetNumberStringCache(Object* number);
893
894 // Update the cache with a new number-string pair.
895 static void SetNumberStringCache(Object* number, String* str);
896
Steve Blocka7e24c12009-10-30 11:49:00 +0000897 // Adjusts the amount of registered external memory.
898 // Returns the adjusted value.
899 static inline int AdjustAmountOfExternalAllocatedMemory(int change_in_bytes);
900
Steve Block6ded16b2010-05-10 14:33:55 +0100901 // Allocate uninitialized fixed array.
Steve Blocka7e24c12009-10-30 11:49:00 +0000902 static Object* AllocateRawFixedArray(int length);
Steve Block6ded16b2010-05-10 14:33:55 +0100903 static Object* AllocateRawFixedArray(int length,
904 PretenureFlag pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +0000905
906 // True if we have reached the allocation limit in the old generation that
907 // should force the next GC (caused normally) to be a full one.
908 static bool OldGenerationPromotionLimitReached() {
909 return (PromotedSpaceSize() + PromotedExternalMemorySize())
910 > old_gen_promotion_limit_;
911 }
912
Leon Clarkee46be812010-01-19 14:06:41 +0000913 static intptr_t OldGenerationSpaceAvailable() {
914 return old_gen_allocation_limit_ -
915 (PromotedSpaceSize() + PromotedExternalMemorySize());
916 }
917
Steve Blocka7e24c12009-10-30 11:49:00 +0000918 // True if we have reached the allocation limit in the old generation that
919 // should artificially cause a GC right now.
920 static bool OldGenerationAllocationLimitReached() {
Leon Clarkee46be812010-01-19 14:06:41 +0000921 return OldGenerationSpaceAvailable() < 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000922 }
923
924 // Can be called when the embedding application is idle.
925 static bool IdleNotification();
926
927 // Declare all the root indices.
928 enum RootListIndex {
929#define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
930 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
931#undef ROOT_INDEX_DECLARATION
932
933// Utility type maps
934#define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
935 STRUCT_LIST(DECLARE_STRUCT_MAP)
936#undef DECLARE_STRUCT_MAP
937
938#define SYMBOL_INDEX_DECLARATION(name, str) k##name##RootIndex,
939 SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
940#undef SYMBOL_DECLARATION
941
942 kSymbolTableRootIndex,
943 kStrongRootListLength = kSymbolTableRootIndex,
944 kRootListLength
945 };
946
Steve Block6ded16b2010-05-10 14:33:55 +0100947 static Object* NumberToString(Object* number,
948 bool check_number_string_cache = true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000949
Steve Block3ce2e202009-11-05 08:53:23 +0000950 static Map* MapForExternalArrayType(ExternalArrayType array_type);
951 static RootListIndex RootIndexForExternalArrayType(
952 ExternalArrayType array_type);
953
Steve Blockd0582a62009-12-15 09:54:21 +0000954 static void RecordStats(HeapStats* stats);
955
Steve Block6ded16b2010-05-10 14:33:55 +0100956 // Copy block of memory from src to dst. Size of block should be aligned
957 // by pointer size.
958 static inline void CopyBlock(Object** dst, Object** src, int byte_size);
959
960 // Optimized version of memmove for blocks with pointer size aligned sizes and
961 // pointer size aligned addresses.
962 static inline void MoveBlock(Object** dst, Object** src, int byte_size);
963
964 // Check new space expansion criteria and expand semispaces if it was hit.
965 static void CheckNewSpaceExpansionCriteria();
966
967 static inline void IncrementYoungSurvivorsCounter(int survived) {
968 survived_since_last_expansion_ += survived;
969 }
970
971 static void UpdateNewSpaceReferencesInExternalStringTable(
972 ExternalStringTableUpdaterCallback updater_func);
973
974 // Helper function that governs the promotion policy from new space to
975 // old. If the object's old address lies below the new space's age
976 // mark or if we've already filled the bottom 1/16th of the to space,
977 // we try to promote this object.
978 static inline bool ShouldBePromoted(Address old_address, int object_size);
979
980 static int MaxObjectSizeInNewSpace() { return kMaxObjectSizeInNewSpace; }
981
Kristian Monsen25f61362010-05-21 11:50:48 +0100982 static void ClearJSFunctionResultCaches();
983
Steve Blocka7e24c12009-10-30 11:49:00 +0000984 private:
Steve Block3ce2e202009-11-05 08:53:23 +0000985 static int reserved_semispace_size_;
986 static int max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000987 static int initial_semispace_size_;
Steve Block3ce2e202009-11-05 08:53:23 +0000988 static int max_old_generation_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000989 static size_t code_range_size_;
990
991 // For keeping track of how much data has survived
992 // scavenge since last new space expansion.
993 static int survived_since_last_expansion_;
994
995 static int always_allocate_scope_depth_;
Steve Blockd0582a62009-12-15 09:54:21 +0000996 static int linear_allocation_scope_depth_;
Steve Block6ded16b2010-05-10 14:33:55 +0100997
998 // For keeping track of context disposals.
999 static int contexts_disposed_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001000
Steve Blocka7e24c12009-10-30 11:49:00 +00001001#if defined(V8_TARGET_ARCH_X64)
1002 static const int kMaxObjectSizeInNewSpace = 512*KB;
1003#else
1004 static const int kMaxObjectSizeInNewSpace = 256*KB;
1005#endif
1006
1007 static NewSpace new_space_;
1008 static OldSpace* old_pointer_space_;
1009 static OldSpace* old_data_space_;
1010 static OldSpace* code_space_;
1011 static MapSpace* map_space_;
1012 static CellSpace* cell_space_;
1013 static LargeObjectSpace* lo_space_;
1014 static HeapState gc_state_;
1015
1016 // Returns the size of object residing in non new spaces.
1017 static int PromotedSpaceSize();
1018
1019 // Returns the amount of external memory registered since last global gc.
1020 static int PromotedExternalMemorySize();
1021
1022 static int mc_count_; // how many mark-compact collections happened
1023 static int gc_count_; // how many gc happened
1024
Steve Block6ded16b2010-05-10 14:33:55 +01001025 // Total length of the strings we failed to flatten since the last GC.
1026 static int unflattened_strings_length_;
1027
Steve Blocka7e24c12009-10-30 11:49:00 +00001028#define ROOT_ACCESSOR(type, name, camel_name) \
1029 static inline void set_##name(type* value) { \
1030 roots_[k##camel_name##RootIndex] = value; \
1031 }
1032 ROOT_LIST(ROOT_ACCESSOR)
1033#undef ROOT_ACCESSOR
1034
1035#ifdef DEBUG
1036 static bool allocation_allowed_;
1037
1038 // If the --gc-interval flag is set to a positive value, this
1039 // variable holds the value indicating the number of allocations
1040 // remain until the next failure and garbage collection.
1041 static int allocation_timeout_;
1042
1043 // Do we expect to be able to handle allocation failure at this
1044 // time?
1045 static bool disallow_allocation_failure_;
1046#endif // DEBUG
1047
1048 // Limit that triggers a global GC on the next (normally caused) GC. This
1049 // is checked when we have already decided to do a GC to help determine
1050 // which collector to invoke.
1051 static int old_gen_promotion_limit_;
1052
1053 // Limit that triggers a global GC as soon as is reasonable. This is
1054 // checked before expanding a paged space in the old generation and on
1055 // every allocation in large object space.
1056 static int old_gen_allocation_limit_;
1057
1058 // Limit on the amount of externally allocated memory allowed
1059 // between global GCs. If reached a global GC is forced.
1060 static int external_allocation_limit_;
1061
1062 // The amount of external memory registered through the API kept alive
1063 // by global handles
1064 static int amount_of_external_allocated_memory_;
1065
1066 // Caches the amount of external memory registered at the last global gc.
1067 static int amount_of_external_allocated_memory_at_last_global_gc_;
1068
1069 // Indicates that an allocation has failed in the old generation since the
1070 // last GC.
1071 static int old_gen_exhausted_;
1072
1073 static Object* roots_[kRootListLength];
1074
1075 struct StringTypeTable {
1076 InstanceType type;
1077 int size;
1078 RootListIndex index;
1079 };
1080
1081 struct ConstantSymbolTable {
1082 const char* contents;
1083 RootListIndex index;
1084 };
1085
1086 struct StructTable {
1087 InstanceType type;
1088 int size;
1089 RootListIndex index;
1090 };
1091
1092 static const StringTypeTable string_type_table[];
1093 static const ConstantSymbolTable constant_symbol_table[];
1094 static const StructTable struct_table[];
1095
1096 // The special hidden symbol which is an empty string, but does not match
1097 // any string when looked up in properties.
1098 static String* hidden_symbol_;
1099
1100 // GC callback function, called before and after mark-compact GC.
1101 // Allocations in the callback function are disallowed.
Steve Block6ded16b2010-05-10 14:33:55 +01001102 struct GCPrologueCallbackPair {
1103 GCPrologueCallbackPair(GCPrologueCallback callback, GCType gc_type)
1104 : callback(callback), gc_type(gc_type) {
1105 }
1106 bool operator==(const GCPrologueCallbackPair& pair) const {
1107 return pair.callback == callback;
1108 }
1109 GCPrologueCallback callback;
1110 GCType gc_type;
1111 };
1112 static List<GCPrologueCallbackPair> gc_prologue_callbacks_;
1113
1114 struct GCEpilogueCallbackPair {
1115 GCEpilogueCallbackPair(GCEpilogueCallback callback, GCType gc_type)
1116 : callback(callback), gc_type(gc_type) {
1117 }
1118 bool operator==(const GCEpilogueCallbackPair& pair) const {
1119 return pair.callback == callback;
1120 }
1121 GCEpilogueCallback callback;
1122 GCType gc_type;
1123 };
1124 static List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
1125
Steve Blocka7e24c12009-10-30 11:49:00 +00001126 static GCCallback global_gc_prologue_callback_;
1127 static GCCallback global_gc_epilogue_callback_;
1128
1129 // Checks whether a global GC is necessary
1130 static GarbageCollector SelectGarbageCollector(AllocationSpace space);
1131
1132 // Performs garbage collection
1133 static void PerformGarbageCollection(AllocationSpace space,
1134 GarbageCollector collector,
1135 GCTracer* tracer);
1136
Steve Blocka7e24c12009-10-30 11:49:00 +00001137 // Allocate an uninitialized object in map space. The behavior is identical
1138 // to Heap::AllocateRaw(size_in_bytes, MAP_SPACE), except that (a) it doesn't
1139 // have to test the allocation space argument and (b) can reduce code size
1140 // (since both AllocateRaw and AllocateRawMap are inlined).
1141 static inline Object* AllocateRawMap();
1142
1143 // Allocate an uninitialized object in the global property cell space.
1144 static inline Object* AllocateRawCell();
1145
1146 // Initializes a JSObject based on its map.
1147 static void InitializeJSObjectFromMap(JSObject* obj,
1148 FixedArray* properties,
1149 Map* map);
1150
1151 static bool CreateInitialMaps();
1152 static bool CreateInitialObjects();
1153
1154 // These four Create*EntryStub functions are here because of a gcc-4.4 bug
1155 // that assigns wrong vtable entries.
1156 static void CreateCEntryStub();
Steve Blocka7e24c12009-10-30 11:49:00 +00001157 static void CreateJSEntryStub();
1158 static void CreateJSConstructEntryStub();
1159 static void CreateRegExpCEntryStub();
1160
1161 static void CreateFixedStubs();
1162
Steve Block6ded16b2010-05-10 14:33:55 +01001163 static Object* CreateOddball(const char* to_string, Object* to_number);
Steve Blocka7e24c12009-10-30 11:49:00 +00001164
1165 // Allocate empty fixed array.
1166 static Object* AllocateEmptyFixedArray();
1167
1168 // Performs a minor collection in new generation.
1169 static void Scavenge();
Steve Block6ded16b2010-05-10 14:33:55 +01001170
1171 static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
1172 Object** pointer);
1173
Leon Clarkee46be812010-01-19 14:06:41 +00001174 static Address DoScavenge(ObjectVisitor* scavenge_visitor,
1175 Address new_space_front);
Steve Blocka7e24c12009-10-30 11:49:00 +00001176
1177 // Performs a major collection in the whole heap.
1178 static void MarkCompact(GCTracer* tracer);
1179
1180 // Code to be run before and after mark-compact.
1181 static void MarkCompactPrologue(bool is_compacting);
1182 static void MarkCompactEpilogue(bool is_compacting);
1183
Kristian Monsen25f61362010-05-21 11:50:48 +01001184 // Completely clear the Instanceof cache (to stop it keeping objects alive
1185 // around a GC).
1186 static void CompletelyClearInstanceofCache() {
1187 set_instanceof_cache_map(the_hole_value());
1188 set_instanceof_cache_function(the_hole_value());
1189 }
1190
Steve Blocka7e24c12009-10-30 11:49:00 +00001191 // Helper function used by CopyObject to copy a source object to an
1192 // allocated target object and update the forwarding pointer in the source
1193 // object. Returns the target object.
Leon Clarkee46be812010-01-19 14:06:41 +00001194 static inline HeapObject* MigrateObject(HeapObject* source,
1195 HeapObject* target,
1196 int size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001197
Steve Blocka7e24c12009-10-30 11:49:00 +00001198#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1199 // Record the copy of an object in the NewSpace's statistics.
1200 static void RecordCopiedObject(HeapObject* obj);
1201
1202 // Record statistics before and after garbage collection.
1203 static void ReportStatisticsBeforeGC();
1204 static void ReportStatisticsAfterGC();
1205#endif
1206
Steve Blocka7e24c12009-10-30 11:49:00 +00001207 // Rebuild remembered set in an old space.
1208 static void RebuildRSets(PagedSpace* space);
1209
1210 // Rebuild remembered set in the large object space.
1211 static void RebuildRSets(LargeObjectSpace* space);
1212
1213 // Slow part of scavenge object.
1214 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
1215
Steve Blocka7e24c12009-10-30 11:49:00 +00001216 // Initializes a function with a shared part and prototype.
1217 // Returns the function.
1218 // Note: this code was factored out of AllocateFunction such that
1219 // other parts of the VM could use it. Specifically, a function that creates
1220 // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
1221 // Please note this does not perform a garbage collection.
1222 static inline Object* InitializeFunction(JSFunction* function,
1223 SharedFunctionInfo* shared,
1224 Object* prototype);
1225
Leon Clarkee46be812010-01-19 14:06:41 +00001226
1227 // Initializes the number to string cache based on the max semispace size.
1228 static Object* InitializeNumberStringCache();
1229 // Flush the number to string cache.
1230 static void FlushNumberStringCache();
1231
Steve Blocka7e24c12009-10-30 11:49:00 +00001232 static const int kInitialSymbolTableSize = 2048;
1233 static const int kInitialEvalCacheSize = 64;
1234
1235 friend class Factory;
1236 friend class DisallowAllocationFailure;
1237 friend class AlwaysAllocateScope;
Steve Blockd0582a62009-12-15 09:54:21 +00001238 friend class LinearAllocationScope;
1239};
1240
1241
1242class HeapStats {
1243 public:
Steve Block6ded16b2010-05-10 14:33:55 +01001244 int* start_marker;
1245 int* new_space_size;
1246 int* new_space_capacity;
1247 int* old_pointer_space_size;
1248 int* old_pointer_space_capacity;
1249 int* old_data_space_size;
1250 int* old_data_space_capacity;
1251 int* code_space_size;
1252 int* code_space_capacity;
1253 int* map_space_size;
1254 int* map_space_capacity;
1255 int* cell_space_size;
1256 int* cell_space_capacity;
1257 int* lo_space_size;
1258 int* global_handle_count;
1259 int* weak_global_handle_count;
1260 int* pending_global_handle_count;
1261 int* near_death_global_handle_count;
1262 int* destroyed_global_handle_count;
1263 int* end_marker;
Steve Blocka7e24c12009-10-30 11:49:00 +00001264};
1265
1266
1267class AlwaysAllocateScope {
1268 public:
1269 AlwaysAllocateScope() {
1270 // We shouldn't hit any nested scopes, because that requires
1271 // non-handle code to call handle code. The code still works but
1272 // performance will degrade, so we want to catch this situation
1273 // in debug mode.
1274 ASSERT(Heap::always_allocate_scope_depth_ == 0);
1275 Heap::always_allocate_scope_depth_++;
1276 }
1277
1278 ~AlwaysAllocateScope() {
1279 Heap::always_allocate_scope_depth_--;
1280 ASSERT(Heap::always_allocate_scope_depth_ == 0);
1281 }
1282};
1283
1284
Steve Blockd0582a62009-12-15 09:54:21 +00001285class LinearAllocationScope {
1286 public:
1287 LinearAllocationScope() {
1288 Heap::linear_allocation_scope_depth_++;
1289 }
1290
1291 ~LinearAllocationScope() {
1292 Heap::linear_allocation_scope_depth_--;
1293 ASSERT(Heap::linear_allocation_scope_depth_ >= 0);
1294 }
1295};
1296
1297
Steve Blocka7e24c12009-10-30 11:49:00 +00001298#ifdef DEBUG
1299// Visitor class to verify interior pointers that do not have remembered set
1300// bits. All heap object pointers have to point into the heap to a location
1301// that has a map pointer at its first word. Caveat: Heap::Contains is an
1302// approximation because it can return true for objects in a heap space but
1303// above the allocation pointer.
1304class VerifyPointersVisitor: public ObjectVisitor {
1305 public:
1306 void VisitPointers(Object** start, Object** end) {
1307 for (Object** current = start; current < end; current++) {
1308 if ((*current)->IsHeapObject()) {
1309 HeapObject* object = HeapObject::cast(*current);
1310 ASSERT(Heap::Contains(object));
1311 ASSERT(object->map()->IsMap());
1312 }
1313 }
1314 }
1315};
1316
1317
1318// Visitor class to verify interior pointers that have remembered set bits.
1319// As VerifyPointersVisitor but also checks that remembered set bits are
1320// always set for pointers into new space.
1321class VerifyPointersAndRSetVisitor: public ObjectVisitor {
1322 public:
1323 void VisitPointers(Object** start, Object** end) {
1324 for (Object** current = start; current < end; current++) {
1325 if ((*current)->IsHeapObject()) {
1326 HeapObject* object = HeapObject::cast(*current);
1327 ASSERT(Heap::Contains(object));
1328 ASSERT(object->map()->IsMap());
1329 if (Heap::InNewSpace(object)) {
1330 ASSERT(Page::IsRSetSet(reinterpret_cast<Address>(current), 0));
1331 }
1332 }
1333 }
1334 }
1335};
1336#endif
1337
1338
1339// Space iterator for iterating over all spaces of the heap.
1340// Returns each space in turn, and null when it is done.
1341class AllSpaces BASE_EMBEDDED {
1342 public:
1343 Space* next();
1344 AllSpaces() { counter_ = FIRST_SPACE; }
1345 private:
1346 int counter_;
1347};
1348
1349
1350// Space iterator for iterating over all old spaces of the heap: Old pointer
1351// space, old data space and code space.
1352// Returns each space in turn, and null when it is done.
1353class OldSpaces BASE_EMBEDDED {
1354 public:
1355 OldSpace* next();
1356 OldSpaces() { counter_ = OLD_POINTER_SPACE; }
1357 private:
1358 int counter_;
1359};
1360
1361
1362// Space iterator for iterating over all the paged spaces of the heap:
Leon Clarkee46be812010-01-19 14:06:41 +00001363// Map space, old pointer space, old data space, code space and cell space.
Steve Blocka7e24c12009-10-30 11:49:00 +00001364// Returns each space in turn, and null when it is done.
1365class PagedSpaces BASE_EMBEDDED {
1366 public:
1367 PagedSpace* next();
1368 PagedSpaces() { counter_ = OLD_POINTER_SPACE; }
1369 private:
1370 int counter_;
1371};
1372
1373
1374// Space iterator for iterating over all spaces of the heap.
1375// For each space an object iterator is provided. The deallocation of the
1376// returned object iterators is handled by the space iterator.
1377class SpaceIterator : public Malloced {
1378 public:
1379 SpaceIterator();
1380 virtual ~SpaceIterator();
1381
1382 bool has_next();
1383 ObjectIterator* next();
1384
1385 private:
1386 ObjectIterator* CreateIterator();
1387
1388 int current_space_; // from enum AllocationSpace.
1389 ObjectIterator* iterator_; // object iterator for the current space.
1390};
1391
1392
1393// A HeapIterator provides iteration over the whole heap It aggregates a the
1394// specific iterators for the different spaces as these can only iterate over
1395// one space only.
1396
1397class HeapIterator BASE_EMBEDDED {
1398 public:
1399 explicit HeapIterator();
1400 virtual ~HeapIterator();
1401
Steve Blocka7e24c12009-10-30 11:49:00 +00001402 HeapObject* next();
1403 void reset();
1404
1405 private:
1406 // Perform the initialization.
1407 void Init();
1408
1409 // Perform all necessary shutdown (destruction) work.
1410 void Shutdown();
1411
1412 // Space iterator for iterating all the spaces.
1413 SpaceIterator* space_iterator_;
1414 // Object iterator for the space currently being iterated.
1415 ObjectIterator* object_iterator_;
1416};
1417
1418
1419// Cache for mapping (map, property name) into field offset.
1420// Cleared at startup and prior to mark sweep collection.
1421class KeyedLookupCache {
1422 public:
1423 // Lookup field offset for (map, name). If absent, -1 is returned.
1424 static int Lookup(Map* map, String* name);
1425
1426 // Update an element in the cache.
1427 static void Update(Map* map, String* name, int field_offset);
1428
1429 // Clear the cache.
1430 static void Clear();
Leon Clarkee46be812010-01-19 14:06:41 +00001431
1432 static const int kLength = 64;
1433 static const int kCapacityMask = kLength - 1;
1434 static const int kMapHashShift = 2;
1435
Steve Blocka7e24c12009-10-30 11:49:00 +00001436 private:
1437 static inline int Hash(Map* map, String* name);
Leon Clarkee46be812010-01-19 14:06:41 +00001438
1439 // Get the address of the keys and field_offsets arrays. Used in
1440 // generated code to perform cache lookups.
1441 static Address keys_address() {
1442 return reinterpret_cast<Address>(&keys_);
1443 }
1444
1445 static Address field_offsets_address() {
1446 return reinterpret_cast<Address>(&field_offsets_);
1447 }
1448
Steve Blocka7e24c12009-10-30 11:49:00 +00001449 struct Key {
1450 Map* map;
1451 String* name;
1452 };
1453 static Key keys_[kLength];
1454 static int field_offsets_[kLength];
Steve Blocka7e24c12009-10-30 11:49:00 +00001455
Leon Clarkee46be812010-01-19 14:06:41 +00001456 friend class ExternalReference;
1457};
Steve Blocka7e24c12009-10-30 11:49:00 +00001458
1459
1460// Cache for mapping (array, property name) into descriptor index.
1461// The cache contains both positive and negative results.
1462// Descriptor index equals kNotFound means the property is absent.
1463// Cleared at startup and prior to any gc.
1464class DescriptorLookupCache {
1465 public:
1466 // Lookup descriptor index for (map, name).
1467 // If absent, kAbsent is returned.
1468 static int Lookup(DescriptorArray* array, String* name) {
1469 if (!StringShape(name).IsSymbol()) return kAbsent;
1470 int index = Hash(array, name);
1471 Key& key = keys_[index];
1472 if ((key.array == array) && (key.name == name)) return results_[index];
1473 return kAbsent;
1474 }
1475
1476 // Update an element in the cache.
1477 static void Update(DescriptorArray* array, String* name, int result) {
1478 ASSERT(result != kAbsent);
1479 if (StringShape(name).IsSymbol()) {
1480 int index = Hash(array, name);
1481 Key& key = keys_[index];
1482 key.array = array;
1483 key.name = name;
1484 results_[index] = result;
1485 }
1486 }
1487
1488 // Clear the cache.
1489 static void Clear();
1490
1491 static const int kAbsent = -2;
1492 private:
1493 static int Hash(DescriptorArray* array, String* name) {
1494 // Uses only lower 32 bits if pointers are larger.
Andrei Popescu402d9372010-02-26 13:31:12 +00001495 uint32_t array_hash =
Steve Blocka7e24c12009-10-30 11:49:00 +00001496 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(array)) >> 2;
Andrei Popescu402d9372010-02-26 13:31:12 +00001497 uint32_t name_hash =
Steve Blocka7e24c12009-10-30 11:49:00 +00001498 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >> 2;
1499 return (array_hash ^ name_hash) % kLength;
1500 }
1501
1502 static const int kLength = 64;
1503 struct Key {
1504 DescriptorArray* array;
1505 String* name;
1506 };
1507
1508 static Key keys_[kLength];
1509 static int results_[kLength];
1510};
1511
1512
1513// ----------------------------------------------------------------------------
1514// Marking stack for tracing live objects.
1515
1516class MarkingStack {
1517 public:
1518 void Initialize(Address low, Address high) {
1519 top_ = low_ = reinterpret_cast<HeapObject**>(low);
1520 high_ = reinterpret_cast<HeapObject**>(high);
1521 overflowed_ = false;
1522 }
1523
1524 bool is_full() { return top_ >= high_; }
1525
1526 bool is_empty() { return top_ <= low_; }
1527
1528 bool overflowed() { return overflowed_; }
1529
1530 void clear_overflowed() { overflowed_ = false; }
1531
1532 // Push the (marked) object on the marking stack if there is room,
1533 // otherwise mark the object as overflowed and wait for a rescan of the
1534 // heap.
1535 void Push(HeapObject* object) {
1536 CHECK(object->IsHeapObject());
1537 if (is_full()) {
1538 object->SetOverflow();
1539 overflowed_ = true;
1540 } else {
1541 *(top_++) = object;
1542 }
1543 }
1544
1545 HeapObject* Pop() {
1546 ASSERT(!is_empty());
1547 HeapObject* object = *(--top_);
1548 CHECK(object->IsHeapObject());
1549 return object;
1550 }
1551
1552 private:
1553 HeapObject** low_;
1554 HeapObject** top_;
1555 HeapObject** high_;
1556 bool overflowed_;
1557};
1558
1559
1560// A helper class to document/test C++ scopes where we do not
1561// expect a GC. Usage:
1562//
1563// /* Allocation not allowed: we cannot handle a GC in this scope. */
1564// { AssertNoAllocation nogc;
1565// ...
1566// }
1567
1568#ifdef DEBUG
1569
1570class DisallowAllocationFailure {
1571 public:
1572 DisallowAllocationFailure() {
1573 old_state_ = Heap::disallow_allocation_failure_;
1574 Heap::disallow_allocation_failure_ = true;
1575 }
1576 ~DisallowAllocationFailure() {
1577 Heap::disallow_allocation_failure_ = old_state_;
1578 }
1579 private:
1580 bool old_state_;
1581};
1582
1583class AssertNoAllocation {
1584 public:
1585 AssertNoAllocation() {
1586 old_state_ = Heap::allow_allocation(false);
1587 }
1588
1589 ~AssertNoAllocation() {
1590 Heap::allow_allocation(old_state_);
1591 }
1592
1593 private:
1594 bool old_state_;
1595};
1596
1597class DisableAssertNoAllocation {
1598 public:
1599 DisableAssertNoAllocation() {
1600 old_state_ = Heap::allow_allocation(true);
1601 }
1602
1603 ~DisableAssertNoAllocation() {
1604 Heap::allow_allocation(old_state_);
1605 }
1606
1607 private:
1608 bool old_state_;
1609};
1610
1611#else // ndef DEBUG
1612
1613class AssertNoAllocation {
1614 public:
1615 AssertNoAllocation() { }
1616 ~AssertNoAllocation() { }
1617};
1618
1619class DisableAssertNoAllocation {
1620 public:
1621 DisableAssertNoAllocation() { }
1622 ~DisableAssertNoAllocation() { }
1623};
1624
1625#endif
1626
1627// GCTracer collects and prints ONE line after each garbage collector
1628// invocation IFF --trace_gc is used.
1629
1630class GCTracer BASE_EMBEDDED {
1631 public:
Steve Block6ded16b2010-05-10 14:33:55 +01001632 // Time spent while in the external scope counts towards the
1633 // external time in the tracer and will be reported separately.
1634 class ExternalScope BASE_EMBEDDED {
1635 public:
1636 explicit ExternalScope(GCTracer* tracer) : tracer_(tracer) {
1637 start_time_ = OS::TimeCurrentMillis();
1638 }
1639 ~ExternalScope() {
1640 tracer_->external_time_ += OS::TimeCurrentMillis() - start_time_;
1641 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001642
Steve Block6ded16b2010-05-10 14:33:55 +01001643 private:
1644 GCTracer* tracer_;
1645 double start_time_;
1646 };
1647
1648 GCTracer();
Steve Blocka7e24c12009-10-30 11:49:00 +00001649 ~GCTracer();
1650
1651 // Sets the collector.
1652 void set_collector(GarbageCollector collector) { collector_ = collector; }
1653
1654 // Sets the GC count.
1655 void set_gc_count(int count) { gc_count_ = count; }
1656
1657 // Sets the full GC count.
1658 void set_full_gc_count(int count) { full_gc_count_ = count; }
1659
1660 // Sets the flag that this is a compacting full GC.
1661 void set_is_compacting() { is_compacting_ = true; }
Steve Block6ded16b2010-05-10 14:33:55 +01001662 bool is_compacting() const { return is_compacting_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001663
1664 // Increment and decrement the count of marked objects.
1665 void increment_marked_count() { ++marked_count_; }
1666 void decrement_marked_count() { --marked_count_; }
1667
1668 int marked_count() { return marked_count_; }
1669
1670 private:
1671 // Returns a string matching the collector.
1672 const char* CollectorString();
1673
1674 // Returns size of object in heap (in MB).
1675 double SizeOfHeapObjects() {
1676 return (static_cast<double>(Heap::SizeOfObjects())) / MB;
1677 }
1678
1679 double start_time_; // Timestamp set in the constructor.
1680 double start_size_; // Size of objects in heap set in constructor.
1681 GarbageCollector collector_; // Type of collector.
1682
Steve Block6ded16b2010-05-10 14:33:55 +01001683 // Keep track of the amount of time spent in external callbacks.
1684 double external_time_;
1685
Steve Blocka7e24c12009-10-30 11:49:00 +00001686 // A count (including this one, eg, the first collection is 1) of the
1687 // number of garbage collections.
1688 int gc_count_;
1689
1690 // A count (including this one) of the number of full garbage collections.
1691 int full_gc_count_;
1692
1693 // True if the current GC is a compacting full collection, false
1694 // otherwise.
1695 bool is_compacting_;
1696
1697 // True if the *previous* full GC cwas a compacting collection (will be
1698 // false if there has not been a previous full GC).
1699 bool previous_has_compacted_;
1700
1701 // On a full GC, a count of the number of marked objects. Incremented
1702 // when an object is marked and decremented when an object's mark bit is
1703 // cleared. Will be zero on a scavenge collection.
1704 int marked_count_;
1705
1706 // The count from the end of the previous full GC. Will be zero if there
1707 // was no previous full GC.
1708 int previous_marked_count_;
1709};
1710
1711
1712class TranscendentalCache {
1713 public:
1714 enum Type {ACOS, ASIN, ATAN, COS, EXP, LOG, SIN, TAN, kNumberOfCaches};
1715
1716 explicit TranscendentalCache(Type t);
1717
1718 // Returns a heap number with f(input), where f is a math function specified
1719 // by the 'type' argument.
1720 static inline Object* Get(Type type, double input) {
1721 TranscendentalCache* cache = caches_[type];
1722 if (cache == NULL) {
1723 caches_[type] = cache = new TranscendentalCache(type);
1724 }
1725 return cache->Get(input);
1726 }
1727
1728 // The cache contains raw Object pointers. This method disposes of
1729 // them before a garbage collection.
1730 static void Clear();
1731
1732 private:
1733 inline Object* Get(double input) {
1734 Converter c;
1735 c.dbl = input;
1736 int hash = Hash(c);
1737 Element e = elements_[hash];
1738 if (e.in[0] == c.integers[0] &&
1739 e.in[1] == c.integers[1]) {
1740 ASSERT(e.output != NULL);
Andrei Popescu402d9372010-02-26 13:31:12 +00001741 Counters::transcendental_cache_hit.Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +00001742 return e.output;
1743 }
1744 double answer = Calculate(input);
1745 Object* heap_number = Heap::AllocateHeapNumber(answer);
1746 if (!heap_number->IsFailure()) {
1747 elements_[hash].in[0] = c.integers[0];
1748 elements_[hash].in[1] = c.integers[1];
1749 elements_[hash].output = heap_number;
1750 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001751 Counters::transcendental_cache_miss.Increment();
Steve Blocka7e24c12009-10-30 11:49:00 +00001752 return heap_number;
1753 }
1754
1755 inline double Calculate(double input) {
1756 switch (type_) {
1757 case ACOS:
1758 return acos(input);
1759 case ASIN:
1760 return asin(input);
1761 case ATAN:
1762 return atan(input);
1763 case COS:
1764 return cos(input);
1765 case EXP:
1766 return exp(input);
1767 case LOG:
1768 return log(input);
1769 case SIN:
1770 return sin(input);
1771 case TAN:
1772 return tan(input);
1773 default:
1774 return 0.0; // Never happens.
1775 }
1776 }
1777 static const int kCacheSize = 512;
1778 struct Element {
1779 uint32_t in[2];
1780 Object* output;
1781 };
1782 union Converter {
1783 double dbl;
1784 uint32_t integers[2];
1785 };
1786 inline static int Hash(const Converter& c) {
1787 uint32_t hash = (c.integers[0] ^ c.integers[1]);
1788 hash ^= hash >> 16;
1789 hash ^= hash >> 8;
1790 return (hash & (kCacheSize - 1));
1791 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001792
1793 static Address cache_array_address() {
1794 // Used to create an external reference.
1795 return reinterpret_cast<Address>(caches_);
1796 }
1797
1798 // Allow access to the caches_ array as an ExternalReference.
1799 friend class ExternalReference;
1800 // Inline implementation of the caching.
1801 friend class TranscendentalCacheStub;
1802
Steve Blocka7e24c12009-10-30 11:49:00 +00001803 static TranscendentalCache* caches_[kNumberOfCaches];
1804 Element elements_[kCacheSize];
1805 Type type_;
1806};
1807
1808
Leon Clarkee46be812010-01-19 14:06:41 +00001809// External strings table is a place where all external strings are
1810// registered. We need to keep track of such strings to properly
1811// finalize them.
1812class ExternalStringTable : public AllStatic {
1813 public:
1814 // Registers an external string.
1815 inline static void AddString(String* string);
1816
1817 inline static void Iterate(ObjectVisitor* v);
1818
1819 // Restores internal invariant and gets rid of collected strings.
1820 // Must be called after each Iterate() that modified the strings.
1821 static void CleanUp();
1822
1823 // Destroys all allocated memory.
1824 static void TearDown();
1825
1826 private:
1827 friend class Heap;
1828
1829 inline static void Verify();
1830
1831 inline static void AddOldString(String* string);
1832
1833 // Notifies the table that only a prefix of the new list is valid.
1834 inline static void ShrinkNewStrings(int position);
1835
1836 // To speed up scavenge collections new space string are kept
1837 // separate from old space strings.
1838 static List<Object*> new_space_strings_;
1839 static List<Object*> old_space_strings_;
1840};
1841
Steve Blocka7e24c12009-10-30 11:49:00 +00001842} } // namespace v8::internal
1843
1844#endif // V8_HEAP_H_