1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
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.
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.
33 #include "allocation.h"
34 #include "assert-scope.h"
36 #include "incremental-marking.h"
38 #include "mark-compact.h"
39 #include "objects-visiting.h"
41 #include "splay-tree-inl.h"
42 #include "store-buffer.h"
43 #include "v8-counters.h"
44 #include "v8globals.h"
49 // Defines all the roots in Heap.
50 #define STRONG_ROOT_LIST(V) \
51 V(Map, byte_array_map, ByteArrayMap) \
52 V(Map, free_space_map, FreeSpaceMap) \
53 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
54 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
55 /* Cluster the most popular ones in a few cache lines here at the top. */ \
56 V(Smi, store_buffer_top, StoreBufferTop) \
57 V(Oddball, undefined_value, UndefinedValue) \
58 V(Oddball, the_hole_value, TheHoleValue) \
59 V(Oddball, null_value, NullValue) \
60 V(Oddball, true_value, TrueValue) \
61 V(Oddball, false_value, FalseValue) \
62 V(Oddball, uninitialized_value, UninitializedValue) \
63 V(Map, cell_map, CellMap) \
64 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
65 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
66 V(Map, meta_map, MetaMap) \
67 V(Map, heap_number_map, HeapNumberMap) \
68 V(Map, float32x4_map, Float32x4Map) \
69 V(Map, int32x4_map, Int32x4Map) \
70 V(Map, native_context_map, NativeContextMap) \
71 V(Map, fixed_array_map, FixedArrayMap) \
72 V(Map, code_map, CodeMap) \
73 V(Map, scope_info_map, ScopeInfoMap) \
74 V(Map, fixed_cow_array_map, FixedCOWArrayMap) \
75 V(Map, fixed_double_array_map, FixedDoubleArrayMap) \
76 V(Map, constant_pool_array_map, ConstantPoolArrayMap) \
77 V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
78 V(Map, hash_table_map, HashTableMap) \
79 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
80 V(ByteArray, empty_byte_array, EmptyByteArray) \
81 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
82 V(ConstantPoolArray, empty_constant_pool_array, EmptyConstantPoolArray) \
83 V(Oddball, arguments_marker, ArgumentsMarker) \
84 /* The roots above this line should be boring from a GC point of view. */ \
85 /* This means they are never in new space and never on a page that is */ \
86 /* being compacted. */ \
87 V(FixedArray, number_string_cache, NumberStringCache) \
88 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
89 V(Object, instanceof_cache_map, InstanceofCacheMap) \
90 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
91 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
92 V(FixedArray, string_split_cache, StringSplitCache) \
93 V(FixedArray, regexp_multiple_cache, RegExpMultipleCache) \
94 V(Object, termination_exception, TerminationException) \
95 V(Smi, hash_seed, HashSeed) \
96 V(Map, symbol_map, SymbolMap) \
97 V(Map, string_map, StringMap) \
98 V(Map, ascii_string_map, AsciiStringMap) \
99 V(Map, cons_string_map, ConsStringMap) \
100 V(Map, cons_ascii_string_map, ConsAsciiStringMap) \
101 V(Map, sliced_string_map, SlicedStringMap) \
102 V(Map, sliced_ascii_string_map, SlicedAsciiStringMap) \
103 V(Map, external_string_map, ExternalStringMap) \
105 external_string_with_one_byte_data_map, \
106 ExternalStringWithOneByteDataMap) \
107 V(Map, external_ascii_string_map, ExternalAsciiStringMap) \
108 V(Map, short_external_string_map, ShortExternalStringMap) \
110 short_external_string_with_one_byte_data_map, \
111 ShortExternalStringWithOneByteDataMap) \
112 V(Map, internalized_string_map, InternalizedStringMap) \
113 V(Map, ascii_internalized_string_map, AsciiInternalizedStringMap) \
114 V(Map, cons_internalized_string_map, ConsInternalizedStringMap) \
115 V(Map, cons_ascii_internalized_string_map, ConsAsciiInternalizedStringMap) \
117 external_internalized_string_map, \
118 ExternalInternalizedStringMap) \
120 external_internalized_string_with_one_byte_data_map, \
121 ExternalInternalizedStringWithOneByteDataMap) \
123 external_ascii_internalized_string_map, \
124 ExternalAsciiInternalizedStringMap) \
126 short_external_internalized_string_map, \
127 ShortExternalInternalizedStringMap) \
129 short_external_internalized_string_with_one_byte_data_map, \
130 ShortExternalInternalizedStringWithOneByteDataMap) \
132 short_external_ascii_internalized_string_map, \
133 ShortExternalAsciiInternalizedStringMap) \
134 V(Map, short_external_ascii_string_map, ShortExternalAsciiStringMap) \
135 V(Map, undetectable_string_map, UndetectableStringMap) \
136 V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap) \
137 V(Map, external_int8_array_map, ExternalInt8ArrayMap) \
138 V(Map, external_uint8_array_map, ExternalUint8ArrayMap) \
139 V(Map, external_int16_array_map, ExternalInt16ArrayMap) \
140 V(Map, external_uint16_array_map, ExternalUint16ArrayMap) \
141 V(Map, external_int32_array_map, ExternalInt32ArrayMap) \
142 V(Map, external_int32x4_array_map, ExternalInt32x4ArrayMap) \
143 V(Map, external_uint32_array_map, ExternalUint32ArrayMap) \
144 V(Map, external_float32_array_map, ExternalFloat32ArrayMap) \
145 V(Map, external_float32x4_array_map, ExternalFloat32x4ArrayMap) \
146 V(Map, external_float64_array_map, ExternalFloat64ArrayMap) \
147 V(Map, external_uint8_clamped_array_map, ExternalUint8ClampedArrayMap) \
148 V(ExternalArray, empty_external_int8_array, \
149 EmptyExternalInt8Array) \
150 V(ExternalArray, empty_external_uint8_array, \
151 EmptyExternalUint8Array) \
152 V(ExternalArray, empty_external_int16_array, EmptyExternalInt16Array) \
153 V(ExternalArray, empty_external_uint16_array, \
154 EmptyExternalUint16Array) \
155 V(ExternalArray, empty_external_int32_array, EmptyExternalInt32Array) \
156 V(ExternalArray, empty_external_int32x4_array, EmptyExternalInt32x4Array) \
157 V(ExternalArray, empty_external_uint32_array, \
158 EmptyExternalUint32Array) \
159 V(ExternalArray, empty_external_float32_array, EmptyExternalFloat32Array) \
160 V(ExternalArray, empty_external_float32x4_array, EmptyExternalFloat32x4Array)\
161 V(ExternalArray, empty_external_float64_array, EmptyExternalFloat64Array) \
162 V(ExternalArray, empty_external_uint8_clamped_array, \
163 EmptyExternalUint8ClampedArray) \
164 V(Map, fixed_uint8_array_map, FixedUint8ArrayMap) \
165 V(Map, fixed_int8_array_map, FixedInt8ArrayMap) \
166 V(Map, fixed_uint16_array_map, FixedUint16ArrayMap) \
167 V(Map, fixed_int16_array_map, FixedInt16ArrayMap) \
168 V(Map, fixed_uint32_array_map, FixedUint32ArrayMap) \
169 V(Map, fixed_int32_array_map, FixedInt32ArrayMap) \
170 V(Map, fixed_int32x4_array_map, FixedInt32x4ArrayMap) \
171 V(Map, fixed_float32_array_map, FixedFloat32ArrayMap) \
172 V(Map, fixed_float32x4_array_map, FixedFloat32x4ArrayMap) \
173 V(Map, fixed_float64_array_map, FixedFloat64ArrayMap) \
174 V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap) \
175 V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array) \
176 V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array) \
177 V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array) \
178 V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array) \
179 V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array) \
180 V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array) \
181 V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array) \
182 V(FixedTypedArrayBase, empty_fixed_float32x4_array, \
183 EmptyFixedFloat32x4Array) \
184 V(FixedTypedArrayBase, empty_fixed_int32x4_array, EmptyFixedInt32x4Array) \
185 V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array) \
186 V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array, \
187 EmptyFixedUint8ClampedArray) \
188 V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap) \
189 V(Map, function_context_map, FunctionContextMap) \
190 V(Map, catch_context_map, CatchContextMap) \
191 V(Map, with_context_map, WithContextMap) \
192 V(Map, block_context_map, BlockContextMap) \
193 V(Map, module_context_map, ModuleContextMap) \
194 V(Map, global_context_map, GlobalContextMap) \
195 V(Map, oddball_map, OddballMap) \
196 V(Map, message_object_map, JSMessageObjectMap) \
197 V(Map, foreign_map, ForeignMap) \
198 V(HeapNumber, nan_value, NanValue) \
199 V(HeapNumber, infinity_value, InfinityValue) \
200 V(HeapNumber, minus_zero_value, MinusZeroValue) \
201 V(Map, neander_map, NeanderMap) \
202 V(JSObject, message_listeners, MessageListeners) \
203 V(UnseededNumberDictionary, code_stubs, CodeStubs) \
204 V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
205 V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache) \
206 V(Code, js_entry_code, JsEntryCode) \
207 V(Code, js_construct_entry_code, JsConstructEntryCode) \
208 V(FixedArray, natives_source_cache, NativesSourceCache) \
209 V(Script, empty_script, EmptyScript) \
210 V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames) \
211 V(Cell, undefined_cell, UndefineCell) \
212 V(JSObject, observation_state, ObservationState) \
213 V(Map, external_map, ExternalMap) \
214 V(Object, symbol_registry, SymbolRegistry) \
215 V(Symbol, frozen_symbol, FrozenSymbol) \
216 V(Symbol, nonexistent_symbol, NonExistentSymbol) \
217 V(Symbol, elements_transition_symbol, ElementsTransitionSymbol) \
218 V(SeededNumberDictionary, empty_slow_element_dictionary, \
219 EmptySlowElementDictionary) \
220 V(Symbol, observed_symbol, ObservedSymbol) \
221 V(Symbol, uninitialized_symbol, UninitializedSymbol) \
222 V(Symbol, megamorphic_symbol, MegamorphicSymbol) \
223 V(FixedArray, materialized_objects, MaterializedObjects) \
224 V(FixedArray, allocation_sites_scratchpad, AllocationSitesScratchpad) \
225 V(JSObject, microtask_state, MicrotaskState)
227 // Entries in this list are limited to Smis and are not visited during GC.
228 #define SMI_ROOT_LIST(V) \
229 V(Smi, stack_limit, StackLimit) \
230 V(Smi, real_stack_limit, RealStackLimit) \
231 V(Smi, last_script_id, LastScriptId) \
232 V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset) \
233 V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset) \
234 V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset) \
235 V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
237 #define ROOT_LIST(V) \
238 STRONG_ROOT_LIST(V) \
240 V(StringTable, string_table, StringTable)
242 // Heap roots that are known to be immortal immovable, for which we can safely
243 // skip write barriers.
244 #define IMMORTAL_IMMOVABLE_ROOT_LIST(V) \
247 V(one_pointer_filler_map) \
248 V(two_pointer_filler_map) \
254 V(uninitialized_value) \
256 V(global_property_cell_map) \
257 V(shared_function_info_map) \
260 V(native_context_map) \
264 V(fixed_cow_array_map) \
265 V(fixed_double_array_map) \
266 V(constant_pool_array_map) \
267 V(no_interceptor_result_sentinel) \
269 V(empty_fixed_array) \
270 V(empty_byte_array) \
271 V(empty_descriptor_array) \
272 V(empty_constant_pool_array) \
273 V(arguments_marker) \
275 V(sloppy_arguments_elements_map) \
276 V(function_context_map) \
277 V(catch_context_map) \
278 V(with_context_map) \
279 V(block_context_map) \
280 V(module_context_map) \
281 V(global_context_map) \
283 V(message_object_map) \
287 #define INTERNALIZED_STRING_LIST(V) \
288 V(Array_string, "Array") \
289 V(Object_string, "Object") \
290 V(proto_string, "__proto__") \
291 V(arguments_string, "arguments") \
292 V(Arguments_string, "Arguments") \
293 V(call_string, "call") \
294 V(apply_string, "apply") \
295 V(caller_string, "caller") \
296 V(boolean_string, "boolean") \
297 V(Boolean_string, "Boolean") \
298 V(callee_string, "callee") \
299 V(constructor_string, "constructor") \
300 V(dot_result_string, ".result") \
301 V(dot_for_string, ".for.") \
302 V(dot_iterator_string, ".iterator") \
303 V(dot_generator_object_string, ".generator_object") \
304 V(eval_string, "eval") \
305 V(empty_string, "") \
306 V(function_string, "function") \
307 V(length_string, "length") \
308 V(module_string, "module") \
309 V(name_string, "name") \
310 V(native_string, "native") \
311 V(null_string, "null") \
312 V(number_string, "number") \
313 V(Number_string, "Number") \
314 V(float32x4_string, "float32x4") \
315 V(int32x4_string, "int32x4") \
316 V(nan_string, "NaN") \
317 V(RegExp_string, "RegExp") \
318 V(source_string, "source") \
319 V(global_string, "global") \
320 V(ignore_case_string, "ignoreCase") \
321 V(multiline_string, "multiline") \
322 V(input_string, "input") \
323 V(index_string, "index") \
324 V(last_index_string, "lastIndex") \
325 V(object_string, "object") \
326 V(literals_string, "literals") \
327 V(prototype_string, "prototype") \
328 V(string_string, "string") \
329 V(String_string, "String") \
330 V(symbol_string, "symbol") \
331 V(Symbol_string, "Symbol") \
332 V(for_string, "for") \
333 V(for_api_string, "for_api") \
334 V(for_intern_string, "for_intern") \
335 V(private_api_string, "private_api") \
336 V(private_intern_string, "private_intern") \
337 V(Date_string, "Date") \
338 V(this_string, "this") \
339 V(to_string_string, "toString") \
340 V(char_at_string, "CharAt") \
341 V(undefined_string, "undefined") \
342 V(value_of_string, "valueOf") \
343 V(stack_string, "stack") \
344 V(toJSON_string, "toJSON") \
345 V(InitializeVarGlobal_string, "InitializeVarGlobal") \
346 V(InitializeConstGlobal_string, "InitializeConstGlobal") \
347 V(KeyedLoadElementMonomorphic_string, \
348 "KeyedLoadElementMonomorphic") \
349 V(KeyedStoreElementMonomorphic_string, \
350 "KeyedStoreElementMonomorphic") \
351 V(stack_overflow_string, "kStackOverflowBoilerplate") \
352 V(illegal_access_string, "illegal access") \
353 V(illegal_execution_state_string, "illegal execution state") \
354 V(get_string, "get") \
355 V(set_string, "set") \
356 V(map_field_string, "%map") \
357 V(elements_field_string, "%elements") \
358 V(length_field_string, "%length") \
359 V(cell_value_string, "%cell_value") \
360 V(function_class_string, "Function") \
361 V(illegal_argument_string, "illegal argument") \
362 V(MakeReferenceError_string, "MakeReferenceError") \
363 V(MakeSyntaxError_string, "MakeSyntaxError") \
364 V(MakeTypeError_string, "MakeTypeError") \
365 V(unknown_label_string, "unknown_label") \
366 V(space_string, " ") \
367 V(exec_string, "exec") \
368 V(zero_string, "0") \
369 V(global_eval_string, "GlobalEval") \
370 V(identity_hash_string, "v8::IdentityHash") \
371 V(closure_string, "(closure)") \
372 V(use_strict_string, "use strict") \
374 V(anonymous_function_string, "(anonymous function)") \
375 V(compare_ic_string, "==") \
376 V(strict_compare_ic_string, "===") \
377 V(infinity_string, "Infinity") \
378 V(minus_infinity_string, "-Infinity") \
379 V(hidden_stack_trace_string, "v8::hidden_stack_trace") \
380 V(query_colon_string, "(?:)") \
381 V(Generator_string, "Generator") \
382 V(throw_string, "throw") \
383 V(done_string, "done") \
384 V(value_string, "value") \
385 V(signMask, "signMask") \
395 V(next_string, "next") \
396 V(byte_length_string, "byteLength") \
397 V(byte_offset_string, "byteOffset") \
398 V(buffer_string, "buffer") \
399 V(intl_initialized_marker_string, "v8::intl_initialized_marker") \
400 V(intl_impl_object_string, "v8::intl_object")
402 // Forward declarations.
406 class WeakObjectRetainer;
409 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
412 class StoreBufferRebuilder {
414 explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
415 : store_buffer_(store_buffer) {
418 void Callback(MemoryChunk* page, StoreBufferEvent event);
421 StoreBuffer* store_buffer_;
423 // We record in this variable how full the store buffer was when we started
424 // iterating over the current page, finding pointers to new space. If the
425 // store buffer overflows again we can exempt the page from the store buffer
426 // by rewinding to this point instead of having to search the store buffer.
427 Object*** start_of_current_page_;
428 // The current page we are scanning in the store buffer iterator.
429 MemoryChunk* current_page_;
434 // A queue of objects promoted during scavenge. Each object is accompanied
435 // by it's size to avoid dereferencing a map pointer for scanning.
436 class PromotionQueue {
438 explicit PromotionQueue(Heap* heap)
449 delete emergency_stack_;
450 emergency_stack_ = NULL;
453 inline void ActivateGuardIfOnTheSamePage();
455 Page* GetHeadPage() {
456 return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
459 void SetNewLimit(Address limit) {
464 ASSERT(GetHeadPage() == Page::FromAllocationTop(limit));
465 limit_ = reinterpret_cast<intptr_t*>(limit);
467 if (limit_ <= rear_) {
475 return (front_ == rear_) &&
476 (emergency_stack_ == NULL || emergency_stack_->length() == 0);
479 inline void insert(HeapObject* target, int size);
481 void remove(HeapObject** target, int* size) {
483 if (front_ == rear_) {
484 Entry e = emergency_stack_->RemoveLast();
490 if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(front_))) {
491 NewSpacePage* front_page =
492 NewSpacePage::FromAddress(reinterpret_cast<Address>(front_));
493 ASSERT(!front_page->prev_page()->is_anchor());
495 reinterpret_cast<intptr_t*>(front_page->prev_page()->area_end());
497 *target = reinterpret_cast<HeapObject*>(*(--front_));
498 *size = static_cast<int>(*(--front_));
499 // Assert no underflow.
500 SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
501 reinterpret_cast<Address>(front_));
505 // The front of the queue is higher in the memory page chain than the rear.
512 static const int kEntrySizeInWords = 2;
515 Entry(HeapObject* obj, int size) : obj_(obj), size_(size) { }
520 List<Entry>* emergency_stack_;
524 void RelocateQueueHead();
526 DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
530 typedef void (*ScavengingCallback)(Map* map,
535 // External strings table is a place where all external strings are
536 // registered. We need to keep track of such strings to properly
538 class ExternalStringTable {
540 // Registers an external string.
541 inline void AddString(String* string);
543 inline void Iterate(ObjectVisitor* v);
545 // Restores internal invariant and gets rid of collected strings.
546 // Must be called after each Iterate() that modified the strings.
549 // Destroys all allocated memory.
553 explicit ExternalStringTable(Heap* heap) : heap_(heap) { }
557 inline void Verify();
559 inline void AddOldString(String* string);
561 // Notifies the table that only a prefix of the new list is valid.
562 inline void ShrinkNewStrings(int position);
564 // To speed up scavenge collections new space string are kept
565 // separate from old space strings.
566 List<Object*> new_space_strings_;
567 List<Object*> old_space_strings_;
571 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
575 enum ArrayStorageAllocationMode {
576 DONT_INITIALIZE_ARRAY_ELEMENTS,
577 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
583 // Configure heap size before setup. Return false if the heap has been
585 bool ConfigureHeap(int max_semispace_size,
586 intptr_t max_old_gen_size,
587 intptr_t max_executable_size);
588 bool ConfigureHeapDefault();
590 // Prepares the heap, setting up memory areas that are needed in the isolate
591 // without actually creating any objects.
594 // Bootstraps the object heap with the core set of objects required to run.
595 // Returns whether it succeeded.
596 bool CreateHeapObjects();
598 // Destroys all memory allocated by the heap.
601 // Set the stack limit in the roots_ array. Some architectures generate
602 // code that looks here, because it is faster than loading from the static
603 // jslimit_/real_jslimit_ variable in the StackGuard.
604 void SetStackLimits();
606 // Returns whether SetUp has been called.
609 // Returns the maximum amount of memory reserved for the heap. For
610 // the young generation, we reserve 4 times the amount needed for a
611 // semi space. The young generation consists of two semi spaces and
612 // we reserve twice the amount needed for those in order to ensure
613 // that new space can be aligned to its size.
614 intptr_t MaxReserved() {
615 return 4 * reserved_semispace_size_ + max_old_generation_size_;
617 int MaxSemiSpaceSize() { return max_semispace_size_; }
618 int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
619 int InitialSemiSpaceSize() { return initial_semispace_size_; }
620 intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
621 intptr_t MaxExecutableSize() { return max_executable_size_; }
623 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
624 // more spaces are needed until it reaches the limit.
627 // Returns the amount of memory currently committed for the heap.
628 intptr_t CommittedMemory();
630 // Returns the amount of executable memory currently committed for the heap.
631 intptr_t CommittedMemoryExecutable();
633 // Returns the amount of phyical memory currently committed for the heap.
634 size_t CommittedPhysicalMemory();
636 // Returns the maximum amount of memory ever committed for the heap.
637 intptr_t MaximumCommittedMemory() { return maximum_committed_; }
639 // Updates the maximum committed memory for the heap. Should be called
640 // whenever a space grows.
641 void UpdateMaximumCommitted();
643 // Returns the available bytes in space w/o growing.
644 // Heap doesn't guarantee that it can allocate an object that requires
645 // all available bytes. Check MaxHeapObjectSize() instead.
646 intptr_t Available();
648 // Returns of size of all objects residing in the heap.
649 intptr_t SizeOfObjects();
651 // Return the starting address and a mask for the new space. And-masking an
652 // address with the mask will result in the start address of the new space
653 // for all addresses in either semispace.
654 Address NewSpaceStart() { return new_space_.start(); }
655 uintptr_t NewSpaceMask() { return new_space_.mask(); }
656 Address NewSpaceTop() { return new_space_.top(); }
658 NewSpace* new_space() { return &new_space_; }
659 OldSpace* old_pointer_space() { return old_pointer_space_; }
660 OldSpace* old_data_space() { return old_data_space_; }
661 OldSpace* code_space() { return code_space_; }
662 MapSpace* map_space() { return map_space_; }
663 CellSpace* cell_space() { return cell_space_; }
664 PropertyCellSpace* property_cell_space() {
665 return property_cell_space_;
667 LargeObjectSpace* lo_space() { return lo_space_; }
668 PagedSpace* paged_space(int idx) {
670 case OLD_POINTER_SPACE:
671 return old_pointer_space();
673 return old_data_space();
678 case PROPERTY_CELL_SPACE:
679 return property_cell_space();
689 bool always_allocate() { return always_allocate_scope_depth_ != 0; }
690 Address always_allocate_scope_depth_address() {
691 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
693 bool linear_allocation() {
694 return linear_allocation_scope_depth_ != 0;
697 Address* NewSpaceAllocationTopAddress() {
698 return new_space_.allocation_top_address();
700 Address* NewSpaceAllocationLimitAddress() {
701 return new_space_.allocation_limit_address();
704 Address* OldPointerSpaceAllocationTopAddress() {
705 return old_pointer_space_->allocation_top_address();
707 Address* OldPointerSpaceAllocationLimitAddress() {
708 return old_pointer_space_->allocation_limit_address();
711 Address* OldDataSpaceAllocationTopAddress() {
712 return old_data_space_->allocation_top_address();
714 Address* OldDataSpaceAllocationLimitAddress() {
715 return old_data_space_->allocation_limit_address();
718 // Allocates and initializes a new JavaScript object based on a
720 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
722 // If allocation_site is non-null, then a memento is emitted after the object
723 // that points to the site.
724 // Please note this does not perform a garbage collection.
725 MUST_USE_RESULT MaybeObject* AllocateJSObject(
726 JSFunction* constructor,
727 PretenureFlag pretenure = NOT_TENURED,
728 AllocationSite* allocation_site = NULL);
730 MUST_USE_RESULT MaybeObject* AllocateJSModule(Context* context,
731 ScopeInfo* scope_info);
733 // Allocate a JSArray with no elements
734 MUST_USE_RESULT MaybeObject* AllocateEmptyJSArray(
735 ElementsKind elements_kind,
736 PretenureFlag pretenure = NOT_TENURED) {
737 return AllocateJSArrayAndStorage(elements_kind, 0, 0,
738 DONT_INITIALIZE_ARRAY_ELEMENTS,
742 // Allocate a JSArray with a specified length but elements that are left
744 MUST_USE_RESULT MaybeObject* AllocateJSArrayAndStorage(
745 ElementsKind elements_kind,
748 ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS,
749 PretenureFlag pretenure = NOT_TENURED);
751 MUST_USE_RESULT MaybeObject* AllocateJSArrayStorage(
755 ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS);
757 // Allocate a JSArray with no elements
758 MUST_USE_RESULT MaybeObject* AllocateJSArrayWithElements(
759 FixedArrayBase* array_base,
760 ElementsKind elements_kind,
762 PretenureFlag pretenure = NOT_TENURED);
764 // Returns a deep copy of the JavaScript object.
765 // Properties and elements are copied too.
766 // Returns failure if allocation failed.
767 // Optionally takes an AllocationSite to be appended in an AllocationMemento.
768 MUST_USE_RESULT MaybeObject* CopyJSObject(JSObject* source,
769 AllocationSite* site = NULL);
771 // Allocates a JS ArrayBuffer object.
772 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
774 // Please note this does not perform a garbage collection.
775 MUST_USE_RESULT MaybeObject* AllocateJSArrayBuffer();
777 // Allocates a Harmony proxy or function proxy.
778 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
780 // Please note this does not perform a garbage collection.
781 MUST_USE_RESULT MaybeObject* AllocateJSProxy(Object* handler,
784 MUST_USE_RESULT MaybeObject* AllocateJSFunctionProxy(Object* handler,
786 Object* construct_trap,
789 // Reinitialize a JSReceiver into an (empty) JS object of respective type and
790 // size, but keeping the original prototype. The receiver must have at least
791 // the size of the new object. The object is reinitialized and behaves as an
792 // object that has been freshly allocated.
793 // Returns failure if an error occured, otherwise object.
794 MUST_USE_RESULT MaybeObject* ReinitializeJSReceiver(JSReceiver* object,
798 // Reinitialize an JSGlobalProxy based on a constructor. The object
799 // must have the same size as objects allocated using the
800 // constructor. The object is reinitialized and behaves as an
801 // object that has been freshly allocated using the constructor.
802 MUST_USE_RESULT MaybeObject* ReinitializeJSGlobalProxy(
803 JSFunction* constructor, JSGlobalProxy* global);
805 // Allocates and initializes a new JavaScript object based on a map.
806 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
808 // Passing an allocation site means that a memento will be created that
809 // points to the site.
810 // Please note this does not perform a garbage collection.
811 MUST_USE_RESULT MaybeObject* AllocateJSObjectFromMap(
813 PretenureFlag pretenure = NOT_TENURED,
814 bool alloc_props = true,
815 AllocationSite* allocation_site = NULL);
817 // Allocates a heap object based on the map.
818 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
820 // Please note this function does not perform a garbage collection.
821 MUST_USE_RESULT MaybeObject* Allocate(Map* map, AllocationSpace space,
822 AllocationSite* allocation_site = NULL);
824 // Allocates a JS Map in the heap.
825 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
827 // Please note this function does not perform a garbage collection.
828 MUST_USE_RESULT MaybeObject* AllocateMap(
829 InstanceType instance_type,
831 ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
833 // Allocates a partial map for bootstrapping.
834 MUST_USE_RESULT MaybeObject* AllocatePartialMap(InstanceType instance_type,
837 // Allocates an empty code cache.
838 MUST_USE_RESULT MaybeObject* AllocateCodeCache();
840 // Allocates a serialized scope info.
841 MUST_USE_RESULT MaybeObject* AllocateScopeInfo(int length);
843 // Allocates an External object for v8's external API.
844 MUST_USE_RESULT MaybeObject* AllocateExternal(void* value);
846 // Allocates an empty PolymorphicCodeCache.
847 MUST_USE_RESULT MaybeObject* AllocatePolymorphicCodeCache();
849 // Allocates a pre-tenured empty AccessorPair.
850 MUST_USE_RESULT MaybeObject* AllocateAccessorPair();
852 // Allocates an empty TypeFeedbackInfo.
853 MUST_USE_RESULT MaybeObject* AllocateTypeFeedbackInfo();
855 // Allocates an AliasedArgumentsEntry.
856 MUST_USE_RESULT MaybeObject* AllocateAliasedArgumentsEntry(int slot);
858 // Clear the Instanceof cache (used when a prototype changes).
859 inline void ClearInstanceofCache();
861 // Iterates the whole code space to clear all ICs of the given kind.
862 void ClearAllICsByKind(Code::Kind kind);
864 // For use during bootup.
865 void RepairFreeListsAfterBoot();
867 // Allocates and fully initializes a String. There are two String
868 // encodings: ASCII and two byte. One should choose between the three string
869 // allocation functions based on the encoding of the string buffer used to
870 // initialized the string.
871 // - ...FromAscii initializes the string from a buffer that is ASCII
872 // encoded (it does not check that the buffer is ASCII encoded) and the
873 // result will be ASCII encoded.
874 // - ...FromUTF8 initializes the string from a buffer that is UTF-8
875 // encoded. If the characters are all single-byte characters, the
876 // result will be ASCII encoded, otherwise it will converted to two
878 // - ...FromTwoByte initializes the string from a buffer that is two-byte
879 // encoded. If the characters are all single-byte characters, the
880 // result will be converted to ASCII, otherwise it will be left as
882 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
884 // Please note this does not perform a garbage collection.
885 MUST_USE_RESULT MaybeObject* AllocateStringFromOneByte(
886 Vector<const uint8_t> str,
887 PretenureFlag pretenure = NOT_TENURED);
888 // TODO(dcarney): remove this function.
889 MUST_USE_RESULT inline MaybeObject* AllocateStringFromOneByte(
890 Vector<const char> str,
891 PretenureFlag pretenure = NOT_TENURED) {
892 return AllocateStringFromOneByte(Vector<const uint8_t>::cast(str),
895 MUST_USE_RESULT inline MaybeObject* AllocateStringFromUtf8(
896 Vector<const char> str,
897 PretenureFlag pretenure = NOT_TENURED);
898 MUST_USE_RESULT MaybeObject* AllocateStringFromUtf8Slow(
899 Vector<const char> str,
901 PretenureFlag pretenure = NOT_TENURED);
902 MUST_USE_RESULT MaybeObject* AllocateStringFromTwoByte(
903 Vector<const uc16> str,
904 PretenureFlag pretenure = NOT_TENURED);
906 // Allocates an internalized string in old space based on the character
907 // stream. Returns Failure::RetryAfterGC(requested_bytes, space) if the
908 // allocation failed.
909 // Please note this function does not perform a garbage collection.
910 MUST_USE_RESULT inline MaybeObject* AllocateInternalizedStringFromUtf8(
911 Vector<const char> str,
913 uint32_t hash_field);
915 MUST_USE_RESULT inline MaybeObject* AllocateOneByteInternalizedString(
916 Vector<const uint8_t> str,
917 uint32_t hash_field);
919 MUST_USE_RESULT inline MaybeObject* AllocateTwoByteInternalizedString(
920 Vector<const uc16> str,
921 uint32_t hash_field);
924 static inline bool IsOneByte(T t, int chars);
927 MUST_USE_RESULT inline MaybeObject* AllocateInternalizedStringImpl(
928 T t, int chars, uint32_t hash_field);
930 template<bool is_one_byte, typename T>
931 MUST_USE_RESULT MaybeObject* AllocateInternalizedStringImpl(
932 T t, int chars, uint32_t hash_field);
934 // Allocates and partially initializes a String. There are two String
935 // encodings: ASCII and two byte. These functions allocate a string of the
936 // given length and set its map and length fields. The characters of the
937 // string are uninitialized.
938 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
940 // Please note this does not perform a garbage collection.
941 MUST_USE_RESULT MaybeObject* AllocateRawOneByteString(
943 PretenureFlag pretenure = NOT_TENURED);
944 MUST_USE_RESULT MaybeObject* AllocateRawTwoByteString(
946 PretenureFlag pretenure = NOT_TENURED);
948 // Computes a single character string where the character has code.
949 // A cache is used for ASCII codes.
950 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
951 // failed. Please note this does not perform a garbage collection.
952 MUST_USE_RESULT MaybeObject* LookupSingleCharacterStringFromCode(
955 // Allocate a byte array of the specified length
956 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
958 // Please note this does not perform a garbage collection.
959 MUST_USE_RESULT MaybeObject* AllocateByteArray(
961 PretenureFlag pretenure = NOT_TENURED);
963 // Allocates an external array of the specified length and type.
964 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
966 // Please note this does not perform a garbage collection.
967 MUST_USE_RESULT MaybeObject* AllocateExternalArray(
969 ExternalArrayType array_type,
970 void* external_pointer,
971 PretenureFlag pretenure);
973 // Allocates a fixed typed array of the specified length and type.
974 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
976 // Please note this does not perform a garbage collection.
977 MUST_USE_RESULT MaybeObject* AllocateFixedTypedArray(
979 ExternalArrayType array_type,
980 PretenureFlag pretenure);
982 // Allocate a symbol in old space.
983 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
985 // Please note this does not perform a garbage collection.
986 MUST_USE_RESULT MaybeObject* AllocateSymbol();
987 MUST_USE_RESULT MaybeObject* AllocatePrivateSymbol();
989 // Allocate a tenured AllocationSite. It's payload is null
990 MUST_USE_RESULT MaybeObject* AllocateAllocationSite();
992 // Allocates a fixed array initialized with undefined values
993 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
995 // Please note this does not perform a garbage collection.
996 MUST_USE_RESULT MaybeObject* AllocateFixedArray(
998 PretenureFlag pretenure = NOT_TENURED);
1000 // Allocates an uninitialized fixed array. It must be filled by the caller.
1002 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1004 // Please note this does not perform a garbage collection.
1005 MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedArray(int length);
1007 // Move len elements within a given array from src_index index to dst_index
1009 void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
1011 // Make a copy of src and return it. Returns
1012 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1013 MUST_USE_RESULT inline MaybeObject* CopyFixedArray(FixedArray* src);
1015 // Make a copy of src and return it. Returns
1016 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1017 MUST_USE_RESULT MaybeObject* CopyAndTenureFixedCOWArray(FixedArray* src);
1019 // Make a copy of src, set the map, and return the copy. Returns
1020 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1021 MUST_USE_RESULT MaybeObject* CopyFixedArrayWithMap(FixedArray* src, Map* map);
1023 // Make a copy of src and return it. Returns
1024 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1025 MUST_USE_RESULT inline MaybeObject* CopyFixedDoubleArray(
1026 FixedDoubleArray* src);
1028 // Make a copy of src, set the map, and return the copy. Returns
1029 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1030 MUST_USE_RESULT MaybeObject* CopyFixedDoubleArrayWithMap(
1031 FixedDoubleArray* src, Map* map);
1033 // Make a copy of src and return it. Returns
1034 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1035 MUST_USE_RESULT inline MaybeObject* CopyConstantPoolArray(
1036 ConstantPoolArray* src);
1038 // Make a copy of src, set the map, and return the copy. Returns
1039 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1040 MUST_USE_RESULT MaybeObject* CopyConstantPoolArrayWithMap(
1041 ConstantPoolArray* src, Map* map);
1043 // Allocates a fixed array initialized with the hole values.
1044 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1046 // Please note this does not perform a garbage collection.
1047 MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithHoles(
1049 PretenureFlag pretenure = NOT_TENURED);
1051 MUST_USE_RESULT MaybeObject* AllocateConstantPoolArray(
1052 int number_of_int64_entries,
1053 int number_of_code_ptr_entries,
1054 int number_of_heap_ptr_entries,
1055 int number_of_int32_entries);
1057 // Allocates a fixed double array with uninitialized values. Returns
1058 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1059 // Please note this does not perform a garbage collection.
1060 MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedDoubleArray(
1062 PretenureFlag pretenure = NOT_TENURED);
1064 // Allocates a fixed double array with hole values. Returns
1065 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1066 // Please note this does not perform a garbage collection.
1067 MUST_USE_RESULT MaybeObject* AllocateFixedDoubleArrayWithHoles(
1069 PretenureFlag pretenure = NOT_TENURED);
1071 // AllocateHashTable is identical to AllocateFixedArray except
1072 // that the resulting object has hash_table_map as map.
1073 MUST_USE_RESULT MaybeObject* AllocateHashTable(
1074 int length, PretenureFlag pretenure = NOT_TENURED);
1076 // Allocate a native (but otherwise uninitialized) context.
1077 MUST_USE_RESULT MaybeObject* AllocateNativeContext();
1079 // Allocate a global context.
1080 MUST_USE_RESULT MaybeObject* AllocateGlobalContext(JSFunction* function,
1081 ScopeInfo* scope_info);
1083 // Allocate a module context.
1084 MUST_USE_RESULT MaybeObject* AllocateModuleContext(ScopeInfo* scope_info);
1086 // Allocate a function context.
1087 MUST_USE_RESULT MaybeObject* AllocateFunctionContext(int length,
1088 JSFunction* function);
1090 // Allocate a catch context.
1091 MUST_USE_RESULT MaybeObject* AllocateCatchContext(JSFunction* function,
1094 Object* thrown_object);
1095 // Allocate a 'with' context.
1096 MUST_USE_RESULT MaybeObject* AllocateWithContext(JSFunction* function,
1098 JSReceiver* extension);
1100 // Allocate a block context.
1101 MUST_USE_RESULT MaybeObject* AllocateBlockContext(JSFunction* function,
1105 // Allocates a new utility object in the old generation.
1106 MUST_USE_RESULT MaybeObject* AllocateStruct(InstanceType type);
1108 // Allocates a function initialized with a shared part.
1109 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1111 // Please note this does not perform a garbage collection.
1112 MUST_USE_RESULT MaybeObject* AllocateFunction(
1114 SharedFunctionInfo* shared,
1116 PretenureFlag pretenure = TENURED);
1118 // Sloppy mode arguments object size.
1119 static const int kSloppyArgumentsObjectSize =
1120 JSObject::kHeaderSize + 2 * kPointerSize;
1121 // Strict mode arguments has no callee so it is smaller.
1122 static const int kStrictArgumentsObjectSize =
1123 JSObject::kHeaderSize + 1 * kPointerSize;
1124 // Indicies for direct access into argument objects.
1125 static const int kArgumentsLengthIndex = 0;
1126 // callee is only valid in sloppy mode.
1127 static const int kArgumentsCalleeIndex = 1;
1129 // Allocates an arguments object - optionally with an elements array.
1130 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1132 // Please note this does not perform a garbage collection.
1133 MUST_USE_RESULT MaybeObject* AllocateArgumentsObject(
1134 Object* callee, int length);
1136 // Same as NewNumberFromDouble, but may return a preallocated/immutable
1137 // number object (e.g., minus_zero_value_, nan_value_)
1138 MUST_USE_RESULT MaybeObject* NumberFromDouble(
1139 double value, PretenureFlag pretenure = NOT_TENURED);
1141 // Allocated a HeapNumber from value.
1142 MUST_USE_RESULT MaybeObject* AllocateHeapNumber(
1143 double value, PretenureFlag pretenure = NOT_TENURED);
1145 // Allocated a Float32x4 from value.
1146 MUST_USE_RESULT MaybeObject* AllocateFloat32x4(
1147 float32x4_value_t value,
1148 PretenureFlag pretenure = NOT_TENURED);
1150 // Allocated a Int32x4 from value.
1151 MUST_USE_RESULT MaybeObject* AllocateInt32x4(
1152 int32x4_value_t value,
1153 PretenureFlag pretenure = NOT_TENURED);
1155 // Converts an int into either a Smi or a HeapNumber object.
1156 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1158 // Please note this does not perform a garbage collection.
1159 MUST_USE_RESULT inline MaybeObject* NumberFromInt32(
1160 int32_t value, PretenureFlag pretenure = NOT_TENURED);
1162 // Converts an int into either a Smi or a HeapNumber object.
1163 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1165 // Please note this does not perform a garbage collection.
1166 MUST_USE_RESULT inline MaybeObject* NumberFromUint32(
1167 uint32_t value, PretenureFlag pretenure = NOT_TENURED);
1169 // Allocates a new foreign object.
1170 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1172 // Please note this does not perform a garbage collection.
1173 MUST_USE_RESULT MaybeObject* AllocateForeign(
1174 Address address, PretenureFlag pretenure = NOT_TENURED);
1176 // Allocates a new SharedFunctionInfo object.
1177 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1179 // Please note this does not perform a garbage collection.
1180 MUST_USE_RESULT MaybeObject* AllocateSharedFunctionInfo(Object* name);
1182 // Allocates a new JSMessageObject object.
1183 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1185 // Please note that this does not perform a garbage collection.
1186 MUST_USE_RESULT MaybeObject* AllocateJSMessageObject(
1192 Object* stack_frames);
1194 // Allocate a new external string object, which is backed by a string
1195 // resource that resides outside the V8 heap.
1196 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1198 // Please note this does not perform a garbage collection.
1199 MUST_USE_RESULT MaybeObject* AllocateExternalStringFromAscii(
1200 const ExternalAsciiString::Resource* resource);
1201 MUST_USE_RESULT MaybeObject* AllocateExternalStringFromTwoByte(
1202 const ExternalTwoByteString::Resource* resource);
1204 // Finalizes an external string by deleting the associated external
1205 // data and clearing the resource pointer.
1206 inline void FinalizeExternalString(String* string);
1208 // Allocates an uninitialized object. The memory is non-executable if the
1209 // hardware and OS allow.
1210 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1212 // Please note this function does not perform a garbage collection.
1213 MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes,
1214 AllocationSpace space,
1215 AllocationSpace retry_space);
1217 // Initialize a filler object to keep the ability to iterate over the heap
1218 // when shortening objects.
1219 void CreateFillerObjectAt(Address addr, int size);
1221 bool CanMoveObjectStart(HeapObject* object);
1223 enum InvocationMode { FROM_GC, FROM_MUTATOR };
1225 // Maintain marking consistency for IncrementalMarking.
1226 void AdjustLiveBytes(Address address, int by, InvocationMode mode);
1228 // Makes a new native code object
1229 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1230 // failed. On success, the pointer to the Code object is stored in the
1231 // self_reference. This allows generated code to reference its own Code
1232 // object by containing this pointer.
1233 // Please note this function does not perform a garbage collection.
1234 MUST_USE_RESULT MaybeObject* CreateCode(
1235 const CodeDesc& desc,
1237 Handle<Object> self_reference,
1238 bool immovable = false,
1239 bool crankshafted = false,
1240 int prologue_offset = Code::kPrologueOffsetNotSet);
1242 MUST_USE_RESULT MaybeObject* CopyCode(Code* code);
1244 // Copy the code and scope info part of the code object, but insert
1245 // the provided data as the relocation information.
1246 MUST_USE_RESULT MaybeObject* CopyCode(Code* code, Vector<byte> reloc_info);
1248 // Finds the internalized copy for string in the string table.
1249 // If not found, a new string is added to the table and returned.
1250 // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
1252 // Please note this function does not perform a garbage collection.
1253 MUST_USE_RESULT MaybeObject* InternalizeUtf8String(const char* str) {
1254 return InternalizeUtf8String(CStrVector(str));
1256 MUST_USE_RESULT MaybeObject* InternalizeUtf8String(Vector<const char> str);
1258 MUST_USE_RESULT MaybeObject* InternalizeString(String* str);
1259 MUST_USE_RESULT MaybeObject* InternalizeStringWithKey(HashTableKey* key);
1261 bool InternalizeStringIfExists(String* str, String** result);
1262 bool InternalizeTwoCharsStringIfExists(String* str, String** result);
1264 // Compute the matching internalized string map for a string if possible.
1265 // NULL is returned if string is in new space or not flattened.
1266 Map* InternalizedStringMapForString(String* str);
1268 // Tries to flatten a string before compare operation.
1270 // Returns a failure in case it was decided that flattening was
1271 // necessary and failed. Note, if flattening is not necessary the
1272 // string might stay non-flat even when not a failure is returned.
1274 // Please note this function does not perform a garbage collection.
1275 MUST_USE_RESULT inline MaybeObject* PrepareForCompare(String* str);
1277 // Converts the given boolean condition to JavaScript boolean value.
1278 inline Object* ToBoolean(bool condition);
1280 // Performs garbage collection operation.
1281 // Returns whether there is a chance that another major GC could
1282 // collect more garbage.
1283 inline bool CollectGarbage(
1284 AllocationSpace space,
1285 const char* gc_reason = NULL,
1286 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1288 static const int kNoGCFlags = 0;
1289 static const int kSweepPreciselyMask = 1;
1290 static const int kReduceMemoryFootprintMask = 2;
1291 static const int kAbortIncrementalMarkingMask = 4;
1293 // Making the heap iterable requires us to sweep precisely and abort any
1294 // incremental marking as well.
1295 static const int kMakeHeapIterableMask =
1296 kSweepPreciselyMask | kAbortIncrementalMarkingMask;
1298 // Performs a full garbage collection. If (flags & kMakeHeapIterableMask) is
1299 // non-zero, then the slower precise sweeper is used, which leaves the heap
1300 // in a state where we can iterate over the heap visiting all objects.
1301 void CollectAllGarbage(
1303 const char* gc_reason = NULL,
1304 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1306 // Last hope GC, should try to squeeze as much as possible.
1307 void CollectAllAvailableGarbage(const char* gc_reason = NULL);
1309 // Check whether the heap is currently iterable.
1310 bool IsHeapIterable();
1312 // Ensure that we have swept all spaces in such a way that we can iterate
1313 // over all objects. May cause a GC.
1314 void EnsureHeapIsIterable();
1316 // Notify the heap that a context has been disposed.
1317 int NotifyContextDisposed();
1319 inline void increment_scan_on_scavenge_pages() {
1320 scan_on_scavenge_pages_++;
1321 if (FLAG_gc_verbose) {
1322 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1326 inline void decrement_scan_on_scavenge_pages() {
1327 scan_on_scavenge_pages_--;
1328 if (FLAG_gc_verbose) {
1329 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1333 PromotionQueue* promotion_queue() { return &promotion_queue_; }
1336 // Utility used with flag gc-greedy.
1337 void GarbageCollectionGreedyCheck();
1340 void AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
1341 GCType gc_type_filter,
1342 bool pass_isolate = true);
1343 void RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback);
1345 void AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
1346 GCType gc_type_filter,
1347 bool pass_isolate = true);
1348 void RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback);
1350 // Heap root getters. We have versions with and without type::cast() here.
1351 // You can't use type::cast during GC because the assert fails.
1352 // TODO(1490): Try removing the unchecked accessors, now that GC marking does
1353 // not corrupt the map.
1354 #define ROOT_ACCESSOR(type, name, camel_name) \
1356 return type::cast(roots_[k##camel_name##RootIndex]); \
1358 type* raw_unchecked_##name() { \
1359 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
1361 ROOT_LIST(ROOT_ACCESSOR)
1362 #undef ROOT_ACCESSOR
1364 // Utility type maps
1365 #define STRUCT_MAP_ACCESSOR(NAME, Name, name) \
1366 Map* name##_map() { \
1367 return Map::cast(roots_[k##Name##MapRootIndex]); \
1369 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
1370 #undef STRUCT_MAP_ACCESSOR
1372 #define STRING_ACCESSOR(name, str) String* name() { \
1373 return String::cast(roots_[k##name##RootIndex]); \
1375 INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
1376 #undef STRING_ACCESSOR
1378 // The hidden_string is special because it is the empty string, but does
1379 // not match the empty string.
1380 String* hidden_string() { return hidden_string_; }
1382 void set_native_contexts_list(Object* object) {
1383 native_contexts_list_ = object;
1385 Object* native_contexts_list() { return native_contexts_list_; }
1387 void set_array_buffers_list(Object* object) {
1388 array_buffers_list_ = object;
1390 Object* array_buffers_list() { return array_buffers_list_; }
1392 void set_allocation_sites_list(Object* object) {
1393 allocation_sites_list_ = object;
1395 Object* allocation_sites_list() { return allocation_sites_list_; }
1396 Object** allocation_sites_list_address() { return &allocation_sites_list_; }
1398 Object* weak_object_to_code_table() { return weak_object_to_code_table_; }
1400 // Number of mark-sweeps.
1401 unsigned int ms_count() { return ms_count_; }
1403 // Iterates over all roots in the heap.
1404 void IterateRoots(ObjectVisitor* v, VisitMode mode);
1405 // Iterates over all strong roots in the heap.
1406 void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
1407 // Iterates over entries in the smi roots list. Only interesting to the
1408 // serializer/deserializer, since GC does not care about smis.
1409 void IterateSmiRoots(ObjectVisitor* v);
1410 // Iterates over all the other roots in the heap.
1411 void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
1413 // Iterate pointers to from semispace of new space found in memory interval
1414 // from start to end.
1415 void IterateAndMarkPointersToFromSpace(Address start,
1417 ObjectSlotCallback callback);
1419 // Returns whether the object resides in new space.
1420 inline bool InNewSpace(Object* object);
1421 inline bool InNewSpace(Address address);
1422 inline bool InNewSpacePage(Address address);
1423 inline bool InFromSpace(Object* object);
1424 inline bool InToSpace(Object* object);
1426 // Returns whether the object resides in old pointer space.
1427 inline bool InOldPointerSpace(Address address);
1428 inline bool InOldPointerSpace(Object* object);
1430 // Returns whether the object resides in old data space.
1431 inline bool InOldDataSpace(Address address);
1432 inline bool InOldDataSpace(Object* object);
1434 // Checks whether an address/object in the heap (including auxiliary
1435 // area and unused area).
1436 bool Contains(Address addr);
1437 bool Contains(HeapObject* value);
1439 // Checks whether an address/object in a space.
1440 // Currently used by tests, serialization and heap verification only.
1441 bool InSpace(Address addr, AllocationSpace space);
1442 bool InSpace(HeapObject* value, AllocationSpace space);
1444 // Finds out which space an object should get promoted to based on its type.
1445 inline OldSpace* TargetSpace(HeapObject* object);
1446 static inline AllocationSpace TargetSpaceId(InstanceType type);
1448 // Checks whether the given object is allowed to be migrated from it's
1449 // current space into the given destination space. Used for debugging.
1450 inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
1452 // Sets the stub_cache_ (only used when expanding the dictionary).
1453 void public_set_code_stubs(UnseededNumberDictionary* value) {
1454 roots_[kCodeStubsRootIndex] = value;
1457 // Support for computing object sizes for old objects during GCs. Returns
1458 // a function that is guaranteed to be safe for computing object sizes in
1459 // the current GC phase.
1460 HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
1461 return gc_safe_size_of_old_object_;
1464 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
1465 void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
1466 roots_[kNonMonomorphicCacheRootIndex] = value;
1469 void public_set_empty_script(Script* script) {
1470 roots_[kEmptyScriptRootIndex] = script;
1473 void public_set_store_buffer_top(Address* top) {
1474 roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1477 void public_set_materialized_objects(FixedArray* objects) {
1478 roots_[kMaterializedObjectsRootIndex] = objects;
1481 // Generated code can embed this address to get access to the roots.
1482 Object** roots_array_start() { return roots_; }
1484 Address* store_buffer_top_address() {
1485 return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1488 // Get address of native contexts list for serialization support.
1489 Object** native_contexts_list_address() {
1490 return &native_contexts_list_;
1494 // Verify the heap is in its normal state before or after a GC.
1498 bool weak_embedded_objects_verification_enabled() {
1499 return no_weak_object_verification_scope_depth_ == 0;
1505 void PrintHandles();
1507 void OldPointerSpaceCheckStoreBuffer();
1508 void MapSpaceCheckStoreBuffer();
1509 void LargeObjectSpaceCheckStoreBuffer();
1511 // Report heap statistics.
1512 void ReportHeapStatistics(const char* title);
1513 void ReportCodeStatistics(const char* title);
1516 // Zapping is needed for verify heap, and always done in debug builds.
1517 static inline bool ShouldZapGarbage() {
1522 return FLAG_verify_heap;
1529 // Print short heap statistics.
1530 void PrintShortHeapStatistics();
1532 // Write barrier support for address[offset] = o.
1533 INLINE(void RecordWrite(Address address, int offset));
1535 // Write barrier support for address[start : start + len[ = o.
1536 INLINE(void RecordWrites(Address address, int start, int len));
1538 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1539 inline HeapState gc_state() { return gc_state_; }
1541 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1544 void set_allocation_timeout(int timeout) {
1545 allocation_timeout_ = timeout;
1548 void TracePathToObjectFrom(Object* target, Object* root);
1549 void TracePathToObject(Object* target);
1550 void TracePathToGlobal();
1553 // Callback function passed to Heap::Iterate etc. Copies an object if
1554 // necessary, the object might be promoted to an old space. The caller must
1555 // ensure the precondition that the object is (a) a heap object and (b) in
1556 // the heap's from space.
1557 static inline void ScavengePointer(HeapObject** p);
1558 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1560 enum ScratchpadSlotMode {
1561 IGNORE_SCRATCHPAD_SLOT,
1562 RECORD_SCRATCHPAD_SLOT
1565 // An object may have an AllocationSite associated with it through a trailing
1566 // AllocationMemento. Its feedback should be updated when objects are found
1568 static inline void UpdateAllocationSiteFeedback(
1569 HeapObject* object, ScratchpadSlotMode mode);
1571 // Support for partial snapshots. After calling this we have a linear
1572 // space to write objects in each space.
1573 void ReserveSpace(int *sizes, Address* addresses);
1576 // Support for the API.
1579 bool CreateApiObjects();
1581 // Attempt to find the number in a small cache. If we finds it, return
1582 // the string representation of the number. Otherwise return undefined.
1583 Object* GetNumberStringCache(Object* number);
1585 // Update the cache with a new number-string pair.
1586 void SetNumberStringCache(Object* number, String* str);
1588 // Adjusts the amount of registered external memory.
1589 // Returns the adjusted value.
1590 inline int64_t AdjustAmountOfExternalAllocatedMemory(
1591 int64_t change_in_bytes);
1593 // This is only needed for testing high promotion mode.
1594 void SetNewSpaceHighPromotionModeActive(bool mode) {
1595 new_space_high_promotion_mode_active_ = mode;
1598 // Returns the allocation mode (pre-tenuring) based on observed promotion
1599 // rates of previous collections.
1600 inline PretenureFlag GetPretenureMode() {
1601 return FLAG_pretenuring && new_space_high_promotion_mode_active_
1602 ? TENURED : NOT_TENURED;
1605 inline Address* NewSpaceHighPromotionModeActiveAddress() {
1606 return reinterpret_cast<Address*>(&new_space_high_promotion_mode_active_);
1609 inline intptr_t PromotedTotalSize() {
1610 int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1611 if (total > kMaxInt) return static_cast<intptr_t>(kMaxInt);
1612 if (total < 0) return 0;
1613 return static_cast<intptr_t>(total);
1616 inline intptr_t OldGenerationSpaceAvailable() {
1617 return old_generation_allocation_limit_ - PromotedTotalSize();
1620 inline intptr_t OldGenerationCapacityAvailable() {
1621 return max_old_generation_size_ - PromotedTotalSize();
1624 static const intptr_t kMinimumOldGenerationAllocationLimit =
1625 8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1627 intptr_t OldGenerationAllocationLimit(intptr_t old_gen_size) {
1628 const int divisor = FLAG_stress_compaction ? 10 : 1;
1630 Max(old_gen_size + old_gen_size / divisor,
1631 kMinimumOldGenerationAllocationLimit);
1632 limit += new_space_.Capacity();
1633 intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1634 return Min(limit, halfway_to_the_max);
1637 // Indicates whether inline bump-pointer allocation has been disabled.
1638 bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1640 // Switch whether inline bump-pointer allocation should be used.
1641 void EnableInlineAllocation();
1642 void DisableInlineAllocation();
1644 // Implements the corresponding V8 API function.
1645 bool IdleNotification(int hint);
1647 // Declare all the root indices. This defines the root list order.
1648 enum RootListIndex {
1649 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1650 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1651 #undef ROOT_INDEX_DECLARATION
1653 #define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
1654 INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
1655 #undef STRING_DECLARATION
1657 // Utility type maps
1658 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1659 STRUCT_LIST(DECLARE_STRUCT_MAP)
1660 #undef DECLARE_STRUCT_MAP
1662 kStringTableRootIndex,
1664 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1665 SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
1666 #undef ROOT_INDEX_DECLARATION
1669 kStrongRootListLength = kStringTableRootIndex,
1670 kSmiRootsStart = kStringTableRootIndex + 1
1673 STATIC_CHECK(kUndefinedValueRootIndex == Internals::kUndefinedValueRootIndex);
1674 STATIC_CHECK(kNullValueRootIndex == Internals::kNullValueRootIndex);
1675 STATIC_CHECK(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1676 STATIC_CHECK(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1677 STATIC_CHECK(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
1679 // Generated code can embed direct references to non-writable roots if
1680 // they are in new space.
1681 static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
1682 // Generated code can treat direct references to this root as constant.
1683 bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1685 MUST_USE_RESULT MaybeObject* NumberToString(
1686 Object* number, bool check_number_string_cache = true);
1687 MUST_USE_RESULT MaybeObject* Uint32ToString(
1688 uint32_t value, bool check_number_string_cache = true);
1690 Map* MapForFixedTypedArray(ExternalArrayType array_type);
1691 RootListIndex RootIndexForFixedTypedArray(
1692 ExternalArrayType array_type);
1694 Map* MapForExternalArrayType(ExternalArrayType array_type);
1695 RootListIndex RootIndexForExternalArrayType(
1696 ExternalArrayType array_type);
1698 RootListIndex RootIndexForEmptyExternalArray(ElementsKind kind);
1699 RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1700 ExternalArray* EmptyExternalArrayForMap(Map* map);
1701 FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1703 void RecordStats(HeapStats* stats, bool take_snapshot = false);
1705 // Copy block of memory from src to dst. Size of block should be aligned
1707 static inline void CopyBlock(Address dst, Address src, int byte_size);
1709 // Optimized version of memmove for blocks with pointer size aligned sizes and
1710 // pointer size aligned addresses.
1711 static inline void MoveBlock(Address dst, Address src, int byte_size);
1713 // Check new space expansion criteria and expand semispaces if it was hit.
1714 void CheckNewSpaceExpansionCriteria();
1716 inline void IncrementYoungSurvivorsCounter(int survived) {
1717 ASSERT(survived >= 0);
1718 young_survivors_after_last_gc_ = survived;
1719 survived_since_last_expansion_ += survived;
1722 inline bool NextGCIsLikelyToBeFull() {
1723 if (FLAG_gc_global) return true;
1725 if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1727 intptr_t adjusted_allocation_limit =
1728 old_generation_allocation_limit_ - new_space_.Capacity();
1730 if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
1735 void UpdateNewSpaceReferencesInExternalStringTable(
1736 ExternalStringTableUpdaterCallback updater_func);
1738 void UpdateReferencesInExternalStringTable(
1739 ExternalStringTableUpdaterCallback updater_func);
1741 void ProcessWeakReferences(WeakObjectRetainer* retainer);
1743 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1745 // Helper function that governs the promotion policy from new space to
1746 // old. If the object's old address lies below the new space's age
1747 // mark or if we've already filled the bottom 1/16th of the to space,
1748 // we try to promote this object.
1749 inline bool ShouldBePromoted(Address old_address, int object_size);
1751 void ClearJSFunctionResultCaches();
1753 void ClearNormalizedMapCaches();
1755 GCTracer* tracer() { return tracer_; }
1757 // Returns the size of objects residing in non new spaces.
1758 intptr_t PromotedSpaceSizeOfObjects();
1760 double total_regexp_code_generated() { return total_regexp_code_generated_; }
1761 void IncreaseTotalRegexpCodeGenerated(int size) {
1762 total_regexp_code_generated_ += size;
1765 void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1766 if (is_crankshafted) {
1767 crankshaft_codegen_bytes_generated_ += size;
1769 full_codegen_bytes_generated_ += size;
1773 // Returns maximum GC pause.
1774 double get_max_gc_pause() { return max_gc_pause_; }
1776 // Returns maximum size of objects alive after GC.
1777 intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1779 // Returns minimal interval between two subsequent collections.
1780 double get_min_in_mutator() { return min_in_mutator_; }
1782 // TODO(hpayer): remove, should be handled by GCTracer
1783 void AddMarkingTime(double marking_time) {
1784 marking_time_ += marking_time;
1787 double marking_time() const {
1788 return marking_time_;
1791 // TODO(hpayer): remove, should be handled by GCTracer
1792 void AddSweepingTime(double sweeping_time) {
1793 sweeping_time_ += sweeping_time;
1796 double sweeping_time() const {
1797 return sweeping_time_;
1800 MarkCompactCollector* mark_compact_collector() {
1801 return &mark_compact_collector_;
1804 StoreBuffer* store_buffer() {
1805 return &store_buffer_;
1808 Marking* marking() {
1812 IncrementalMarking* incremental_marking() {
1813 return &incremental_marking_;
1816 bool IsSweepingComplete() {
1817 return !mark_compact_collector()->IsConcurrentSweepingInProgress() &&
1818 old_data_space()->IsLazySweepingComplete() &&
1819 old_pointer_space()->IsLazySweepingComplete();
1822 bool AdvanceSweepers(int step_size);
1824 bool EnsureSweepersProgressed(int step_size) {
1825 bool sweeping_complete = old_data_space()->EnsureSweeperProgress(step_size);
1826 sweeping_complete &= old_pointer_space()->EnsureSweeperProgress(step_size);
1827 return sweeping_complete;
1830 ExternalStringTable* external_string_table() {
1831 return &external_string_table_;
1834 // Returns the current sweep generation.
1835 int sweep_generation() {
1836 return sweep_generation_;
1839 inline Isolate* isolate();
1841 void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1842 void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1844 inline bool OldGenerationAllocationLimitReached();
1846 inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1847 scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1850 void QueueMemoryChunkForFree(MemoryChunk* chunk);
1851 void FreeQueuedChunks();
1853 int gc_count() const { return gc_count_; }
1855 // Completely clear the Instanceof cache (to stop it keeping objects alive
1857 inline void CompletelyClearInstanceofCache();
1859 // The roots that have an index less than this are always in old space.
1860 static const int kOldSpaceRoots = 0x20;
1862 uint32_t HashSeed() {
1863 uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1864 ASSERT(FLAG_randomize_hashes || seed == 0);
1868 void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1869 ASSERT(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1870 set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1873 void SetConstructStubDeoptPCOffset(int pc_offset) {
1874 ASSERT(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1875 set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1878 void SetGetterStubDeoptPCOffset(int pc_offset) {
1879 ASSERT(getter_stub_deopt_pc_offset() == Smi::FromInt(0));
1880 set_getter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1883 void SetSetterStubDeoptPCOffset(int pc_offset) {
1884 ASSERT(setter_stub_deopt_pc_offset() == Smi::FromInt(0));
1885 set_setter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1888 // For post mortem debugging.
1889 void RememberUnmappedPage(Address page, bool compacted);
1891 // Global inline caching age: it is incremented on some GCs after context
1892 // disposal. We use it to flush inline caches.
1893 int global_ic_age() {
1894 return global_ic_age_;
1897 void AgeInlineCaches() {
1898 global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
1901 bool flush_monomorphic_ics() { return flush_monomorphic_ics_; }
1903 int64_t amount_of_external_allocated_memory() {
1904 return amount_of_external_allocated_memory_;
1907 void DeoptMarkedAllocationSites();
1909 // ObjectStats are kept in two arrays, counts and sizes. Related stats are
1910 // stored in a contiguous linear buffer. Stats groups are stored one after
1913 FIRST_CODE_KIND_SUB_TYPE = LAST_TYPE + 1,
1914 FIRST_FIXED_ARRAY_SUB_TYPE =
1915 FIRST_CODE_KIND_SUB_TYPE + Code::NUMBER_OF_KINDS,
1916 FIRST_CODE_AGE_SUB_TYPE =
1917 FIRST_FIXED_ARRAY_SUB_TYPE + LAST_FIXED_ARRAY_SUB_TYPE + 1,
1918 OBJECT_STATS_COUNT = FIRST_CODE_AGE_SUB_TYPE + Code::kCodeAgeCount + 1
1921 void RecordObjectStats(InstanceType type, size_t size) {
1922 ASSERT(type <= LAST_TYPE);
1923 object_counts_[type]++;
1924 object_sizes_[type] += size;
1927 void RecordCodeSubTypeStats(int code_sub_type, int code_age, size_t size) {
1928 int code_sub_type_index = FIRST_CODE_KIND_SUB_TYPE + code_sub_type;
1929 int code_age_index =
1930 FIRST_CODE_AGE_SUB_TYPE + code_age - Code::kFirstCodeAge;
1931 ASSERT(code_sub_type_index >= FIRST_CODE_KIND_SUB_TYPE &&
1932 code_sub_type_index < FIRST_CODE_AGE_SUB_TYPE);
1933 ASSERT(code_age_index >= FIRST_CODE_AGE_SUB_TYPE &&
1934 code_age_index < OBJECT_STATS_COUNT);
1935 object_counts_[code_sub_type_index]++;
1936 object_sizes_[code_sub_type_index] += size;
1937 object_counts_[code_age_index]++;
1938 object_sizes_[code_age_index] += size;
1941 void RecordFixedArraySubTypeStats(int array_sub_type, size_t size) {
1942 ASSERT(array_sub_type <= LAST_FIXED_ARRAY_SUB_TYPE);
1943 object_counts_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type]++;
1944 object_sizes_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type] += size;
1947 void CheckpointObjectStats();
1949 // We don't use a LockGuard here since we want to lock the heap
1950 // only when FLAG_concurrent_recompilation is true.
1951 class RelocationLock {
1953 explicit RelocationLock(Heap* heap) : heap_(heap) {
1954 heap_->relocation_mutex_.Lock();
1959 heap_->relocation_mutex_.Unlock();
1966 MaybeObject* AddWeakObjectToCodeDependency(Object* obj, DependentCode* dep);
1968 DependentCode* LookupWeakObjectToCodeDependency(Object* obj);
1970 void InitializeWeakObjectToCodeTable() {
1971 set_weak_object_to_code_table(undefined_value());
1974 void EnsureWeakObjectToCodeTable();
1976 static void FatalProcessOutOfMemory(const char* location,
1977 bool take_snapshot = false);
1982 // This can be calculated directly from a pointer to the heap; however, it is
1983 // more expedient to get at the isolate directly from within Heap methods.
1986 Object* roots_[kRootListLength];
1988 intptr_t code_range_size_;
1989 int reserved_semispace_size_;
1990 int max_semispace_size_;
1991 int initial_semispace_size_;
1992 intptr_t max_old_generation_size_;
1993 intptr_t max_executable_size_;
1994 intptr_t maximum_committed_;
1996 // For keeping track of how much data has survived
1997 // scavenge since last new space expansion.
1998 int survived_since_last_expansion_;
2000 // For keeping track on when to flush RegExp code.
2001 int sweep_generation_;
2003 int always_allocate_scope_depth_;
2004 int linear_allocation_scope_depth_;
2006 // For keeping track of context disposals.
2007 int contexts_disposed_;
2011 bool flush_monomorphic_ics_;
2013 int scan_on_scavenge_pages_;
2015 NewSpace new_space_;
2016 OldSpace* old_pointer_space_;
2017 OldSpace* old_data_space_;
2018 OldSpace* code_space_;
2019 MapSpace* map_space_;
2020 CellSpace* cell_space_;
2021 PropertyCellSpace* property_cell_space_;
2022 LargeObjectSpace* lo_space_;
2023 HeapState gc_state_;
2024 int gc_post_processing_depth_;
2026 // Returns the amount of external memory registered since last global gc.
2027 int64_t PromotedExternalMemorySize();
2029 unsigned int ms_count_; // how many mark-sweep collections happened
2030 unsigned int gc_count_; // how many gc happened
2032 // For post mortem debugging.
2033 static const int kRememberedUnmappedPages = 128;
2034 int remembered_unmapped_pages_index_;
2035 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
2037 // Total length of the strings we failed to flatten since the last GC.
2038 int unflattened_strings_length_;
2040 #define ROOT_ACCESSOR(type, name, camel_name) \
2041 inline void set_##name(type* value) { \
2042 /* The deserializer makes use of the fact that these common roots are */ \
2043 /* never in new space and never on a page that is being compacted. */ \
2044 ASSERT(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value)); \
2045 roots_[k##camel_name##RootIndex] = value; \
2047 ROOT_LIST(ROOT_ACCESSOR)
2048 #undef ROOT_ACCESSOR
2051 // If the --gc-interval flag is set to a positive value, this
2052 // variable holds the value indicating the number of allocations
2053 // remain until the next failure and garbage collection.
2054 int allocation_timeout_;
2057 // Indicates that the new space should be kept small due to high promotion
2058 // rates caused by the mutator allocating a lot of long-lived objects.
2059 // TODO(hpayer): change to bool if no longer accessed from generated code
2060 intptr_t new_space_high_promotion_mode_active_;
2062 // Limit that triggers a global GC on the next (normally caused) GC. This
2063 // is checked when we have already decided to do a GC to help determine
2064 // which collector to invoke, before expanding a paged space in the old
2065 // generation and on every allocation in large object space.
2066 intptr_t old_generation_allocation_limit_;
2068 // Used to adjust the limits that control the timing of the next GC.
2069 intptr_t size_of_old_gen_at_last_old_space_gc_;
2071 // Limit on the amount of externally allocated memory allowed
2072 // between global GCs. If reached a global GC is forced.
2073 intptr_t external_allocation_limit_;
2075 // The amount of external memory registered through the API kept alive
2076 // by global handles
2077 int64_t amount_of_external_allocated_memory_;
2079 // Caches the amount of external memory registered at the last global gc.
2080 int64_t amount_of_external_allocated_memory_at_last_global_gc_;
2082 // Indicates that an allocation has failed in the old generation since the
2084 bool old_gen_exhausted_;
2086 // Indicates that inline bump-pointer allocation has been globally disabled
2087 // for all spaces. This is used to disable allocations in generated code.
2088 bool inline_allocation_disabled_;
2090 // Weak list heads, threaded through the objects.
2091 // List heads are initilized lazily and contain the undefined_value at start.
2092 Object* native_contexts_list_;
2093 Object* array_buffers_list_;
2094 Object* allocation_sites_list_;
2096 // WeakHashTable that maps objects embedded in optimized code to dependent
2097 // code list. It is initilized lazily and contains the undefined_value at
2099 Object* weak_object_to_code_table_;
2101 StoreBufferRebuilder store_buffer_rebuilder_;
2103 struct StringTypeTable {
2106 RootListIndex index;
2109 struct ConstantStringTable {
2110 const char* contents;
2111 RootListIndex index;
2114 struct StructTable {
2117 RootListIndex index;
2120 static const StringTypeTable string_type_table[];
2121 static const ConstantStringTable constant_string_table[];
2122 static const StructTable struct_table[];
2124 // The special hidden string which is an empty string, but does not match
2125 // any string when looked up in properties.
2126 String* hidden_string_;
2128 // GC callback function, called before and after mark-compact GC.
2129 // Allocations in the callback function are disallowed.
2130 struct GCPrologueCallbackPair {
2131 GCPrologueCallbackPair(v8::Isolate::GCPrologueCallback callback,
2134 : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
2136 bool operator==(const GCPrologueCallbackPair& pair) const {
2137 return pair.callback == callback;
2139 v8::Isolate::GCPrologueCallback callback;
2141 // TODO(dcarney): remove variable
2144 List<GCPrologueCallbackPair> gc_prologue_callbacks_;
2146 struct GCEpilogueCallbackPair {
2147 GCEpilogueCallbackPair(v8::Isolate::GCPrologueCallback callback,
2150 : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
2152 bool operator==(const GCEpilogueCallbackPair& pair) const {
2153 return pair.callback == callback;
2155 v8::Isolate::GCPrologueCallback callback;
2157 // TODO(dcarney): remove variable
2160 List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
2162 // Support for computing object sizes during GC.
2163 HeapObjectCallback gc_safe_size_of_old_object_;
2164 static int GcSafeSizeOfOldObject(HeapObject* object);
2166 // Update the GC state. Called from the mark-compact collector.
2167 void MarkMapPointersAsEncoded(bool encoded) {
2169 gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
2172 // Code that should be run before and after each GC. Includes some
2173 // reporting/verification activities when compiled with DEBUG set.
2174 void GarbageCollectionPrologue();
2175 void GarbageCollectionEpilogue();
2177 // Pretenuring decisions are made based on feedback collected during new
2178 // space evacuation. Note that between feedback collection and calling this
2179 // method object in old space must not move.
2180 // Right now we only process pretenuring feedback in high promotion mode.
2181 void ProcessPretenuringFeedback();
2183 // Checks whether a global GC is necessary
2184 GarbageCollector SelectGarbageCollector(AllocationSpace space,
2185 const char** reason);
2187 // Make sure there is a filler value behind the top of the new space
2188 // so that the GC does not confuse some unintialized/stale memory
2189 // with the allocation memento of the object at the top
2190 void EnsureFillerObjectAtTop();
2192 // Performs garbage collection operation.
2193 // Returns whether there is a chance that another major GC could
2194 // collect more garbage.
2195 bool CollectGarbage(
2196 GarbageCollector collector,
2197 const char* gc_reason,
2198 const char* collector_reason,
2199 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
2201 // Performs garbage collection
2202 // Returns whether there is a chance another major GC could
2203 // collect more garbage.
2204 bool PerformGarbageCollection(
2205 GarbageCollector collector,
2207 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
2209 inline void UpdateOldSpaceLimits();
2211 // Selects the proper allocation space depending on the given object
2212 // size, pretenuring decision, and preferred old-space.
2213 static AllocationSpace SelectSpace(int object_size,
2214 AllocationSpace preferred_old_space,
2215 PretenureFlag pretenure) {
2216 ASSERT(preferred_old_space == OLD_POINTER_SPACE ||
2217 preferred_old_space == OLD_DATA_SPACE);
2218 if (object_size > Page::kMaxRegularHeapObjectSize) return LO_SPACE;
2219 return (pretenure == TENURED) ? preferred_old_space : NEW_SPACE;
2222 // Allocate an uninitialized fixed array.
2223 MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(
2224 int length, PretenureFlag pretenure);
2226 // Allocate an uninitialized fixed double array.
2227 MUST_USE_RESULT MaybeObject* AllocateRawFixedDoubleArray(
2228 int length, PretenureFlag pretenure);
2230 // Allocate an initialized fixed array with the given filler value.
2231 MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithFiller(
2232 int length, PretenureFlag pretenure, Object* filler);
2234 // Initializes a JSObject based on its map.
2235 void InitializeJSObjectFromMap(JSObject* obj,
2236 FixedArray* properties,
2238 void InitializeAllocationMemento(AllocationMemento* memento,
2239 AllocationSite* allocation_site);
2241 bool CreateInitialMaps();
2242 bool CreateInitialObjects();
2244 // These five Create*EntryStub functions are here and forced to not be inlined
2245 // because of a gcc-4.4 bug that assigns wrong vtable entries.
2246 NO_INLINE(void CreateJSEntryStub());
2247 NO_INLINE(void CreateJSConstructEntryStub());
2249 void CreateFixedStubs();
2251 MUST_USE_RESULT MaybeObject* CreateOddball(const char* to_string,
2255 // Allocate a JSArray with no elements
2256 MUST_USE_RESULT MaybeObject* AllocateJSArray(
2257 ElementsKind elements_kind,
2258 PretenureFlag pretenure = NOT_TENURED);
2260 // Allocate empty fixed array.
2261 MUST_USE_RESULT MaybeObject* AllocateEmptyFixedArray();
2263 // Allocate empty external array of given type.
2264 MUST_USE_RESULT MaybeObject* AllocateEmptyExternalArray(
2265 ExternalArrayType array_type);
2267 // Allocate empty fixed typed array of given type.
2268 MUST_USE_RESULT MaybeObject* AllocateEmptyFixedTypedArray(
2269 ExternalArrayType array_type);
2271 // Allocate empty fixed double array.
2272 MUST_USE_RESULT MaybeObject* AllocateEmptyFixedDoubleArray();
2274 // Allocate empty constant pool array.
2275 MUST_USE_RESULT MaybeObject* AllocateEmptyConstantPoolArray();
2277 // Allocate a tenured simple cell.
2278 MUST_USE_RESULT MaybeObject* AllocateCell(Object* value);
2280 // Allocate a tenured JS global property cell initialized with the hole.
2281 MUST_USE_RESULT MaybeObject* AllocatePropertyCell();
2284 MUST_USE_RESULT MaybeObject* AllocateBox(Object* value,
2285 PretenureFlag pretenure);
2287 // Performs a minor collection in new generation.
2290 // Commits from space if it is uncommitted.
2291 void EnsureFromSpaceIsCommitted();
2293 // Uncommit unused semi space.
2294 bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
2296 // Fill in bogus values in from space
2297 void ZapFromSpace();
2299 static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
2303 Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
2304 static void ScavengeStoreBufferCallback(Heap* heap,
2306 StoreBufferEvent event);
2308 // Performs a major collection in the whole heap.
2309 void MarkCompact(GCTracer* tracer);
2311 // Code to be run before and after mark-compact.
2312 void MarkCompactPrologue();
2314 void ProcessNativeContexts(WeakObjectRetainer* retainer, bool record_slots);
2315 void ProcessArrayBuffers(WeakObjectRetainer* retainer, bool record_slots);
2316 void ProcessAllocationSites(WeakObjectRetainer* retainer, bool record_slots);
2318 // Deopts all code that contains allocation instruction which are tenured or
2319 // not tenured. Moreover it clears the pretenuring allocation site statistics.
2320 void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
2322 // Evaluates local pretenuring for the old space and calls
2323 // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
2325 void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
2327 // Called on heap tear-down.
2328 void TearDownArrayBuffers();
2330 // Record statistics before and after garbage collection.
2331 void ReportStatisticsBeforeGC();
2332 void ReportStatisticsAfterGC();
2334 // Slow part of scavenge object.
2335 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
2337 // Initializes a function with a shared part and prototype.
2338 // Note: this code was factored out of AllocateFunction such that
2339 // other parts of the VM could use it. Specifically, a function that creates
2340 // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
2341 // Please note this does not perform a garbage collection.
2342 inline void InitializeFunction(
2343 JSFunction* function,
2344 SharedFunctionInfo* shared,
2347 // Total RegExp code ever generated
2348 double total_regexp_code_generated_;
2352 // Allocates a small number to string cache.
2353 MUST_USE_RESULT MaybeObject* AllocateInitialNumberStringCache();
2354 // Creates and installs the full-sized number string cache.
2355 void AllocateFullSizeNumberStringCache();
2356 // Get the length of the number to string cache based on the max semispace
2358 int FullSizeNumberStringCacheLength();
2359 // Flush the number to string cache.
2360 void FlushNumberStringCache();
2362 // Allocates a fixed-size allocation sites scratchpad.
2363 MUST_USE_RESULT MaybeObject* AllocateAllocationSitesScratchpad();
2365 // Sets used allocation sites entries to undefined.
2366 void FlushAllocationSitesScratchpad();
2368 // Initializes the allocation sites scratchpad with undefined values.
2369 void InitializeAllocationSitesScratchpad();
2371 // Adds an allocation site to the scratchpad if there is space left.
2372 void AddAllocationSiteToScratchpad(AllocationSite* site,
2373 ScratchpadSlotMode mode);
2375 void UpdateSurvivalRateTrend(int start_new_space_size);
2377 enum SurvivalRateTrend { INCREASING, STABLE, DECREASING, FLUCTUATING };
2379 static const int kYoungSurvivalRateHighThreshold = 90;
2380 static const int kYoungSurvivalRateLowThreshold = 10;
2381 static const int kYoungSurvivalRateAllowedDeviation = 15;
2383 static const int kOldSurvivalRateLowThreshold = 20;
2385 int young_survivors_after_last_gc_;
2386 int high_survival_rate_period_length_;
2387 int low_survival_rate_period_length_;
2388 double survival_rate_;
2389 SurvivalRateTrend previous_survival_rate_trend_;
2390 SurvivalRateTrend survival_rate_trend_;
2392 void set_survival_rate_trend(SurvivalRateTrend survival_rate_trend) {
2393 ASSERT(survival_rate_trend != FLUCTUATING);
2394 previous_survival_rate_trend_ = survival_rate_trend_;
2395 survival_rate_trend_ = survival_rate_trend;
2398 SurvivalRateTrend survival_rate_trend() {
2399 if (survival_rate_trend_ == STABLE) {
2401 } else if (previous_survival_rate_trend_ == STABLE) {
2402 return survival_rate_trend_;
2403 } else if (survival_rate_trend_ != previous_survival_rate_trend_) {
2406 return survival_rate_trend_;
2410 bool IsStableOrIncreasingSurvivalTrend() {
2411 switch (survival_rate_trend()) {
2420 bool IsStableOrDecreasingSurvivalTrend() {
2421 switch (survival_rate_trend()) {
2430 bool IsIncreasingSurvivalTrend() {
2431 return survival_rate_trend() == INCREASING;
2434 bool IsHighSurvivalRate() {
2435 return high_survival_rate_period_length_ > 0;
2438 bool IsLowSurvivalRate() {
2439 return low_survival_rate_period_length_ > 0;
2442 void SelectScavengingVisitorsTable();
2444 void StartIdleRound() {
2445 mark_sweeps_since_idle_round_started_ = 0;
2448 void FinishIdleRound() {
2449 mark_sweeps_since_idle_round_started_ = kMaxMarkSweepsInIdleRound;
2450 scavenges_since_last_idle_round_ = 0;
2453 bool EnoughGarbageSinceLastIdleRound() {
2454 return (scavenges_since_last_idle_round_ >= kIdleScavengeThreshold);
2457 // Estimates how many milliseconds a Mark-Sweep would take to complete.
2458 // In idle notification handler we assume that this function will return:
2459 // - a number less than 10 for small heaps, which are less than 8Mb.
2460 // - a number greater than 10 for large heaps, which are greater than 32Mb.
2461 int TimeMarkSweepWouldTakeInMs() {
2462 // Rough estimate of how many megabytes of heap can be processed in 1 ms.
2463 static const int kMbPerMs = 2;
2465 int heap_size_mb = static_cast<int>(SizeOfObjects() / MB);
2466 return heap_size_mb / kMbPerMs;
2469 // Returns true if no more GC work is left.
2470 bool IdleGlobalGC();
2472 void AdvanceIdleIncrementalMarking(intptr_t step_size);
2474 void ClearObjectStats(bool clear_last_time_stats = false);
2476 void set_weak_object_to_code_table(Object* value) {
2477 ASSERT(!InNewSpace(value));
2478 weak_object_to_code_table_ = value;
2481 Object** weak_object_to_code_table_address() {
2482 return &weak_object_to_code_table_;
2485 static const int kInitialStringTableSize = 2048;
2486 static const int kInitialEvalCacheSize = 64;
2487 static const int kInitialNumberStringCacheSize = 256;
2489 // Object counts and used memory by InstanceType
2490 size_t object_counts_[OBJECT_STATS_COUNT];
2491 size_t object_counts_last_time_[OBJECT_STATS_COUNT];
2492 size_t object_sizes_[OBJECT_STATS_COUNT];
2493 size_t object_sizes_last_time_[OBJECT_STATS_COUNT];
2495 // Maximum GC pause.
2496 double max_gc_pause_;
2498 // Total time spent in GC.
2499 double total_gc_time_ms_;
2501 // Maximum size of objects alive after GC.
2502 intptr_t max_alive_after_gc_;
2504 // Minimal interval between two subsequent collections.
2505 double min_in_mutator_;
2507 // Size of objects alive after last GC.
2508 intptr_t alive_after_last_gc_;
2510 double last_gc_end_timestamp_;
2512 // Cumulative GC time spent in marking
2513 double marking_time_;
2515 // Cumulative GC time spent in sweeping
2516 double sweeping_time_;
2518 MarkCompactCollector mark_compact_collector_;
2520 StoreBuffer store_buffer_;
2524 IncrementalMarking incremental_marking_;
2526 int number_idle_notifications_;
2527 unsigned int last_idle_notification_gc_count_;
2528 bool last_idle_notification_gc_count_init_;
2530 int mark_sweeps_since_idle_round_started_;
2531 unsigned int gc_count_at_last_idle_gc_;
2532 int scavenges_since_last_idle_round_;
2534 // These two counters are monotomically increasing and never reset.
2535 size_t full_codegen_bytes_generated_;
2536 size_t crankshaft_codegen_bytes_generated_;
2538 // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2539 // this variable holds the number of garbage collections since the last
2540 // deoptimization triggered by garbage collection.
2541 int gcs_since_last_deopt_;
2544 int no_weak_object_verification_scope_depth_;
2547 static const int kAllocationSiteScratchpadSize = 256;
2548 int allocation_sites_scratchpad_length_;
2550 static const int kMaxMarkSweepsInIdleRound = 7;
2551 static const int kIdleScavengeThreshold = 5;
2553 // Shared state read by the scavenge collector and set by ScavengeObject.
2554 PromotionQueue promotion_queue_;
2556 // Flag is set when the heap has been configured. The heap can be repeatedly
2557 // configured through the API until it is set up.
2560 ExternalStringTable external_string_table_;
2562 VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2564 MemoryChunk* chunks_queued_for_free_;
2566 Mutex relocation_mutex_;
2568 int gc_callbacks_depth_;
2570 friend class Factory;
2571 friend class GCTracer;
2572 friend class AlwaysAllocateScope;
2574 friend class Isolate;
2575 friend class MarkCompactCollector;
2576 friend class MarkCompactMarkingVisitor;
2577 friend class MapCompact;
2579 friend class NoWeakObjectVerificationScope;
2581 friend class GCCallbacksScope;
2583 DISALLOW_COPY_AND_ASSIGN(Heap);
2589 static const int kStartMarker = 0xDECADE00;
2590 static const int kEndMarker = 0xDECADE01;
2592 int* start_marker; // 0
2593 int* new_space_size; // 1
2594 int* new_space_capacity; // 2
2595 intptr_t* old_pointer_space_size; // 3
2596 intptr_t* old_pointer_space_capacity; // 4
2597 intptr_t* old_data_space_size; // 5
2598 intptr_t* old_data_space_capacity; // 6
2599 intptr_t* code_space_size; // 7
2600 intptr_t* code_space_capacity; // 8
2601 intptr_t* map_space_size; // 9
2602 intptr_t* map_space_capacity; // 10
2603 intptr_t* cell_space_size; // 11
2604 intptr_t* cell_space_capacity; // 12
2605 intptr_t* lo_space_size; // 13
2606 int* global_handle_count; // 14
2607 int* weak_global_handle_count; // 15
2608 int* pending_global_handle_count; // 16
2609 int* near_death_global_handle_count; // 17
2610 int* free_global_handle_count; // 18
2611 intptr_t* memory_allocator_size; // 19
2612 intptr_t* memory_allocator_capacity; // 20
2613 int* objects_per_type; // 21
2614 int* size_per_type; // 22
2615 int* os_error; // 23
2616 int* end_marker; // 24
2617 intptr_t* property_cell_space_size; // 25
2618 intptr_t* property_cell_space_capacity; // 26
2622 class AlwaysAllocateScope {
2624 explicit inline AlwaysAllocateScope(Isolate* isolate);
2625 inline ~AlwaysAllocateScope();
2628 // Implicitly disable artificial allocation failures.
2630 DisallowAllocationFailure daf_;
2635 class NoWeakObjectVerificationScope {
2637 inline NoWeakObjectVerificationScope();
2638 inline ~NoWeakObjectVerificationScope();
2643 class GCCallbacksScope {
2645 explicit inline GCCallbacksScope(Heap* heap);
2646 inline ~GCCallbacksScope();
2648 inline bool CheckReenter();
2655 // Visitor class to verify interior pointers in spaces that do not contain
2656 // or care about intergenerational references. All heap object pointers have to
2657 // point into the heap to a location that has a map pointer at its first word.
2658 // Caveat: Heap::Contains is an approximation because it can return true for
2659 // objects in a heap space but above the allocation pointer.
2660 class VerifyPointersVisitor: public ObjectVisitor {
2662 inline void VisitPointers(Object** start, Object** end);
2666 // Verify that all objects are Smis.
2667 class VerifySmisVisitor: public ObjectVisitor {
2669 inline void VisitPointers(Object** start, Object** end);
2673 // Space iterator for iterating over all spaces of the heap. Returns each space
2674 // in turn, and null when it is done.
2675 class AllSpaces BASE_EMBEDDED {
2677 explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2685 // Space iterator for iterating over all old spaces of the heap: Old pointer
2686 // space, old data space and code space. Returns each space in turn, and null
2688 class OldSpaces BASE_EMBEDDED {
2690 explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2698 // Space iterator for iterating over all the paged spaces of the heap: Map
2699 // space, old pointer space, old data space, code space and cell space. Returns
2700 // each space in turn, and null when it is done.
2701 class PagedSpaces BASE_EMBEDDED {
2703 explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2711 // Space iterator for iterating over all spaces of the heap.
2712 // For each space an object iterator is provided. The deallocation of the
2713 // returned object iterators is handled by the space iterator.
2714 class SpaceIterator : public Malloced {
2716 explicit SpaceIterator(Heap* heap);
2717 SpaceIterator(Heap* heap, HeapObjectCallback size_func);
2718 virtual ~SpaceIterator();
2721 ObjectIterator* next();
2724 ObjectIterator* CreateIterator();
2727 int current_space_; // from enum AllocationSpace.
2728 ObjectIterator* iterator_; // object iterator for the current space.
2729 HeapObjectCallback size_func_;
2733 // A HeapIterator provides iteration over the whole heap. It
2734 // aggregates the specific iterators for the different spaces as
2735 // these can only iterate over one space only.
2737 // HeapIterator can skip free list nodes (that is, de-allocated heap
2738 // objects that still remain in the heap). As implementation of free
2739 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2740 // phases. Also, it is forbidden to interrupt iteration in this mode,
2741 // as this will leave heap objects marked (and thus, unusable).
2742 class HeapObjectsFilter;
2744 class HeapIterator BASE_EMBEDDED {
2746 enum HeapObjectsFiltering {
2751 explicit HeapIterator(Heap* heap);
2752 HeapIterator(Heap* heap, HeapObjectsFiltering filtering);
2759 // Perform the initialization.
2761 // Perform all necessary shutdown (destruction) work.
2763 HeapObject* NextObject();
2766 HeapObjectsFiltering filtering_;
2767 HeapObjectsFilter* filter_;
2768 // Space iterator for iterating all the spaces.
2769 SpaceIterator* space_iterator_;
2770 // Object iterator for the space currently being iterated.
2771 ObjectIterator* object_iterator_;
2775 // Cache for mapping (map, property name) into field offset.
2776 // Cleared at startup and prior to mark sweep collection.
2777 class KeyedLookupCache {
2779 // Lookup field offset for (map, name). If absent, -1 is returned.
2780 int Lookup(Map* map, Name* name);
2782 // Update an element in the cache.
2783 void Update(Map* map, Name* name, int field_offset);
2788 static const int kLength = 256;
2789 static const int kCapacityMask = kLength - 1;
2790 static const int kMapHashShift = 5;
2791 static const int kHashMask = -4; // Zero the last two bits.
2792 static const int kEntriesPerBucket = 4;
2793 static const int kNotFound = -1;
2795 // kEntriesPerBucket should be a power of 2.
2796 STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2797 STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2800 KeyedLookupCache() {
2801 for (int i = 0; i < kLength; ++i) {
2802 keys_[i].map = NULL;
2803 keys_[i].name = NULL;
2804 field_offsets_[i] = kNotFound;
2808 static inline int Hash(Map* map, Name* name);
2810 // Get the address of the keys and field_offsets arrays. Used in
2811 // generated code to perform cache lookups.
2812 Address keys_address() {
2813 return reinterpret_cast<Address>(&keys_);
2816 Address field_offsets_address() {
2817 return reinterpret_cast<Address>(&field_offsets_);
2826 int field_offsets_[kLength];
2828 friend class ExternalReference;
2829 friend class Isolate;
2830 DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2834 // Cache for mapping (map, property name) into descriptor index.
2835 // The cache contains both positive and negative results.
2836 // Descriptor index equals kNotFound means the property is absent.
2837 // Cleared at startup and prior to any gc.
2838 class DescriptorLookupCache {
2840 // Lookup descriptor index for (map, name).
2841 // If absent, kAbsent is returned.
2842 int Lookup(Map* source, Name* name) {
2843 if (!name->IsUniqueName()) return kAbsent;
2844 int index = Hash(source, name);
2845 Key& key = keys_[index];
2846 if ((key.source == source) && (key.name == name)) return results_[index];
2850 // Update an element in the cache.
2851 void Update(Map* source, Name* name, int result) {
2852 ASSERT(result != kAbsent);
2853 if (name->IsUniqueName()) {
2854 int index = Hash(source, name);
2855 Key& key = keys_[index];
2856 key.source = source;
2858 results_[index] = result;
2865 static const int kAbsent = -2;
2868 DescriptorLookupCache() {
2869 for (int i = 0; i < kLength; ++i) {
2870 keys_[i].source = NULL;
2871 keys_[i].name = NULL;
2872 results_[i] = kAbsent;
2876 static int Hash(Object* source, Name* name) {
2877 // Uses only lower 32 bits if pointers are larger.
2878 uint32_t source_hash =
2879 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(source))
2880 >> kPointerSizeLog2;
2881 uint32_t name_hash =
2882 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name))
2883 >> kPointerSizeLog2;
2884 return (source_hash ^ name_hash) % kLength;
2887 static const int kLength = 64;
2894 int results_[kLength];
2896 friend class Isolate;
2897 DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2901 // GCTracer collects and prints ONE line after each garbage collector
2902 // invocation IFF --trace_gc is used.
2904 class GCTracer BASE_EMBEDDED {
2906 class Scope BASE_EMBEDDED {
2915 MC_UPDATE_NEW_TO_NEW_POINTERS,
2916 MC_UPDATE_ROOT_TO_NEW_POINTERS,
2917 MC_UPDATE_OLD_TO_NEW_POINTERS,
2918 MC_UPDATE_POINTERS_TO_EVACUATED,
2919 MC_UPDATE_POINTERS_BETWEEN_EVACUATED,
2920 MC_UPDATE_MISC_POINTERS,
2921 MC_WEAKCOLLECTION_PROCESS,
2922 MC_WEAKCOLLECTION_CLEAR,
2927 Scope(GCTracer* tracer, ScopeId scope)
2930 start_time_ = OS::TimeCurrentMillis();
2934 ASSERT(scope_ < kNumberOfScopes); // scope_ is unsigned.
2935 tracer_->scopes_[scope_] += OS::TimeCurrentMillis() - start_time_;
2944 explicit GCTracer(Heap* heap,
2945 const char* gc_reason,
2946 const char* collector_reason);
2949 // Sets the collector.
2950 void set_collector(GarbageCollector collector) { collector_ = collector; }
2952 // Sets the GC count.
2953 void set_gc_count(unsigned int count) { gc_count_ = count; }
2955 // Sets the full GC count.
2956 void set_full_gc_count(int count) { full_gc_count_ = count; }
2958 void increment_promoted_objects_size(int object_size) {
2959 promoted_objects_size_ += object_size;
2962 void increment_nodes_died_in_new_space() {
2963 nodes_died_in_new_space_++;
2966 void increment_nodes_copied_in_new_space() {
2967 nodes_copied_in_new_space_++;
2970 void increment_nodes_promoted() {
2975 // Returns a string matching the collector.
2976 const char* CollectorString();
2978 // Returns size of object in heap (in MB).
2979 inline double SizeOfHeapObjects();
2981 // Timestamp set in the constructor.
2984 // Size of objects in heap set in constructor.
2985 intptr_t start_object_size_;
2987 // Size of memory allocated from OS set in constructor.
2988 intptr_t start_memory_size_;
2990 // Type of collector.
2991 GarbageCollector collector_;
2993 // A count (including this one, e.g. the first collection is 1) of the
2994 // number of garbage collections.
2995 unsigned int gc_count_;
2997 // A count (including this one) of the number of full garbage collections.
3000 // Amounts of time spent in different scopes during GC.
3001 double scopes_[Scope::kNumberOfScopes];
3003 // Total amount of space either wasted or contained in one of free lists
3004 // before the current GC.
3005 intptr_t in_free_list_or_wasted_before_gc_;
3007 // Difference between space used in the heap at the beginning of the current
3008 // collection and the end of the previous collection.
3009 intptr_t allocated_since_last_gc_;
3011 // Amount of time spent in mutator that is time elapsed between end of the
3012 // previous collection and the beginning of the current one.
3013 double spent_in_mutator_;
3015 // Size of objects promoted during the current collection.
3016 intptr_t promoted_objects_size_;
3018 // Number of died nodes in the new space.
3019 int nodes_died_in_new_space_;
3021 // Number of copied nodes to the new space.
3022 int nodes_copied_in_new_space_;
3024 // Number of promoted nodes to the old space.
3025 int nodes_promoted_;
3027 // Incremental marking steps counters.
3030 double longest_step_;
3031 int steps_count_since_last_gc_;
3032 double steps_took_since_last_gc_;
3036 const char* gc_reason_;
3037 const char* collector_reason_;
3041 class RegExpResultsCache {
3043 enum ResultsCacheType { REGEXP_MULTIPLE_INDICES, STRING_SPLIT_SUBSTRINGS };
3045 // Attempt to retrieve a cached result. On failure, 0 is returned as a Smi.
3046 // On success, the returned result is guaranteed to be a COW-array.
3047 static Object* Lookup(Heap* heap,
3049 Object* key_pattern,
3050 ResultsCacheType type);
3051 // Attempt to add value_array to the cache specified by type. On success,
3052 // value_array is turned into a COW-array.
3053 static void Enter(Heap* heap,
3055 Object* key_pattern,
3056 FixedArray* value_array,
3057 ResultsCacheType type);
3058 static void Clear(FixedArray* cache);
3059 static const int kRegExpResultsCacheSize = 0x100;
3062 static const int kArrayEntriesPerCacheEntry = 4;
3063 static const int kStringOffset = 0;
3064 static const int kPatternOffset = 1;
3065 static const int kArrayOffset = 2;
3069 // Abstract base class for checking whether a weak object should be retained.
3070 class WeakObjectRetainer {
3072 virtual ~WeakObjectRetainer() {}
3074 // Return whether this object should be retained. If NULL is returned the
3075 // object has no references. Otherwise the address of the retained object
3076 // should be returned as in some GC situations the object has been moved.
3077 virtual Object* RetainAs(Object* object) = 0;
3081 // Intrusive object marking uses least significant bit of
3082 // heap object's map word to mark objects.
3083 // Normally all map words have least significant bit set
3084 // because they contain tagged map pointer.
3085 // If the bit is not set object is marked.
3086 // All objects should be unmarked before resuming
3087 // JavaScript execution.
3088 class IntrusiveMarking {
3090 static bool IsMarked(HeapObject* object) {
3091 return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
3094 static void ClearMark(HeapObject* object) {
3095 uintptr_t map_word = object->map_word().ToRawValue();
3096 object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
3097 ASSERT(!IsMarked(object));
3100 static void SetMark(HeapObject* object) {
3101 uintptr_t map_word = object->map_word().ToRawValue();
3102 object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
3103 ASSERT(IsMarked(object));
3106 static Map* MapOfMarkedObject(HeapObject* object) {
3107 uintptr_t map_word = object->map_word().ToRawValue();
3108 return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
3111 static int SizeOfMarkedObject(HeapObject* object) {
3112 return object->SizeFromMap(MapOfMarkedObject(object));
3116 static const uintptr_t kNotMarkedBit = 0x1;
3117 STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0);
3122 // Helper class for tracing paths to a search target Object from all roots.
3123 // The TracePathFrom() method can be used to trace paths from a specific
3124 // object to the search target object.
3125 class PathTracer : public ObjectVisitor {
3128 FIND_ALL, // Will find all matches.
3129 FIND_FIRST // Will stop the search after first match.
3132 // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
3133 // after the first match. If FIND_ALL is specified, then tracing will be
3134 // done for all matches.
3135 PathTracer(Object* search_target,
3136 WhatToFind what_to_find,
3137 VisitMode visit_mode)
3138 : search_target_(search_target),
3139 found_target_(false),
3140 found_target_in_trace_(false),
3141 what_to_find_(what_to_find),
3142 visit_mode_(visit_mode),
3146 virtual void VisitPointers(Object** start, Object** end);
3149 void TracePathFrom(Object** root);
3151 bool found() const { return found_target_; }
3153 static Object* const kAnyGlobalObject;
3157 class UnmarkVisitor;
3159 void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
3160 void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
3161 virtual void ProcessResults();
3163 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3164 static const int kMarkTag = 2;
3166 Object* search_target_;
3168 bool found_target_in_trace_;
3169 WhatToFind what_to_find_;
3170 VisitMode visit_mode_;
3171 List<Object*> object_stack_;
3173 DisallowHeapAllocation no_allocation; // i.e. no gc allowed.
3176 DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
3180 } } // namespace v8::internal
3182 #endif // V8_HEAP_H_