1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_HEAP_HEAP_H_
6 #define V8_HEAP_HEAP_H_
11 #include "src/allocation.h"
12 #include "src/assert-scope.h"
13 #include "src/counters.h"
14 #include "src/globals.h"
15 #include "src/heap/gc-idle-time-handler.h"
16 #include "src/heap/gc-tracer.h"
17 #include "src/heap/incremental-marking.h"
18 #include "src/heap/mark-compact.h"
19 #include "src/heap/memory-reducer.h"
20 #include "src/heap/objects-visiting.h"
21 #include "src/heap/spaces.h"
22 #include "src/heap/store-buffer.h"
24 #include "src/splay-tree-inl.h"
29 // Defines all the roots in Heap.
30 #define STRONG_ROOT_LIST(V) \
31 V(Map, byte_array_map, ByteArrayMap) \
32 V(Map, free_space_map, FreeSpaceMap) \
33 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
34 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
35 /* Cluster the most popular ones in a few cache lines here at the top. */ \
36 V(Smi, store_buffer_top, StoreBufferTop) \
37 V(Oddball, undefined_value, UndefinedValue) \
38 V(Oddball, the_hole_value, TheHoleValue) \
39 V(Oddball, null_value, NullValue) \
40 V(Oddball, true_value, TrueValue) \
41 V(Oddball, false_value, FalseValue) \
42 V(String, empty_string, empty_string) \
43 V(Oddball, uninitialized_value, UninitializedValue) \
44 V(Map, cell_map, CellMap) \
45 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
46 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
47 V(Map, meta_map, MetaMap) \
48 V(Map, heap_number_map, HeapNumberMap) \
49 V(Map, mutable_heap_number_map, MutableHeapNumberMap) \
50 V(Map, float32x4_map, Float32x4Map) \
51 V(Map, native_context_map, NativeContextMap) \
52 V(Map, fixed_array_map, FixedArrayMap) \
53 V(Map, code_map, CodeMap) \
54 V(Map, scope_info_map, ScopeInfoMap) \
55 V(Map, fixed_cow_array_map, FixedCOWArrayMap) \
56 V(Map, fixed_double_array_map, FixedDoubleArrayMap) \
57 V(Map, weak_cell_map, WeakCellMap) \
58 V(Map, one_byte_string_map, OneByteStringMap) \
59 V(Map, one_byte_internalized_string_map, OneByteInternalizedStringMap) \
60 V(Map, function_context_map, FunctionContextMap) \
61 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
62 V(ByteArray, empty_byte_array, EmptyByteArray) \
63 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
64 /* The roots above this line should be boring from a GC point of view. */ \
65 /* This means they are never in new space and never on a page that is */ \
66 /* being compacted. */ \
67 V(Oddball, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
68 V(Oddball, arguments_marker, ArgumentsMarker) \
69 V(Oddball, exception, Exception) \
70 V(Oddball, termination_exception, TerminationException) \
71 V(FixedArray, number_string_cache, NumberStringCache) \
72 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
73 V(Object, instanceof_cache_map, InstanceofCacheMap) \
74 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
75 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
76 V(FixedArray, string_split_cache, StringSplitCache) \
77 V(FixedArray, regexp_multiple_cache, RegExpMultipleCache) \
78 V(Smi, hash_seed, HashSeed) \
79 V(Map, hash_table_map, HashTableMap) \
80 V(Map, ordered_hash_table_map, OrderedHashTableMap) \
81 V(Map, symbol_map, SymbolMap) \
82 V(Map, string_map, StringMap) \
83 V(Map, cons_one_byte_string_map, ConsOneByteStringMap) \
84 V(Map, cons_string_map, ConsStringMap) \
85 V(Map, sliced_string_map, SlicedStringMap) \
86 V(Map, sliced_one_byte_string_map, SlicedOneByteStringMap) \
87 V(Map, external_string_map, ExternalStringMap) \
88 V(Map, external_string_with_one_byte_data_map, \
89 ExternalStringWithOneByteDataMap) \
90 V(Map, external_one_byte_string_map, ExternalOneByteStringMap) \
91 V(Map, native_source_string_map, NativeSourceStringMap) \
92 V(Map, short_external_string_map, ShortExternalStringMap) \
93 V(Map, short_external_string_with_one_byte_data_map, \
94 ShortExternalStringWithOneByteDataMap) \
95 V(Map, internalized_string_map, InternalizedStringMap) \
96 V(Map, external_internalized_string_map, ExternalInternalizedStringMap) \
97 V(Map, external_internalized_string_with_one_byte_data_map, \
98 ExternalInternalizedStringWithOneByteDataMap) \
99 V(Map, external_one_byte_internalized_string_map, \
100 ExternalOneByteInternalizedStringMap) \
101 V(Map, short_external_internalized_string_map, \
102 ShortExternalInternalizedStringMap) \
103 V(Map, short_external_internalized_string_with_one_byte_data_map, \
104 ShortExternalInternalizedStringWithOneByteDataMap) \
105 V(Map, short_external_one_byte_internalized_string_map, \
106 ShortExternalOneByteInternalizedStringMap) \
107 V(Map, short_external_one_byte_string_map, ShortExternalOneByteStringMap) \
108 V(Map, external_int8_array_map, ExternalInt8ArrayMap) \
109 V(Map, external_uint8_array_map, ExternalUint8ArrayMap) \
110 V(Map, external_int16_array_map, ExternalInt16ArrayMap) \
111 V(Map, external_uint16_array_map, ExternalUint16ArrayMap) \
112 V(Map, external_int32_array_map, ExternalInt32ArrayMap) \
113 V(Map, external_uint32_array_map, ExternalUint32ArrayMap) \
114 V(Map, external_float32_array_map, ExternalFloat32ArrayMap) \
115 V(Map, external_float64_array_map, ExternalFloat64ArrayMap) \
116 V(Map, external_uint8_clamped_array_map, ExternalUint8ClampedArrayMap) \
117 V(ExternalArray, empty_external_int8_array, EmptyExternalInt8Array) \
118 V(ExternalArray, empty_external_uint8_array, EmptyExternalUint8Array) \
119 V(ExternalArray, empty_external_int16_array, EmptyExternalInt16Array) \
120 V(ExternalArray, empty_external_uint16_array, EmptyExternalUint16Array) \
121 V(ExternalArray, empty_external_int32_array, EmptyExternalInt32Array) \
122 V(ExternalArray, empty_external_uint32_array, EmptyExternalUint32Array) \
123 V(ExternalArray, empty_external_float32_array, EmptyExternalFloat32Array) \
124 V(ExternalArray, empty_external_float64_array, EmptyExternalFloat64Array) \
125 V(ExternalArray, empty_external_uint8_clamped_array, \
126 EmptyExternalUint8ClampedArray) \
127 V(Map, fixed_uint8_array_map, FixedUint8ArrayMap) \
128 V(Map, fixed_int8_array_map, FixedInt8ArrayMap) \
129 V(Map, fixed_uint16_array_map, FixedUint16ArrayMap) \
130 V(Map, fixed_int16_array_map, FixedInt16ArrayMap) \
131 V(Map, fixed_uint32_array_map, FixedUint32ArrayMap) \
132 V(Map, fixed_int32_array_map, FixedInt32ArrayMap) \
133 V(Map, fixed_float32_array_map, FixedFloat32ArrayMap) \
134 V(Map, fixed_float64_array_map, FixedFloat64ArrayMap) \
135 V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap) \
136 V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array) \
137 V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array) \
138 V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array) \
139 V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array) \
140 V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array) \
141 V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array) \
142 V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array) \
143 V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array) \
144 V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array, \
145 EmptyFixedUint8ClampedArray) \
146 V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap) \
147 V(Map, catch_context_map, CatchContextMap) \
148 V(Map, with_context_map, WithContextMap) \
149 V(Map, block_context_map, BlockContextMap) \
150 V(Map, module_context_map, ModuleContextMap) \
151 V(Map, script_context_map, ScriptContextMap) \
152 V(Map, script_context_table_map, ScriptContextTableMap) \
153 V(Map, undefined_map, UndefinedMap) \
154 V(Map, the_hole_map, TheHoleMap) \
155 V(Map, null_map, NullMap) \
156 V(Map, boolean_map, BooleanMap) \
157 V(Map, uninitialized_map, UninitializedMap) \
158 V(Map, arguments_marker_map, ArgumentsMarkerMap) \
159 V(Map, no_interceptor_result_sentinel_map, NoInterceptorResultSentinelMap) \
160 V(Map, exception_map, ExceptionMap) \
161 V(Map, termination_exception_map, TerminationExceptionMap) \
162 V(Map, message_object_map, JSMessageObjectMap) \
163 V(Map, foreign_map, ForeignMap) \
164 V(Map, neander_map, NeanderMap) \
165 V(Map, external_map, ExternalMap) \
166 V(HeapNumber, nan_value, NanValue) \
167 V(HeapNumber, infinity_value, InfinityValue) \
168 V(HeapNumber, minus_zero_value, MinusZeroValue) \
169 V(HeapNumber, minus_infinity_value, MinusInfinityValue) \
170 V(JSObject, message_listeners, MessageListeners) \
171 V(UnseededNumberDictionary, code_stubs, CodeStubs) \
172 V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
173 V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache) \
174 V(Code, js_entry_code, JsEntryCode) \
175 V(Code, js_construct_entry_code, JsConstructEntryCode) \
176 V(FixedArray, natives_source_cache, NativesSourceCache) \
177 V(FixedArray, experimental_natives_source_cache, \
178 ExperimentalNativesSourceCache) \
179 V(FixedArray, extra_natives_source_cache, ExtraNativesSourceCache) \
180 V(FixedArray, code_stub_natives_source_cache, CodeStubNativesSourceCache) \
181 V(Script, empty_script, EmptyScript) \
182 V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames) \
183 V(Cell, undefined_cell, UndefinedCell) \
184 V(JSObject, observation_state, ObservationState) \
185 V(Object, symbol_registry, SymbolRegistry) \
186 V(SeededNumberDictionary, empty_slow_element_dictionary, \
187 EmptySlowElementDictionary) \
188 V(FixedArray, materialized_objects, MaterializedObjects) \
189 V(FixedArray, allocation_sites_scratchpad, AllocationSitesScratchpad) \
190 V(FixedArray, microtask_queue, MicrotaskQueue) \
191 V(FixedArray, keyed_load_dummy_vector, KeyedLoadDummyVector) \
192 V(FixedArray, keyed_store_dummy_vector, KeyedStoreDummyVector) \
193 V(FixedArray, detached_contexts, DetachedContexts) \
194 V(ArrayList, retained_maps, RetainedMaps) \
195 V(WeakHashTable, weak_object_to_code_table, WeakObjectToCodeTable) \
196 V(PropertyCell, array_protector, ArrayProtector) \
197 V(PropertyCell, empty_property_cell, EmptyPropertyCell) \
198 V(Object, weak_stack_trace_list, WeakStackTraceList) \
199 V(Object, code_stub_context, CodeStubContext) \
200 V(JSObject, code_stub_exports_object, CodeStubExportsObject)
202 // Entries in this list are limited to Smis and are not visited during GC.
203 #define SMI_ROOT_LIST(V) \
204 V(Smi, stack_limit, StackLimit) \
205 V(Smi, real_stack_limit, RealStackLimit) \
206 V(Smi, last_script_id, LastScriptId) \
207 V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset) \
208 V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset) \
209 V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset) \
210 V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
213 #define ROOT_LIST(V) \
214 STRONG_ROOT_LIST(V) \
216 V(StringTable, string_table, StringTable)
218 #define INTERNALIZED_STRING_LIST(V) \
219 V(Object_string, "Object") \
220 V(proto_string, "__proto__") \
221 V(arguments_string, "arguments") \
222 V(Arguments_string, "Arguments") \
223 V(caller_string, "caller") \
224 V(boolean_string, "boolean") \
225 V(Boolean_string, "Boolean") \
226 V(callee_string, "callee") \
227 V(constructor_string, "constructor") \
228 V(dot_result_string, ".result") \
229 V(eval_string, "eval") \
230 V(function_string, "function") \
231 V(Function_string, "Function") \
232 V(length_string, "length") \
233 V(name_string, "name") \
234 V(null_string, "null") \
235 V(number_string, "number") \
236 V(Number_string, "Number") \
237 V(nan_string, "NaN") \
238 V(source_string, "source") \
239 V(source_url_string, "source_url") \
240 V(source_mapping_url_string, "source_mapping_url") \
241 V(this_string, "this") \
242 V(global_string, "global") \
243 V(ignore_case_string, "ignoreCase") \
244 V(multiline_string, "multiline") \
245 V(sticky_string, "sticky") \
246 V(unicode_string, "unicode") \
247 V(harmony_regexps_string, "harmony_regexps") \
248 V(harmony_tostring_string, "harmony_tostring") \
249 V(harmony_unicode_regexps_string, "harmony_unicode_regexps") \
250 V(input_string, "input") \
251 V(index_string, "index") \
252 V(last_index_string, "lastIndex") \
253 V(object_string, "object") \
254 V(prototype_string, "prototype") \
255 V(string_string, "string") \
256 V(String_string, "String") \
257 V(symbol_string, "symbol") \
258 V(Symbol_string, "Symbol") \
259 V(Map_string, "Map") \
260 V(Set_string, "Set") \
261 V(WeakMap_string, "WeakMap") \
262 V(WeakSet_string, "WeakSet") \
263 V(for_string, "for") \
264 V(for_api_string, "for_api") \
265 V(for_intern_string, "for_intern") \
266 V(private_api_string, "private_api") \
267 V(private_intern_string, "private_intern") \
268 V(Date_string, "Date") \
269 V(char_at_string, "CharAt") \
270 V(undefined_string, "undefined") \
271 V(value_of_string, "valueOf") \
272 V(stack_string, "stack") \
273 V(toJSON_string, "toJSON") \
274 V(KeyedLoadMonomorphic_string, "KeyedLoadMonomorphic") \
275 V(KeyedStoreMonomorphic_string, "KeyedStoreMonomorphic") \
276 V(stack_overflow_string, "$stackOverflowBoilerplate") \
277 V(illegal_access_string, "illegal access") \
278 V(cell_value_string, "%cell_value") \
279 V(illegal_argument_string, "illegal argument") \
280 V(closure_string, "(closure)") \
282 V(compare_ic_string, "==") \
283 V(strict_compare_ic_string, "===") \
284 V(infinity_string, "Infinity") \
285 V(minus_infinity_string, "-Infinity") \
286 V(query_colon_string, "(?:)") \
287 V(Generator_string, "Generator") \
288 V(throw_string, "throw") \
289 V(done_string, "done") \
290 V(value_string, "value") \
291 V(next_string, "next") \
292 V(byte_length_string, "byteLength") \
293 V(byte_offset_string, "byteOffset") \
294 V(minus_zero_string, "-0") \
295 V(Array_string, "Array") \
296 V(Error_string, "Error") \
297 V(RegExp_string, "RegExp")
299 #define PRIVATE_SYMBOL_LIST(V) \
300 V(nonextensible_symbol) \
302 V(hash_code_symbol) \
304 V(nonexistent_symbol) \
305 V(elements_transition_symbol) \
307 V(uninitialized_symbol) \
308 V(megamorphic_symbol) \
309 V(premonomorphic_symbol) \
310 V(stack_trace_symbol) \
311 V(detailed_stack_trace_symbol) \
312 V(normal_ic_symbol) \
313 V(home_object_symbol) \
314 V(intl_initialized_marker_symbol) \
315 V(intl_impl_object_symbol) \
316 V(promise_debug_marker_symbol) \
317 V(promise_has_handler_symbol) \
318 V(class_script_symbol) \
319 V(class_start_position_symbol) \
320 V(class_end_position_symbol) \
321 V(error_start_pos_symbol) \
322 V(error_end_pos_symbol) \
323 V(error_script_symbol)
325 #define PUBLIC_SYMBOL_LIST(V) \
326 V(has_instance_symbol, symbolHasInstance, Symbol.hasInstance) \
327 V(is_concat_spreadable_symbol, symbolIsConcatSpreadable, \
328 Symbol.isConcatSpreadable) \
329 V(is_regexp_symbol, symbolIsRegExp, Symbol.isRegExp) \
330 V(iterator_symbol, symbolIterator, Symbol.iterator) \
331 V(to_string_tag_symbol, symbolToStringTag, Symbol.toStringTag) \
332 V(unscopables_symbol, symbolUnscopables, Symbol.unscopables)
334 // Heap roots that are known to be immortal immovable, for which we can safely
335 // skip write barriers. This list is not complete and has omissions.
336 #define IMMORTAL_IMMOVABLE_ROOT_LIST(V) \
339 V(OnePointerFillerMap) \
340 V(TwoPointerFillerMap) \
346 V(UninitializedValue) \
348 V(GlobalPropertyCellMap) \
349 V(SharedFunctionInfoMap) \
352 V(MutableHeapNumberMap) \
354 V(NativeContextMap) \
358 V(FixedCOWArrayMap) \
359 V(FixedDoubleArrayMap) \
361 V(NoInterceptorResultSentinel) \
363 V(OrderedHashTableMap) \
366 V(EmptyDescriptorArray) \
369 V(SloppyArgumentsElementsMap) \
370 V(FunctionContextMap) \
374 V(ModuleContextMap) \
375 V(ScriptContextMap) \
380 V(UninitializedMap) \
381 V(ArgumentsMarkerMap) \
382 V(JSMessageObjectMap) \
386 PRIVATE_SYMBOL_LIST(V)
388 // Forward declarations.
391 class WeakObjectRetainer;
394 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
397 class StoreBufferRebuilder {
399 explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
400 : store_buffer_(store_buffer) {}
402 void Callback(MemoryChunk* page, StoreBufferEvent event);
405 StoreBuffer* store_buffer_;
407 // We record in this variable how full the store buffer was when we started
408 // iterating over the current page, finding pointers to new space. If the
409 // store buffer overflows again we can exempt the page from the store buffer
410 // by rewinding to this point instead of having to search the store buffer.
411 Object*** start_of_current_page_;
412 // The current page we are scanning in the store buffer iterator.
413 MemoryChunk* current_page_;
417 // A queue of objects promoted during scavenge. Each object is accompanied
418 // by it's size to avoid dereferencing a map pointer for scanning.
419 // The last page in to-space is used for the promotion queue. On conflict
420 // during scavenge, the promotion queue is allocated externally and all
421 // entries are copied to the external queue.
422 class PromotionQueue {
424 explicit PromotionQueue(Heap* heap)
435 delete emergency_stack_;
436 emergency_stack_ = NULL;
439 Page* GetHeadPage() {
440 return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
443 void SetNewLimit(Address limit) {
444 // If we are already using an emergency stack, we can ignore it.
445 if (emergency_stack_) return;
447 // If the limit is not on the same page, we can ignore it.
448 if (Page::FromAllocationTop(limit) != GetHeadPage()) return;
450 limit_ = reinterpret_cast<intptr_t*>(limit);
452 if (limit_ <= rear_) {
459 bool IsBelowPromotionQueue(Address to_space_top) {
460 // If an emergency stack is used, the to-space address cannot interfere
461 // with the promotion queue.
462 if (emergency_stack_) return true;
464 // If the given to-space top pointer and the head of the promotion queue
465 // are not on the same page, then the to-space objects are below the
467 if (GetHeadPage() != Page::FromAddress(to_space_top)) {
470 // If the to space top pointer is smaller or equal than the promotion
471 // queue head, then the to-space objects are below the promotion queue.
472 return reinterpret_cast<intptr_t*>(to_space_top) <= rear_;
476 return (front_ == rear_) &&
477 (emergency_stack_ == NULL || emergency_stack_->length() == 0);
480 inline void insert(HeapObject* target, int size);
482 void remove(HeapObject** target, int* size) {
484 if (front_ == rear_) {
485 Entry e = emergency_stack_->RemoveLast();
491 *target = reinterpret_cast<HeapObject*>(*(--front_));
492 *size = static_cast<int>(*(--front_));
493 // Assert no underflow.
494 SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
495 reinterpret_cast<Address>(front_));
499 // The front of the queue is higher in the memory page chain than the rear.
504 static const int kEntrySizeInWords = 2;
507 Entry(HeapObject* obj, int size) : obj_(obj), size_(size) {}
512 List<Entry>* emergency_stack_;
516 void RelocateQueueHead();
518 DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
522 typedef void (*ScavengingCallback)(Map* map, HeapObject** slot,
526 // External strings table is a place where all external strings are
527 // registered. We need to keep track of such strings to properly
529 class ExternalStringTable {
531 // Registers an external string.
532 inline void AddString(String* string);
534 inline void Iterate(ObjectVisitor* v);
536 // Restores internal invariant and gets rid of collected strings.
537 // Must be called after each Iterate() that modified the strings.
540 // Destroys all allocated memory.
544 explicit ExternalStringTable(Heap* heap) : heap_(heap) {}
548 inline void Verify();
550 inline void AddOldString(String* string);
552 // Notifies the table that only a prefix of the new list is valid.
553 inline void ShrinkNewStrings(int position);
555 // To speed up scavenge collections new space string are kept
556 // separate from old space strings.
557 List<Object*> new_space_strings_;
558 List<Object*> old_space_strings_;
562 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
566 enum ArrayStorageAllocationMode {
567 DONT_INITIALIZE_ARRAY_ELEMENTS,
568 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
574 // Configure heap size in MB before setup. Return false if the heap has been
576 bool ConfigureHeap(int max_semi_space_size, int max_old_space_size,
577 int max_executable_size, size_t code_range_size);
578 bool ConfigureHeapDefault();
580 // Prepares the heap, setting up memory areas that are needed in the isolate
581 // without actually creating any objects.
584 // Bootstraps the object heap with the core set of objects required to run.
585 // Returns whether it succeeded.
586 bool CreateHeapObjects();
588 // Destroys all memory allocated by the heap.
591 // Set the stack limit in the roots_ array. Some architectures generate
592 // code that looks here, because it is faster than loading from the static
593 // jslimit_/real_jslimit_ variable in the StackGuard.
594 void SetStackLimits();
596 // Notifies the heap that is ok to start marking or other activities that
597 // should not happen during deserialization.
598 void NotifyDeserializationComplete();
600 // Returns whether SetUp has been called.
603 // Returns the maximum amount of memory reserved for the heap. For
604 // the young generation, we reserve 4 times the amount needed for a
605 // semi space. The young generation consists of two semi spaces and
606 // we reserve twice the amount needed for those in order to ensure
607 // that new space can be aligned to its size.
608 intptr_t MaxReserved() {
609 return 4 * reserved_semispace_size_ + max_old_generation_size_;
611 int MaxSemiSpaceSize() { return max_semi_space_size_; }
612 int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
613 int InitialSemiSpaceSize() { return initial_semispace_size_; }
614 int TargetSemiSpaceSize() { return target_semispace_size_; }
615 intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
616 intptr_t MaxExecutableSize() { return max_executable_size_; }
618 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
619 // more spaces are needed until it reaches the limit.
622 // Returns the amount of memory currently committed for the heap.
623 intptr_t CommittedMemory();
625 // Returns the amount of memory currently committed for the old space.
626 intptr_t CommittedOldGenerationMemory();
628 // Returns the amount of executable memory currently committed for the heap.
629 intptr_t CommittedMemoryExecutable();
631 // Returns the amount of phyical memory currently committed for the heap.
632 size_t CommittedPhysicalMemory();
634 // Returns the maximum amount of memory ever committed for the heap.
635 intptr_t MaximumCommittedMemory() { return maximum_committed_; }
637 // Updates the maximum committed memory for the heap. Should be called
638 // whenever a space grows.
639 void UpdateMaximumCommitted();
641 // Returns the available bytes in space w/o growing.
642 // Heap doesn't guarantee that it can allocate an object that requires
643 // all available bytes. Check MaxHeapObjectSize() instead.
644 intptr_t Available();
646 // Returns of size of all objects residing in the heap.
647 intptr_t SizeOfObjects();
649 intptr_t old_generation_allocation_limit() const {
650 return old_generation_allocation_limit_;
653 // Return the starting address and a mask for the new space. And-masking an
654 // address with the mask will result in the start address of the new space
655 // for all addresses in either semispace.
656 Address NewSpaceStart() { return new_space_.start(); }
657 uintptr_t NewSpaceMask() { return new_space_.mask(); }
658 Address NewSpaceTop() { return new_space_.top(); }
660 NewSpace* new_space() { return &new_space_; }
661 OldSpace* old_space() { return old_space_; }
662 OldSpace* code_space() { return code_space_; }
663 MapSpace* map_space() { return map_space_; }
664 LargeObjectSpace* lo_space() { return lo_space_; }
665 PagedSpace* paged_space(int idx) {
679 Space* space(int idx) {
686 return paged_space(idx);
690 // Returns name of the space.
691 const char* GetSpaceName(int idx);
693 bool always_allocate() { return always_allocate_scope_depth_ != 0; }
694 Address always_allocate_scope_depth_address() {
695 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
698 Address* NewSpaceAllocationTopAddress() {
699 return new_space_.allocation_top_address();
701 Address* NewSpaceAllocationLimitAddress() {
702 return new_space_.allocation_limit_address();
705 Address* OldSpaceAllocationTopAddress() {
706 return old_space_->allocation_top_address();
708 Address* OldSpaceAllocationLimitAddress() {
709 return old_space_->allocation_limit_address();
712 // TODO(hpayer): There is still a missmatch between capacity and actual
713 // committed memory size.
714 bool CanExpandOldGeneration(int size) {
715 return (CommittedOldGenerationMemory() + size) < MaxOldGenerationSize();
718 // Returns a deep copy of the JavaScript object.
719 // Properties and elements are copied too.
720 // Optionally takes an AllocationSite to be appended in an AllocationMemento.
721 MUST_USE_RESULT AllocationResult
722 CopyJSObject(JSObject* source, AllocationSite* site = NULL);
724 // Calculates the maximum amount of filler that could be required by the
726 static int GetMaximumFillToAlign(AllocationAlignment alignment);
727 // Calculates the actual amount of filler required for a given address at the
729 static int GetFillToAlign(Address address, AllocationAlignment alignment);
731 // Creates a filler object and returns a heap object immediately after it.
732 MUST_USE_RESULT HeapObject* PrecedeWithFiller(HeapObject* object,
734 // Creates a filler object if needed for alignment and returns a heap object
735 // immediately after it. If any space is left after the returned object,
736 // another filler object is created so the over allocated memory is iterable.
737 MUST_USE_RESULT HeapObject* AlignWithFiller(HeapObject* object,
740 AllocationAlignment alignment);
742 // Clear the Instanceof cache (used when a prototype changes).
743 inline void ClearInstanceofCache();
745 // Iterates the whole code space to clear all ICs of the given kind.
746 void ClearAllICsByKind(Code::Kind kind);
748 // FreeSpace objects have a null map after deserialization. Update the map.
749 void RepairFreeListsAfterDeserialization();
751 template <typename T>
752 static inline bool IsOneByte(T t, int chars);
754 // Move len elements within a given array from src_index index to dst_index
756 void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
758 // Sloppy mode arguments object size.
759 static const int kSloppyArgumentsObjectSize =
760 JSObject::kHeaderSize + 2 * kPointerSize;
761 // Strict mode arguments has no callee so it is smaller.
762 static const int kStrictArgumentsObjectSize =
763 JSObject::kHeaderSize + 1 * kPointerSize;
764 // Indicies for direct access into argument objects.
765 static const int kArgumentsLengthIndex = 0;
766 // callee is only valid in sloppy mode.
767 static const int kArgumentsCalleeIndex = 1;
769 // Finalizes an external string by deleting the associated external
770 // data and clearing the resource pointer.
771 inline void FinalizeExternalString(String* string);
773 // Initialize a filler object to keep the ability to iterate over the heap
774 // when introducing gaps within pages.
775 void CreateFillerObjectAt(Address addr, int size);
777 bool CanMoveObjectStart(HeapObject* object);
779 // Indicates whether live bytes adjustment is triggered
780 // - from within the GC code before sweeping started (SEQUENTIAL_TO_SWEEPER),
781 // - or from within GC (CONCURRENT_TO_SWEEPER),
782 // - or mutator code (CONCURRENT_TO_SWEEPER).
783 enum InvocationMode { SEQUENTIAL_TO_SWEEPER, CONCURRENT_TO_SWEEPER };
785 // Maintain consistency of live bytes during incremental marking.
786 void AdjustLiveBytes(Address address, int by, InvocationMode mode);
788 // Trim the given array from the left. Note that this relocates the object
789 // start and hence is only valid if there is only a single reference to it.
790 FixedArrayBase* LeftTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
792 // Trim the given array from the right.
793 template<Heap::InvocationMode mode>
794 void RightTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
796 // Converts the given boolean condition to JavaScript boolean value.
797 inline Object* ToBoolean(bool condition);
799 // Performs garbage collection operation.
800 // Returns whether there is a chance that another major GC could
801 // collect more garbage.
802 inline bool CollectGarbage(
803 AllocationSpace space, const char* gc_reason = NULL,
804 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
806 static const int kNoGCFlags = 0;
807 static const int kReduceMemoryFootprintMask = 1;
808 static const int kAbortIncrementalMarkingMask = 2;
809 static const int kFinalizeIncrementalMarkingMask = 4;
811 // Making the heap iterable requires us to abort incremental marking.
812 static const int kMakeHeapIterableMask = kAbortIncrementalMarkingMask;
814 // Invoked when GC was requested via the stack guard.
815 void HandleGCRequest();
817 // Attempt to over-approximate the weak closure by marking object groups and
818 // implicit references from global handles, but don't atomically complete
819 // marking. If we continue to mark incrementally, we might have marked
820 // objects that die later.
821 void OverApproximateWeakClosure(const char* gc_reason);
823 // Performs a full garbage collection. If (flags & kMakeHeapIterableMask) is
824 // non-zero, then the slower precise sweeper is used, which leaves the heap
825 // in a state where we can iterate over the heap visiting all objects.
826 void CollectAllGarbage(
827 int flags = kFinalizeIncrementalMarkingMask, const char* gc_reason = NULL,
828 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
830 // Last hope GC, should try to squeeze as much as possible.
831 void CollectAllAvailableGarbage(const char* gc_reason = NULL);
833 // Check whether the heap is currently iterable.
834 bool IsHeapIterable();
836 // Notify the heap that a context has been disposed.
837 int NotifyContextDisposed(bool dependant_context);
839 // Start incremental marking and ensure that idle time handler can perform
840 // incremental steps.
841 void StartIdleIncrementalMarking();
843 inline void increment_scan_on_scavenge_pages() {
844 scan_on_scavenge_pages_++;
845 if (FLAG_gc_verbose) {
846 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
850 inline void decrement_scan_on_scavenge_pages() {
851 scan_on_scavenge_pages_--;
852 if (FLAG_gc_verbose) {
853 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
857 PromotionQueue* promotion_queue() { return &promotion_queue_; }
859 void AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
860 GCType gc_type_filter, bool pass_isolate = true);
861 void RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback);
863 void AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
864 GCType gc_type_filter, bool pass_isolate = true);
865 void RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback);
867 // Heap root getters. We have versions with and without type::cast() here.
868 // You can't use type::cast during GC because the assert fails.
869 // TODO(1490): Try removing the unchecked accessors, now that GC marking does
870 // not corrupt the map.
871 #define ROOT_ACCESSOR(type, name, camel_name) \
872 type* name() { return type::cast(roots_[k##camel_name##RootIndex]); } \
873 type* raw_unchecked_##name() { \
874 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
876 ROOT_LIST(ROOT_ACCESSOR)
880 #define STRUCT_MAP_ACCESSOR(NAME, Name, name) \
881 Map* name##_map() { return Map::cast(roots_[k##Name##MapRootIndex]); }
882 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
883 #undef STRUCT_MAP_ACCESSOR
885 #define STRING_ACCESSOR(name, str) \
886 String* name() { return String::cast(roots_[k##name##RootIndex]); }
887 INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
888 #undef STRING_ACCESSOR
890 #define SYMBOL_ACCESSOR(name) \
891 Symbol* name() { return Symbol::cast(roots_[k##name##RootIndex]); }
892 PRIVATE_SYMBOL_LIST(SYMBOL_ACCESSOR)
893 #undef SYMBOL_ACCESSOR
895 #define SYMBOL_ACCESSOR(name, varname, description) \
896 Symbol* name() { return Symbol::cast(roots_[k##name##RootIndex]); }
897 PUBLIC_SYMBOL_LIST(SYMBOL_ACCESSOR)
898 #undef SYMBOL_ACCESSOR
900 // The hidden_string is special because it is the empty string, but does
901 // not match the empty string.
902 String* hidden_string() { return hidden_string_; }
904 void set_native_contexts_list(Object* object) {
905 native_contexts_list_ = object;
907 Object* native_contexts_list() const { return native_contexts_list_; }
909 void set_allocation_sites_list(Object* object) {
910 allocation_sites_list_ = object;
912 Object* allocation_sites_list() { return allocation_sites_list_; }
914 // Used in CreateAllocationSiteStub and the (de)serializer.
915 Object** allocation_sites_list_address() { return &allocation_sites_list_; }
917 void set_encountered_weak_collections(Object* weak_collection) {
918 encountered_weak_collections_ = weak_collection;
920 Object* encountered_weak_collections() const {
921 return encountered_weak_collections_;
924 void set_encountered_weak_cells(Object* weak_cell) {
925 encountered_weak_cells_ = weak_cell;
927 Object* encountered_weak_cells() const { return encountered_weak_cells_; }
929 // Number of mark-sweeps.
930 unsigned int ms_count() { return ms_count_; }
932 // Iterates over all roots in the heap.
933 void IterateRoots(ObjectVisitor* v, VisitMode mode);
934 // Iterates over all strong roots in the heap.
935 void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
936 // Iterates over entries in the smi roots list. Only interesting to the
937 // serializer/deserializer, since GC does not care about smis.
938 void IterateSmiRoots(ObjectVisitor* v);
939 // Iterates over all the other roots in the heap.
940 void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
942 // Iterate pointers to from semispace of new space found in memory interval
943 // from start to end.
944 void IterateAndMarkPointersToFromSpace(bool record_slots, Address start,
946 ObjectSlotCallback callback);
948 // Returns whether the object resides in new space.
949 inline bool InNewSpace(Object* object);
950 inline bool InNewSpace(Address address);
951 inline bool InNewSpacePage(Address address);
952 inline bool InFromSpace(Object* object);
953 inline bool InToSpace(Object* object);
955 // Returns whether the object resides in old space.
956 inline bool InOldSpace(Address address);
957 inline bool InOldSpace(Object* object);
959 // Checks whether an address/object in the heap (including auxiliary
960 // area and unused area).
961 bool Contains(Address addr);
962 bool Contains(HeapObject* value);
964 // Checks whether an address/object in a space.
965 // Currently used by tests, serialization and heap verification only.
966 bool InSpace(Address addr, AllocationSpace space);
967 bool InSpace(HeapObject* value, AllocationSpace space);
969 // Checks whether the space is valid.
970 static bool IsValidAllocationSpace(AllocationSpace space);
972 // Checks whether the given object is allowed to be migrated from it's
973 // current space into the given destination space. Used for debugging.
974 inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
976 // Sets the stub_cache_ (only used when expanding the dictionary).
977 void public_set_code_stubs(UnseededNumberDictionary* value) {
978 roots_[kCodeStubsRootIndex] = value;
981 // Support for computing object sizes for old objects during GCs. Returns
982 // a function that is guaranteed to be safe for computing object sizes in
983 // the current GC phase.
984 HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
985 return gc_safe_size_of_old_object_;
988 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
989 void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
990 roots_[kNonMonomorphicCacheRootIndex] = value;
993 void public_set_empty_script(Script* script) {
994 roots_[kEmptyScriptRootIndex] = script;
997 void public_set_store_buffer_top(Address* top) {
998 roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1001 void public_set_materialized_objects(FixedArray* objects) {
1002 roots_[kMaterializedObjectsRootIndex] = objects;
1005 // Generated code can embed this address to get access to the roots.
1006 Object** roots_array_start() { return roots_; }
1008 Address* store_buffer_top_address() {
1009 return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1012 static bool RootIsImmortalImmovable(int root_index);
1013 void CheckHandleCount();
1016 // Verify the heap is in its normal state before or after a GC.
1022 void PrintHandles();
1024 // Report heap statistics.
1025 void ReportHeapStatistics(const char* title);
1026 void ReportCodeStatistics(const char* title);
1029 // Zapping is needed for verify heap, and always done in debug builds.
1030 static inline bool ShouldZapGarbage() {
1035 return FLAG_verify_heap;
1042 // Number of "runtime allocations" done so far.
1043 uint32_t allocations_count() { return allocations_count_; }
1045 // Returns deterministic "time" value in ms. Works only with
1046 // FLAG_verify_predictable.
1047 double synthetic_time() { return allocations_count_ / 2.0; }
1049 // Print short heap statistics.
1050 void PrintShortHeapStatistics();
1052 size_t object_count_last_gc(size_t index) {
1053 return index < OBJECT_STATS_COUNT ? object_counts_last_time_[index] : 0;
1055 size_t object_size_last_gc(size_t index) {
1056 return index < OBJECT_STATS_COUNT ? object_sizes_last_time_[index] : 0;
1059 // Write barrier support for address[offset] = o.
1060 INLINE(void RecordWrite(Address address, int offset));
1062 // Write barrier support for address[start : start + len[ = o.
1063 INLINE(void RecordWrites(Address address, int start, int len));
1065 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1066 inline HeapState gc_state() { return gc_state_; }
1068 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1071 void set_allocation_timeout(int timeout) { allocation_timeout_ = timeout; }
1073 void TracePathToObjectFrom(Object* target, Object* root);
1074 void TracePathToObject(Object* target);
1075 void TracePathToGlobal();
1078 // Callback function passed to Heap::Iterate etc. Copies an object if
1079 // necessary, the object might be promoted to an old space. The caller must
1080 // ensure the precondition that the object is (a) a heap object and (b) in
1081 // the heap's from space.
1082 static inline void ScavengePointer(HeapObject** p);
1083 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1085 enum ScratchpadSlotMode { IGNORE_SCRATCHPAD_SLOT, RECORD_SCRATCHPAD_SLOT };
1087 // If an object has an AllocationMemento trailing it, return it, otherwise
1089 inline AllocationMemento* FindAllocationMemento(HeapObject* object);
1091 // An object may have an AllocationSite associated with it through a trailing
1092 // AllocationMemento. Its feedback should be updated when objects are found
1094 static inline void UpdateAllocationSiteFeedback(HeapObject* object,
1095 ScratchpadSlotMode mode);
1097 // Support for partial snapshots. After calling this we have a linear
1098 // space to write objects in each space.
1105 typedef List<Chunk> Reservation;
1107 // Returns false if not able to reserve.
1108 bool ReserveSpace(Reservation* reservations);
1111 // Support for the API.
1114 void CreateApiObjects();
1116 inline intptr_t PromotedTotalSize() {
1117 int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1118 if (total > std::numeric_limits<intptr_t>::max()) {
1119 // TODO(erikcorry): Use uintptr_t everywhere we do heap size calculations.
1120 return std::numeric_limits<intptr_t>::max();
1122 if (total < 0) return 0;
1123 return static_cast<intptr_t>(total);
1126 inline intptr_t OldGenerationSpaceAvailable() {
1127 return old_generation_allocation_limit_ - PromotedTotalSize();
1130 inline intptr_t OldGenerationCapacityAvailable() {
1131 return max_old_generation_size_ - PromotedTotalSize();
1134 static const intptr_t kMinimumOldGenerationAllocationLimit =
1135 8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1137 static const int kInitalOldGenerationLimitFactor = 2;
1140 // Don't apply pointer multiplier on Android since it has no swap space and
1141 // should instead adapt it's heap size based on available physical memory.
1142 static const int kPointerMultiplier = 1;
1144 static const int kPointerMultiplier = i::kPointerSize / 4;
1147 // The new space size has to be a power of 2. Sizes are in MB.
1148 static const int kMaxSemiSpaceSizeLowMemoryDevice = 1 * kPointerMultiplier;
1149 static const int kMaxSemiSpaceSizeMediumMemoryDevice = 4 * kPointerMultiplier;
1150 static const int kMaxSemiSpaceSizeHighMemoryDevice = 8 * kPointerMultiplier;
1151 static const int kMaxSemiSpaceSizeHugeMemoryDevice = 8 * kPointerMultiplier;
1153 // The old space size has to be a multiple of Page::kPageSize.
1155 static const int kMaxOldSpaceSizeLowMemoryDevice = 128 * kPointerMultiplier;
1156 static const int kMaxOldSpaceSizeMediumMemoryDevice =
1157 256 * kPointerMultiplier;
1158 static const int kMaxOldSpaceSizeHighMemoryDevice = 512 * kPointerMultiplier;
1159 static const int kMaxOldSpaceSizeHugeMemoryDevice = 700 * kPointerMultiplier;
1161 // The executable size has to be a multiple of Page::kPageSize.
1163 static const int kMaxExecutableSizeLowMemoryDevice = 96 * kPointerMultiplier;
1164 static const int kMaxExecutableSizeMediumMemoryDevice =
1165 192 * kPointerMultiplier;
1166 static const int kMaxExecutableSizeHighMemoryDevice =
1167 256 * kPointerMultiplier;
1168 static const int kMaxExecutableSizeHugeMemoryDevice =
1169 256 * kPointerMultiplier;
1171 static const int kTraceRingBufferSize = 512;
1172 static const int kStacktraceBufferSize = 512;
1174 static const double kMinHeapGrowingFactor;
1175 static const double kMaxHeapGrowingFactor;
1176 static const double kMaxHeapGrowingFactorMemoryConstrained;
1177 static const double kMaxHeapGrowingFactorIdle;
1178 static const double kTargetMutatorUtilization;
1180 static double HeapGrowingFactor(double gc_speed, double mutator_speed);
1182 // Calculates the allocation limit based on a given growing factor and a
1183 // given old generation size.
1184 intptr_t CalculateOldGenerationAllocationLimit(double factor,
1185 intptr_t old_gen_size);
1187 // Sets the allocation limit to trigger the next full garbage collection.
1188 void SetOldGenerationAllocationLimit(intptr_t old_gen_size, double gc_speed,
1189 double mutator_speed);
1191 // Decrease the allocation limit if the new limit based on the given
1192 // parameters is lower than the current limit.
1193 void DampenOldGenerationAllocationLimit(intptr_t old_gen_size,
1195 double mutator_speed);
1197 // Indicates whether inline bump-pointer allocation has been disabled.
1198 bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1200 // Switch whether inline bump-pointer allocation should be used.
1201 void EnableInlineAllocation();
1202 void DisableInlineAllocation();
1204 // Implements the corresponding V8 API function.
1205 bool IdleNotification(double deadline_in_seconds);
1206 bool IdleNotification(int idle_time_in_ms);
1208 double MonotonicallyIncreasingTimeInMs();
1210 // Declare all the root indices. This defines the root list order.
1211 enum RootListIndex {
1212 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1213 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1214 #undef ROOT_INDEX_DECLARATION
1216 #define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
1217 INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
1218 #undef STRING_DECLARATION
1220 #define SYMBOL_INDEX_DECLARATION(name) k##name##RootIndex,
1221 PRIVATE_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1222 #undef SYMBOL_INDEX_DECLARATION
1224 #define SYMBOL_INDEX_DECLARATION(name, varname, description) k##name##RootIndex,
1225 PUBLIC_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1226 #undef SYMBOL_INDEX_DECLARATION
1228 // Utility type maps
1229 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1230 STRUCT_LIST(DECLARE_STRUCT_MAP)
1231 #undef DECLARE_STRUCT_MAP
1232 kStringTableRootIndex,
1234 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1235 SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
1236 #undef ROOT_INDEX_DECLARATION
1238 kStrongRootListLength = kStringTableRootIndex,
1239 kSmiRootsStart = kStringTableRootIndex + 1
1242 Object* root(RootListIndex index) { return roots_[index]; }
1244 STATIC_ASSERT(kUndefinedValueRootIndex ==
1245 Internals::kUndefinedValueRootIndex);
1246 STATIC_ASSERT(kNullValueRootIndex == Internals::kNullValueRootIndex);
1247 STATIC_ASSERT(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1248 STATIC_ASSERT(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1249 STATIC_ASSERT(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
1251 // Generated code can embed direct references to non-writable roots if
1252 // they are in new space.
1253 static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
1254 // Generated code can treat direct references to this root as constant.
1255 bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1257 Map* MapForFixedTypedArray(ExternalArrayType array_type);
1258 RootListIndex RootIndexForFixedTypedArray(ExternalArrayType array_type);
1260 Map* MapForExternalArrayType(ExternalArrayType array_type);
1261 RootListIndex RootIndexForExternalArrayType(ExternalArrayType array_type);
1263 RootListIndex RootIndexForEmptyExternalArray(ElementsKind kind);
1264 RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1265 ExternalArray* EmptyExternalArrayForMap(Map* map);
1266 FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1268 void RecordStats(HeapStats* stats, bool take_snapshot = false);
1270 // Copy block of memory from src to dst. Size of block should be aligned
1272 static inline void CopyBlock(Address dst, Address src, int byte_size);
1274 // Optimized version of memmove for blocks with pointer size aligned sizes and
1275 // pointer size aligned addresses.
1276 static inline void MoveBlock(Address dst, Address src, int byte_size);
1278 // Check new space expansion criteria and expand semispaces if it was hit.
1279 void CheckNewSpaceExpansionCriteria();
1281 inline void IncrementPromotedObjectsSize(int object_size) {
1282 DCHECK(object_size > 0);
1283 promoted_objects_size_ += object_size;
1286 inline void IncrementSemiSpaceCopiedObjectSize(int object_size) {
1287 DCHECK(object_size > 0);
1288 semi_space_copied_object_size_ += object_size;
1291 inline intptr_t SurvivedNewSpaceObjectSize() {
1292 return promoted_objects_size_ + semi_space_copied_object_size_;
1295 inline void IncrementNodesDiedInNewSpace() { nodes_died_in_new_space_++; }
1297 inline void IncrementNodesCopiedInNewSpace() { nodes_copied_in_new_space_++; }
1299 inline void IncrementNodesPromoted() { nodes_promoted_++; }
1301 inline void IncrementYoungSurvivorsCounter(int survived) {
1302 DCHECK(survived >= 0);
1303 survived_last_scavenge_ = survived;
1304 survived_since_last_expansion_ += survived;
1307 inline bool HeapIsFullEnoughToStartIncrementalMarking(intptr_t limit) {
1308 if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1310 intptr_t adjusted_allocation_limit = limit - new_space_.Capacity();
1312 if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
1317 void UpdateNewSpaceReferencesInExternalStringTable(
1318 ExternalStringTableUpdaterCallback updater_func);
1320 void UpdateReferencesInExternalStringTable(
1321 ExternalStringTableUpdaterCallback updater_func);
1323 void ProcessAllWeakReferences(WeakObjectRetainer* retainer);
1324 void ProcessYoungWeakReferences(WeakObjectRetainer* retainer);
1326 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1328 // An object should be promoted if the object has survived a
1329 // scavenge operation.
1330 inline bool ShouldBePromoted(Address old_address, int object_size);
1332 void ClearJSFunctionResultCaches();
1334 void ClearNormalizedMapCaches();
1336 GCTracer* tracer() { return &tracer_; }
1338 // Returns the size of objects residing in non new spaces.
1339 intptr_t PromotedSpaceSizeOfObjects();
1341 double total_regexp_code_generated() { return total_regexp_code_generated_; }
1342 void IncreaseTotalRegexpCodeGenerated(int size) {
1343 total_regexp_code_generated_ += size;
1346 void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1347 if (is_crankshafted) {
1348 crankshaft_codegen_bytes_generated_ += size;
1350 full_codegen_bytes_generated_ += size;
1354 void UpdateNewSpaceAllocationCounter() {
1355 new_space_allocation_counter_ = NewSpaceAllocationCounter();
1358 size_t NewSpaceAllocationCounter() {
1359 return new_space_allocation_counter_ + new_space()->AllocatedSinceLastGC();
1362 // This should be used only for testing.
1363 void set_new_space_allocation_counter(size_t new_value) {
1364 new_space_allocation_counter_ = new_value;
1367 void UpdateOldGenerationAllocationCounter() {
1368 old_generation_allocation_counter_ = OldGenerationAllocationCounter();
1371 size_t OldGenerationAllocationCounter() {
1372 return old_generation_allocation_counter_ + PromotedSinceLastGC();
1375 // This should be used only for testing.
1376 void set_old_generation_allocation_counter(size_t new_value) {
1377 old_generation_allocation_counter_ = new_value;
1380 size_t PromotedSinceLastGC() {
1381 return PromotedSpaceSizeOfObjects() - old_generation_size_at_last_gc_;
1384 // Record the fact that we generated some optimized code since the last GC
1385 // which will pretenure some previously unpretenured allocation.
1386 void RecordDeoptForPretenuring() { gathering_lifetime_feedback_ = 2; }
1388 // Update GC statistics that are tracked on the Heap.
1389 void UpdateCumulativeGCStatistics(double duration, double spent_in_mutator,
1390 double marking_time);
1392 // Returns maximum GC pause.
1393 double get_max_gc_pause() { return max_gc_pause_; }
1395 // Returns maximum size of objects alive after GC.
1396 intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1398 // Returns minimal interval between two subsequent collections.
1399 double get_min_in_mutator() { return min_in_mutator_; }
1401 void IncrementDeferredCount(v8::Isolate::UseCounterFeature feature);
1403 MarkCompactCollector* mark_compact_collector() {
1404 return &mark_compact_collector_;
1407 StoreBuffer* store_buffer() { return &store_buffer_; }
1409 Marking* marking() { return &marking_; }
1411 IncrementalMarking* incremental_marking() { return &incremental_marking_; }
1413 ExternalStringTable* external_string_table() {
1414 return &external_string_table_;
1417 // Returns the current sweep generation.
1418 int sweep_generation() { return sweep_generation_; }
1420 bool concurrent_sweeping_enabled() { return concurrent_sweeping_enabled_; }
1422 inline Isolate* isolate();
1424 void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1425 void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1427 inline bool OldGenerationAllocationLimitReached();
1429 inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1430 scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1433 void QueueMemoryChunkForFree(MemoryChunk* chunk);
1434 void FreeQueuedChunks();
1436 int gc_count() const { return gc_count_; }
1438 bool RecentIdleNotificationHappened();
1440 // Completely clear the Instanceof cache (to stop it keeping objects alive
1442 inline void CompletelyClearInstanceofCache();
1444 // The roots that have an index less than this are always in old space.
1445 static const int kOldSpaceRoots = 0x20;
1447 uint32_t HashSeed() {
1448 uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1449 DCHECK(FLAG_randomize_hashes || seed == 0);
1453 Smi* NextScriptId() {
1454 int next_id = last_script_id()->value() + 1;
1455 if (!Smi::IsValid(next_id) || next_id < 0) next_id = 1;
1456 Smi* next_id_smi = Smi::FromInt(next_id);
1457 set_last_script_id(next_id_smi);
1461 void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1462 DCHECK(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1463 set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1466 void SetConstructStubDeoptPCOffset(int pc_offset) {
1467 DCHECK(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1468 set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1471 void SetGetterStubDeoptPCOffset(int pc_offset) {
1472 DCHECK(getter_stub_deopt_pc_offset() == Smi::FromInt(0));
1473 set_getter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1476 void SetSetterStubDeoptPCOffset(int pc_offset) {
1477 DCHECK(setter_stub_deopt_pc_offset() == Smi::FromInt(0));
1478 set_setter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1481 // For post mortem debugging.
1482 void RememberUnmappedPage(Address page, bool compacted);
1484 // Global inline caching age: it is incremented on some GCs after context
1485 // disposal. We use it to flush inline caches.
1486 int global_ic_age() { return global_ic_age_; }
1488 void AgeInlineCaches() {
1489 global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
1492 int64_t amount_of_external_allocated_memory() {
1493 return amount_of_external_allocated_memory_;
1496 void DeoptMarkedAllocationSites();
1498 bool MaximumSizeScavenge() { return maximum_size_scavenges_ > 0; }
1500 bool DeoptMaybeTenuredAllocationSites() {
1501 return new_space_.IsAtMaximumCapacity() && maximum_size_scavenges_ == 0;
1504 // ObjectStats are kept in two arrays, counts and sizes. Related stats are
1505 // stored in a contiguous linear buffer. Stats groups are stored one after
1508 FIRST_CODE_KIND_SUB_TYPE = LAST_TYPE + 1,
1509 FIRST_FIXED_ARRAY_SUB_TYPE =
1510 FIRST_CODE_KIND_SUB_TYPE + Code::NUMBER_OF_KINDS,
1511 FIRST_CODE_AGE_SUB_TYPE =
1512 FIRST_FIXED_ARRAY_SUB_TYPE + LAST_FIXED_ARRAY_SUB_TYPE + 1,
1513 OBJECT_STATS_COUNT = FIRST_CODE_AGE_SUB_TYPE + Code::kCodeAgeCount + 1
1516 void RecordObjectStats(InstanceType type, size_t size) {
1517 DCHECK(type <= LAST_TYPE);
1518 object_counts_[type]++;
1519 object_sizes_[type] += size;
1522 void RecordCodeSubTypeStats(int code_sub_type, int code_age, size_t size) {
1523 int code_sub_type_index = FIRST_CODE_KIND_SUB_TYPE + code_sub_type;
1524 int code_age_index =
1525 FIRST_CODE_AGE_SUB_TYPE + code_age - Code::kFirstCodeAge;
1526 DCHECK(code_sub_type_index >= FIRST_CODE_KIND_SUB_TYPE &&
1527 code_sub_type_index < FIRST_CODE_AGE_SUB_TYPE);
1528 DCHECK(code_age_index >= FIRST_CODE_AGE_SUB_TYPE &&
1529 code_age_index < OBJECT_STATS_COUNT);
1530 object_counts_[code_sub_type_index]++;
1531 object_sizes_[code_sub_type_index] += size;
1532 object_counts_[code_age_index]++;
1533 object_sizes_[code_age_index] += size;
1536 void RecordFixedArraySubTypeStats(int array_sub_type, size_t size) {
1537 DCHECK(array_sub_type <= LAST_FIXED_ARRAY_SUB_TYPE);
1538 object_counts_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type]++;
1539 object_sizes_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type] += size;
1542 void TraceObjectStats();
1543 void TraceObjectStat(const char* name, int count, int size, double time);
1544 void CheckpointObjectStats();
1545 bool GetObjectTypeName(size_t index, const char** object_type,
1546 const char** object_sub_type);
1548 void RegisterStrongRoots(Object** start, Object** end);
1549 void UnregisterStrongRoots(Object** start);
1551 // Taking this lock prevents the GC from entering a phase that relocates
1552 // object references.
1553 class RelocationLock {
1555 explicit RelocationLock(Heap* heap) : heap_(heap) {
1556 heap_->relocation_mutex_.Lock();
1559 ~RelocationLock() { heap_->relocation_mutex_.Unlock(); }
1565 // An optional version of the above lock that can be used for some critical
1566 // sections on the mutator thread; only safe since the GC currently does not
1567 // do concurrent compaction.
1568 class OptionalRelocationLock {
1570 OptionalRelocationLock(Heap* heap, bool concurrent)
1571 : heap_(heap), concurrent_(concurrent) {
1572 if (concurrent_) heap_->relocation_mutex_.Lock();
1575 ~OptionalRelocationLock() {
1576 if (concurrent_) heap_->relocation_mutex_.Unlock();
1584 void AddWeakObjectToCodeDependency(Handle<HeapObject> obj,
1585 Handle<DependentCode> dep);
1587 DependentCode* LookupWeakObjectToCodeDependency(Handle<HeapObject> obj);
1589 void AddRetainedMap(Handle<Map> map);
1591 static void FatalProcessOutOfMemory(const char* location,
1592 bool take_snapshot = false);
1594 // This event is triggered after successful allocation of a new object made
1595 // by runtime. Allocations of target space for object evacuation do not
1596 // trigger the event. In order to track ALL allocations one must turn off
1597 // FLAG_inline_new and FLAG_use_allocation_folding.
1598 inline void OnAllocationEvent(HeapObject* object, int size_in_bytes);
1600 // This event is triggered after object is moved to a new place.
1601 inline void OnMoveEvent(HeapObject* target, HeapObject* source,
1604 bool deserialization_complete() const { return deserialization_complete_; }
1606 // The following methods are used to track raw C++ pointers to externally
1607 // allocated memory used as backing store in live array buffers.
1609 // A new ArrayBuffer was created with |data| as backing store.
1610 void RegisterNewArrayBuffer(bool in_new_space, void* data, size_t length);
1612 // The backing store |data| is no longer owned by V8.
1613 void UnregisterArrayBuffer(bool in_new_space, void* data);
1615 // A live ArrayBuffer was discovered during marking/scavenge.
1616 void RegisterLiveArrayBuffer(bool from_scavenge, void* data);
1618 // Frees all backing store pointers that weren't discovered in the previous
1619 // marking or scavenge phase.
1620 void FreeDeadArrayBuffers(bool from_scavenge);
1622 // Prepare for a new scavenge phase. A new marking phase is implicitly
1623 // prepared by finishing the previous one.
1624 void PrepareArrayBufferDiscoveryInNewSpace();
1626 // An ArrayBuffer moved from new space to old space.
1627 void PromoteArrayBuffer(Object* buffer);
1629 bool HasLowAllocationRate();
1630 bool HasHighFragmentation();
1631 bool HasHighFragmentation(intptr_t used, intptr_t committed);
1634 // Methods made available to tests.
1636 // Allocates a JS Map in the heap.
1637 MUST_USE_RESULT AllocationResult
1638 AllocateMap(InstanceType instance_type, int instance_size,
1639 ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
1641 // Allocates and initializes a new JavaScript object based on a
1643 // If allocation_site is non-null, then a memento is emitted after the object
1644 // that points to the site.
1645 MUST_USE_RESULT AllocationResult
1646 AllocateJSObject(JSFunction* constructor,
1647 PretenureFlag pretenure = NOT_TENURED,
1648 AllocationSite* allocation_site = NULL);
1650 // Allocates and initializes a new JavaScript object based on a map.
1651 // Passing an allocation site means that a memento will be created that
1652 // points to the site.
1653 MUST_USE_RESULT AllocationResult
1654 AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure = NOT_TENURED,
1655 AllocationSite* allocation_site = NULL);
1657 // Allocates a HeapNumber from value.
1658 MUST_USE_RESULT AllocationResult
1659 AllocateHeapNumber(double value, MutableMode mode = IMMUTABLE,
1660 PretenureFlag pretenure = NOT_TENURED);
1662 // Allocates a Float32x4 from the given lane values.
1663 MUST_USE_RESULT AllocationResult
1664 AllocateFloat32x4(float w, float x, float y, float z,
1665 PretenureFlag pretenure = NOT_TENURED);
1667 // Allocates a byte array of the specified length
1668 MUST_USE_RESULT AllocationResult
1669 AllocateByteArray(int length, PretenureFlag pretenure = NOT_TENURED);
1671 // Copy the code and scope info part of the code object, but insert
1672 // the provided data as the relocation information.
1673 MUST_USE_RESULT AllocationResult
1674 CopyCode(Code* code, Vector<byte> reloc_info);
1676 MUST_USE_RESULT AllocationResult CopyCode(Code* code);
1678 // Allocates a fixed array initialized with undefined values
1679 MUST_USE_RESULT AllocationResult
1680 AllocateFixedArray(int length, PretenureFlag pretenure = NOT_TENURED);
1682 static const int kInitialStringTableSize = 2048;
1683 static const int kInitialEvalCacheSize = 64;
1684 static const int kInitialNumberStringCacheSize = 256;
1689 // The amount of external memory registered through the API kept alive
1690 // by global handles
1691 int64_t amount_of_external_allocated_memory_;
1693 // Caches the amount of external memory registered at the last global gc.
1694 int64_t amount_of_external_allocated_memory_at_last_global_gc_;
1696 // This can be calculated directly from a pointer to the heap; however, it is
1697 // more expedient to get at the isolate directly from within Heap methods.
1700 Object* roots_[kRootListLength];
1702 size_t code_range_size_;
1703 int reserved_semispace_size_;
1704 int max_semi_space_size_;
1705 int initial_semispace_size_;
1706 int target_semispace_size_;
1707 intptr_t max_old_generation_size_;
1708 intptr_t initial_old_generation_size_;
1709 bool old_generation_size_configured_;
1710 intptr_t max_executable_size_;
1711 intptr_t maximum_committed_;
1713 // For keeping track of how much data has survived
1714 // scavenge since last new space expansion.
1715 int survived_since_last_expansion_;
1717 // ... and since the last scavenge.
1718 int survived_last_scavenge_;
1720 // For keeping track on when to flush RegExp code.
1721 int sweep_generation_;
1723 int always_allocate_scope_depth_;
1725 // For keeping track of context disposals.
1726 int contexts_disposed_;
1730 int scan_on_scavenge_pages_;
1732 NewSpace new_space_;
1733 OldSpace* old_space_;
1734 OldSpace* code_space_;
1735 MapSpace* map_space_;
1736 LargeObjectSpace* lo_space_;
1737 HeapState gc_state_;
1738 int gc_post_processing_depth_;
1739 Address new_space_top_after_last_gc_;
1741 // Returns the amount of external memory registered since last global gc.
1742 int64_t PromotedExternalMemorySize();
1744 // How many "runtime allocations" happened.
1745 uint32_t allocations_count_;
1747 // Running hash over allocations performed.
1748 uint32_t raw_allocations_hash_;
1750 // Countdown counter, dumps allocation hash when 0.
1751 uint32_t dump_allocations_hash_countdown_;
1753 // How many mark-sweep collections happened.
1754 unsigned int ms_count_;
1756 // How many gc happened.
1757 unsigned int gc_count_;
1759 // For post mortem debugging.
1760 static const int kRememberedUnmappedPages = 128;
1761 int remembered_unmapped_pages_index_;
1762 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
1764 // Total length of the strings we failed to flatten since the last GC.
1765 int unflattened_strings_length_;
1767 #define ROOT_ACCESSOR(type, name, camel_name) \
1768 inline void set_##name(type* value) { \
1769 /* The deserializer makes use of the fact that these common roots are */ \
1770 /* never in new space and never on a page that is being compacted. */ \
1771 DCHECK(!deserialization_complete() || \
1772 RootCanBeWrittenAfterInitialization(k##camel_name##RootIndex)); \
1773 DCHECK(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value)); \
1774 roots_[k##camel_name##RootIndex] = value; \
1776 ROOT_LIST(ROOT_ACCESSOR)
1777 #undef ROOT_ACCESSOR
1780 // If the --gc-interval flag is set to a positive value, this
1781 // variable holds the value indicating the number of allocations
1782 // remain until the next failure and garbage collection.
1783 int allocation_timeout_;
1786 // Limit that triggers a global GC on the next (normally caused) GC. This
1787 // is checked when we have already decided to do a GC to help determine
1788 // which collector to invoke, before expanding a paged space in the old
1789 // generation and on every allocation in large object space.
1790 intptr_t old_generation_allocation_limit_;
1792 // Indicates that an allocation has failed in the old generation since the
1794 bool old_gen_exhausted_;
1796 // Indicates that inline bump-pointer allocation has been globally disabled
1797 // for all spaces. This is used to disable allocations in generated code.
1798 bool inline_allocation_disabled_;
1800 // Weak list heads, threaded through the objects.
1801 // List heads are initialized lazily and contain the undefined_value at start.
1802 Object* native_contexts_list_;
1803 Object* allocation_sites_list_;
1805 // List of encountered weak collections (JSWeakMap and JSWeakSet) during
1806 // marking. It is initialized during marking, destroyed after marking and
1807 // contains Smi(0) while marking is not active.
1808 Object* encountered_weak_collections_;
1810 Object* encountered_weak_cells_;
1812 StoreBufferRebuilder store_buffer_rebuilder_;
1814 struct StringTypeTable {
1817 RootListIndex index;
1820 struct ConstantStringTable {
1821 const char* contents;
1822 RootListIndex index;
1825 struct StructTable {
1828 RootListIndex index;
1831 static const StringTypeTable string_type_table[];
1832 static const ConstantStringTable constant_string_table[];
1833 static const StructTable struct_table[];
1835 // The special hidden string which is an empty string, but does not match
1836 // any string when looked up in properties.
1837 String* hidden_string_;
1839 void AddPrivateGlobalSymbols(Handle<Object> private_intern_table);
1841 // GC callback function, called before and after mark-compact GC.
1842 // Allocations in the callback function are disallowed.
1843 struct GCPrologueCallbackPair {
1844 GCPrologueCallbackPair(v8::Isolate::GCPrologueCallback callback,
1845 GCType gc_type, bool pass_isolate)
1846 : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {}
1847 bool operator==(const GCPrologueCallbackPair& pair) const {
1848 return pair.callback == callback;
1850 v8::Isolate::GCPrologueCallback callback;
1852 // TODO(dcarney): remove variable
1855 List<GCPrologueCallbackPair> gc_prologue_callbacks_;
1857 struct GCEpilogueCallbackPair {
1858 GCEpilogueCallbackPair(v8::Isolate::GCPrologueCallback callback,
1859 GCType gc_type, bool pass_isolate)
1860 : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {}
1861 bool operator==(const GCEpilogueCallbackPair& pair) const {
1862 return pair.callback == callback;
1864 v8::Isolate::GCPrologueCallback callback;
1866 // TODO(dcarney): remove variable
1869 List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
1871 // Support for computing object sizes during GC.
1872 HeapObjectCallback gc_safe_size_of_old_object_;
1873 static int GcSafeSizeOfOldObject(HeapObject* object);
1875 // Update the GC state. Called from the mark-compact collector.
1876 void MarkMapPointersAsEncoded(bool encoded) {
1878 gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
1881 // Code that should be run before and after each GC. Includes some
1882 // reporting/verification activities when compiled with DEBUG set.
1883 void GarbageCollectionPrologue();
1884 void GarbageCollectionEpilogue();
1886 void PreprocessStackTraces();
1888 // Pretenuring decisions are made based on feedback collected during new
1889 // space evacuation. Note that between feedback collection and calling this
1890 // method object in old space must not move.
1891 // Right now we only process pretenuring feedback in high promotion mode.
1892 bool ProcessPretenuringFeedback();
1894 // Checks whether a global GC is necessary
1895 GarbageCollector SelectGarbageCollector(AllocationSpace space,
1896 const char** reason);
1898 // Make sure there is a filler value behind the top of the new space
1899 // so that the GC does not confuse some unintialized/stale memory
1900 // with the allocation memento of the object at the top
1901 void EnsureFillerObjectAtTop();
1903 // Ensure that we have swept all spaces in such a way that we can iterate
1904 // over all objects. May cause a GC.
1905 void MakeHeapIterable();
1907 // Performs garbage collection operation.
1908 // Returns whether there is a chance that another major GC could
1909 // collect more garbage.
1910 bool CollectGarbage(
1911 GarbageCollector collector, const char* gc_reason,
1912 const char* collector_reason,
1913 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1915 // Performs garbage collection
1916 // Returns whether there is a chance another major GC could
1917 // collect more garbage.
1918 bool PerformGarbageCollection(
1919 GarbageCollector collector,
1920 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1922 inline void UpdateOldSpaceLimits();
1924 // Selects the proper allocation space depending on the given object
1925 // size and pretenuring decision.
1926 static AllocationSpace SelectSpace(int object_size,
1927 PretenureFlag pretenure) {
1928 if (object_size > Page::kMaxRegularHeapObjectSize) return LO_SPACE;
1929 return (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1932 HeapObject* DoubleAlignForDeserialization(HeapObject* object, int size);
1934 // Allocate an uninitialized object. The memory is non-executable if the
1935 // hardware and OS allow. This is the single choke-point for allocations
1936 // performed by the runtime and should not be bypassed (to extend this to
1937 // inlined allocations, use the Heap::DisableInlineAllocation() support).
1938 MUST_USE_RESULT inline AllocationResult AllocateRaw(
1939 int size_in_bytes, AllocationSpace space, AllocationSpace retry_space,
1940 AllocationAlignment aligment = kWordAligned);
1942 // Allocates a heap object based on the map.
1943 MUST_USE_RESULT AllocationResult
1944 Allocate(Map* map, AllocationSpace space,
1945 AllocationSite* allocation_site = NULL);
1947 // Allocates a partial map for bootstrapping.
1948 MUST_USE_RESULT AllocationResult
1949 AllocatePartialMap(InstanceType instance_type, int instance_size);
1951 // Initializes a JSObject based on its map.
1952 void InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties,
1954 void InitializeAllocationMemento(AllocationMemento* memento,
1955 AllocationSite* allocation_site);
1957 // Allocate a block of memory in the given space (filled with a filler).
1958 // Used as a fall-back for generated code when the space is full.
1959 MUST_USE_RESULT AllocationResult
1960 AllocateFillerObject(int size, bool double_align, AllocationSpace space);
1962 // Allocate an uninitialized fixed array.
1963 MUST_USE_RESULT AllocationResult
1964 AllocateRawFixedArray(int length, PretenureFlag pretenure);
1966 // Allocate an uninitialized fixed double array.
1967 MUST_USE_RESULT AllocationResult
1968 AllocateRawFixedDoubleArray(int length, PretenureFlag pretenure);
1970 // Allocate an initialized fixed array with the given filler value.
1971 MUST_USE_RESULT AllocationResult
1972 AllocateFixedArrayWithFiller(int length, PretenureFlag pretenure,
1975 // Allocate and partially initializes a String. There are two String
1976 // encodings: one-byte and two-byte. These functions allocate a string of
1977 // the given length and set its map and length fields. The characters of
1978 // the string are uninitialized.
1979 MUST_USE_RESULT AllocationResult
1980 AllocateRawOneByteString(int length, PretenureFlag pretenure);
1981 MUST_USE_RESULT AllocationResult
1982 AllocateRawTwoByteString(int length, PretenureFlag pretenure);
1984 bool CreateInitialMaps();
1985 void CreateInitialObjects();
1987 // Allocates an internalized string in old space based on the character
1989 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringFromUtf8(
1990 Vector<const char> str, int chars, uint32_t hash_field);
1992 MUST_USE_RESULT inline AllocationResult AllocateOneByteInternalizedString(
1993 Vector<const uint8_t> str, uint32_t hash_field);
1995 MUST_USE_RESULT inline AllocationResult AllocateTwoByteInternalizedString(
1996 Vector<const uc16> str, uint32_t hash_field);
1998 template <bool is_one_byte, typename T>
1999 MUST_USE_RESULT AllocationResult
2000 AllocateInternalizedStringImpl(T t, int chars, uint32_t hash_field);
2002 template <typename T>
2003 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringImpl(
2004 T t, int chars, uint32_t hash_field);
2006 // Allocates an uninitialized fixed array. It must be filled by the caller.
2007 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedArray(int length);
2009 // Make a copy of src and return it. Returns
2010 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
2011 MUST_USE_RESULT inline AllocationResult CopyFixedArray(FixedArray* src);
2013 // Make a copy of src, set the map, and return the copy. Returns
2014 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
2015 MUST_USE_RESULT AllocationResult
2016 CopyFixedArrayWithMap(FixedArray* src, Map* map);
2018 // Make a copy of src and return it. Returns
2019 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
2020 MUST_USE_RESULT inline AllocationResult CopyFixedDoubleArray(
2021 FixedDoubleArray* src);
2023 // Computes a single character string where the character has code.
2024 // A cache is used for one-byte (Latin1) codes.
2025 MUST_USE_RESULT AllocationResult
2026 LookupSingleCharacterStringFromCode(uint16_t code);
2028 // Allocate a symbol in old space.
2029 MUST_USE_RESULT AllocationResult AllocateSymbol();
2031 // Allocates an external array of the specified length and type.
2032 MUST_USE_RESULT AllocationResult
2033 AllocateExternalArray(int length, ExternalArrayType array_type,
2034 void* external_pointer, PretenureFlag pretenure);
2036 // Allocates a fixed typed array of the specified length and type.
2037 MUST_USE_RESULT AllocationResult
2038 AllocateFixedTypedArray(int length, ExternalArrayType array_type,
2039 bool initialize, PretenureFlag pretenure);
2041 // Make a copy of src and return it.
2042 MUST_USE_RESULT AllocationResult CopyAndTenureFixedCOWArray(FixedArray* src);
2044 // Make a copy of src, set the map, and return the copy.
2045 MUST_USE_RESULT AllocationResult
2046 CopyFixedDoubleArrayWithMap(FixedDoubleArray* src, Map* map);
2048 // Allocates a fixed double array with uninitialized values. Returns
2049 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedDoubleArray(
2050 int length, PretenureFlag pretenure = NOT_TENURED);
2052 // These five Create*EntryStub functions are here and forced to not be inlined
2053 // because of a gcc-4.4 bug that assigns wrong vtable entries.
2054 NO_INLINE(void CreateJSEntryStub());
2055 NO_INLINE(void CreateJSConstructEntryStub());
2057 void CreateFixedStubs();
2059 // Allocate empty fixed array.
2060 MUST_USE_RESULT AllocationResult AllocateEmptyFixedArray();
2062 // Allocate empty external array of given type.
2063 MUST_USE_RESULT AllocationResult
2064 AllocateEmptyExternalArray(ExternalArrayType array_type);
2066 // Allocate empty fixed typed array of given type.
2067 MUST_USE_RESULT AllocationResult
2068 AllocateEmptyFixedTypedArray(ExternalArrayType array_type);
2070 // Allocate a tenured simple cell.
2071 MUST_USE_RESULT AllocationResult AllocateCell(Object* value);
2073 // Allocate a tenured JS global property cell initialized with the hole.
2074 MUST_USE_RESULT AllocationResult AllocatePropertyCell();
2076 MUST_USE_RESULT AllocationResult AllocateWeakCell(HeapObject* value);
2078 // Allocates a new utility object in the old generation.
2079 MUST_USE_RESULT AllocationResult AllocateStruct(InstanceType type);
2081 // Allocates a new foreign object.
2082 MUST_USE_RESULT AllocationResult
2083 AllocateForeign(Address address, PretenureFlag pretenure = NOT_TENURED);
2085 MUST_USE_RESULT AllocationResult
2086 AllocateCode(int object_size, bool immovable);
2088 MUST_USE_RESULT AllocationResult InternalizeStringWithKey(HashTableKey* key);
2090 MUST_USE_RESULT AllocationResult InternalizeString(String* str);
2092 // Performs a minor collection in new generation.
2095 // Commits from space if it is uncommitted.
2096 void EnsureFromSpaceIsCommitted();
2098 // Uncommit unused semi space.
2099 bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
2101 // Fill in bogus values in from space
2102 void ZapFromSpace();
2104 static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
2105 Heap* heap, Object** pointer);
2107 Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
2108 static void ScavengeStoreBufferCallback(Heap* heap, MemoryChunk* page,
2109 StoreBufferEvent event);
2111 // Performs a major collection in the whole heap.
2114 // Code to be run before and after mark-compact.
2115 void MarkCompactPrologue();
2116 void MarkCompactEpilogue();
2118 void ProcessNativeContexts(WeakObjectRetainer* retainer);
2119 void ProcessAllocationSites(WeakObjectRetainer* retainer);
2121 // Deopts all code that contains allocation instruction which are tenured or
2122 // not tenured. Moreover it clears the pretenuring allocation site statistics.
2123 void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
2125 // Evaluates local pretenuring for the old space and calls
2126 // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
2128 void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
2130 // Called on heap tear-down. Frees all remaining ArrayBuffer backing stores.
2131 void TearDownArrayBuffers();
2133 // These correspond to the non-Helper versions.
2134 void RegisterNewArrayBufferHelper(std::map<void*, size_t>& live_buffers,
2135 void* data, size_t length);
2136 void UnregisterArrayBufferHelper(
2137 std::map<void*, size_t>& live_buffers,
2138 std::map<void*, size_t>& not_yet_discovered_buffers, void* data);
2139 void RegisterLiveArrayBufferHelper(
2140 std::map<void*, size_t>& not_yet_discovered_buffers, void* data);
2141 size_t FreeDeadArrayBuffersHelper(
2142 Isolate* isolate, std::map<void*, size_t>& live_buffers,
2143 std::map<void*, size_t>& not_yet_discovered_buffers);
2144 void TearDownArrayBuffersHelper(
2145 Isolate* isolate, std::map<void*, size_t>& live_buffers,
2146 std::map<void*, size_t>& not_yet_discovered_buffers);
2148 // Record statistics before and after garbage collection.
2149 void ReportStatisticsBeforeGC();
2150 void ReportStatisticsAfterGC();
2152 // Slow part of scavenge object.
2153 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
2155 // Total RegExp code ever generated
2156 double total_regexp_code_generated_;
2158 int deferred_counters_[v8::Isolate::kUseCounterFeatureCount];
2162 // Creates and installs the full-sized number string cache.
2163 int FullSizeNumberStringCacheLength();
2164 // Flush the number to string cache.
2165 void FlushNumberStringCache();
2167 // Sets used allocation sites entries to undefined.
2168 void FlushAllocationSitesScratchpad();
2170 // Initializes the allocation sites scratchpad with undefined values.
2171 void InitializeAllocationSitesScratchpad();
2173 // Adds an allocation site to the scratchpad if there is space left.
2174 void AddAllocationSiteToScratchpad(AllocationSite* site,
2175 ScratchpadSlotMode mode);
2177 void UpdateSurvivalStatistics(int start_new_space_size);
2179 enum SurvivalRateTrend { INCREASING, STABLE, DECREASING, FLUCTUATING };
2181 static const int kYoungSurvivalRateHighThreshold = 90;
2182 static const int kYoungSurvivalRateLowThreshold = 10;
2183 static const int kYoungSurvivalRateAllowedDeviation = 15;
2185 static const int kOldSurvivalRateLowThreshold = 10;
2187 bool new_space_high_promotion_mode_active_;
2188 // If this is non-zero, then there is hope yet that the optimized code we
2189 // have generated will solve our high promotion rate problems, so we don't
2190 // need to go into high promotion mode just yet.
2191 int gathering_lifetime_feedback_;
2192 int high_survival_rate_period_length_;
2193 intptr_t promoted_objects_size_;
2194 int low_survival_rate_period_length_;
2195 double survival_rate_;
2196 double promotion_ratio_;
2197 double promotion_rate_;
2198 intptr_t semi_space_copied_object_size_;
2199 intptr_t previous_semi_space_copied_object_size_;
2200 double semi_space_copied_rate_;
2201 int nodes_died_in_new_space_;
2202 int nodes_copied_in_new_space_;
2203 int nodes_promoted_;
2205 // This is the pretenuring trigger for allocation sites that are in maybe
2206 // tenure state. When we switched to the maximum new space size we deoptimize
2207 // the code that belongs to the allocation site and derive the lifetime
2208 // of the allocation site.
2209 unsigned int maximum_size_scavenges_;
2211 SurvivalRateTrend previous_survival_rate_trend_;
2212 SurvivalRateTrend survival_rate_trend_;
2214 void set_survival_rate_trend(SurvivalRateTrend survival_rate_trend) {
2215 DCHECK(survival_rate_trend != FLUCTUATING);
2216 previous_survival_rate_trend_ = survival_rate_trend_;
2217 survival_rate_trend_ = survival_rate_trend;
2220 SurvivalRateTrend survival_rate_trend() {
2221 if (survival_rate_trend_ == STABLE) {
2223 } else if (previous_survival_rate_trend_ == STABLE) {
2224 return survival_rate_trend_;
2225 } else if (survival_rate_trend_ != previous_survival_rate_trend_) {
2228 return survival_rate_trend_;
2232 bool IsStableOrIncreasingSurvivalTrend() {
2233 switch (survival_rate_trend()) {
2242 bool IsStableOrDecreasingSurvivalTrend() {
2243 switch (survival_rate_trend()) {
2252 bool IsIncreasingSurvivalTrend() {
2253 return survival_rate_trend() == INCREASING;
2256 bool IsLowSurvivalRate() { return low_survival_rate_period_length_ > 0; }
2258 bool IsHighSurvivalRate() { return high_survival_rate_period_length_ > 0; }
2260 void ConfigureInitialOldGenerationSize();
2262 void ConfigureNewGenerationSize();
2264 void SelectScavengingVisitorsTable();
2266 bool HasLowYoungGenerationAllocationRate();
2267 bool HasLowOldGenerationAllocationRate();
2269 void ReduceNewSpaceSize();
2271 bool TryFinalizeIdleIncrementalMarking(
2272 double idle_time_in_ms, size_t size_of_objects,
2273 size_t mark_compact_speed_in_bytes_per_ms);
2275 GCIdleTimeHandler::HeapState ComputeHeapState();
2277 bool PerformIdleTimeAction(GCIdleTimeAction action,
2278 GCIdleTimeHandler::HeapState heap_state,
2279 double deadline_in_ms);
2281 void IdleNotificationEpilogue(GCIdleTimeAction action,
2282 GCIdleTimeHandler::HeapState heap_state,
2283 double start_ms, double deadline_in_ms);
2284 void CheckAndNotifyBackgroundIdleNotification(double idle_time_in_ms,
2287 void ClearObjectStats(bool clear_last_time_stats = false);
2289 inline void UpdateAllocationsHash(HeapObject* object);
2290 inline void UpdateAllocationsHash(uint32_t value);
2291 inline void PrintAlloctionsHash();
2293 void AddToRingBuffer(const char* string);
2294 void GetFromRingBuffer(char* buffer);
2296 // Object counts and used memory by InstanceType
2297 size_t object_counts_[OBJECT_STATS_COUNT];
2298 size_t object_counts_last_time_[OBJECT_STATS_COUNT];
2299 size_t object_sizes_[OBJECT_STATS_COUNT];
2300 size_t object_sizes_last_time_[OBJECT_STATS_COUNT];
2302 // Maximum GC pause.
2303 double max_gc_pause_;
2305 // Total time spent in GC.
2306 double total_gc_time_ms_;
2308 // Maximum size of objects alive after GC.
2309 intptr_t max_alive_after_gc_;
2311 // Minimal interval between two subsequent collections.
2312 double min_in_mutator_;
2314 // Cumulative GC time spent in marking.
2315 double marking_time_;
2317 // Cumulative GC time spent in sweeping.
2318 double sweeping_time_;
2320 // Last time an idle notification happened.
2321 double last_idle_notification_time_;
2323 // Last time a garbage collection happened.
2324 double last_gc_time_;
2326 MarkCompactCollector mark_compact_collector_;
2328 StoreBuffer store_buffer_;
2332 IncrementalMarking incremental_marking_;
2334 GCIdleTimeHandler gc_idle_time_handler_;
2336 MemoryReducer memory_reducer_;
2338 // These two counters are monotomically increasing and never reset.
2339 size_t full_codegen_bytes_generated_;
2340 size_t crankshaft_codegen_bytes_generated_;
2342 // This counter is increased before each GC and never reset.
2343 // To account for the bytes allocated since the last GC, use the
2344 // NewSpaceAllocationCounter() function.
2345 size_t new_space_allocation_counter_;
2347 // This counter is increased before each GC and never reset. To
2348 // account for the bytes allocated since the last GC, use the
2349 // OldGenerationAllocationCounter() function.
2350 size_t old_generation_allocation_counter_;
2352 // The size of objects in old generation after the last MarkCompact GC.
2353 size_t old_generation_size_at_last_gc_;
2355 // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2356 // this variable holds the number of garbage collections since the last
2357 // deoptimization triggered by garbage collection.
2358 int gcs_since_last_deopt_;
2360 static const int kAllocationSiteScratchpadSize = 256;
2361 int allocation_sites_scratchpad_length_;
2363 char trace_ring_buffer_[kTraceRingBufferSize];
2364 // If it's not full then the data is from 0 to ring_buffer_end_. If it's
2365 // full then the data is from ring_buffer_end_ to the end of the buffer and
2366 // from 0 to ring_buffer_end_.
2367 bool ring_buffer_full_;
2368 size_t ring_buffer_end_;
2370 static const int kMaxMarkCompactsInIdleRound = 7;
2371 static const int kIdleScavengeThreshold = 5;
2373 // Shared state read by the scavenge collector and set by ScavengeObject.
2374 PromotionQueue promotion_queue_;
2376 // Flag is set when the heap has been configured. The heap can be repeatedly
2377 // configured through the API until it is set up.
2380 ExternalStringTable external_string_table_;
2382 VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2384 MemoryChunk* chunks_queued_for_free_;
2386 base::Mutex relocation_mutex_;
2388 int gc_callbacks_depth_;
2390 bool deserialization_complete_;
2392 bool concurrent_sweeping_enabled_;
2394 // |live_array_buffers_| maps externally allocated memory used as backing
2395 // store for ArrayBuffers to the length of the respective memory blocks.
2397 // At the beginning of mark/compact, |not_yet_discovered_array_buffers_| is
2398 // a copy of |live_array_buffers_| and we remove pointers as we discover live
2399 // ArrayBuffer objects during marking. At the end of mark/compact, the
2400 // remaining memory blocks can be freed.
2401 std::map<void*, size_t> live_array_buffers_;
2402 std::map<void*, size_t> not_yet_discovered_array_buffers_;
2404 // To be able to free memory held by ArrayBuffers during scavenge as well, we
2405 // have a separate list of allocated memory held by ArrayBuffers in new space.
2407 // Since mark/compact also evacuates the new space, all pointers in the
2408 // |live_array_buffers_for_scavenge_| list are also in the
2409 // |live_array_buffers_| list.
2410 std::map<void*, size_t> live_array_buffers_for_scavenge_;
2411 std::map<void*, size_t> not_yet_discovered_array_buffers_for_scavenge_;
2413 struct StrongRootsList;
2414 StrongRootsList* strong_roots_list_;
2416 friend class AlwaysAllocateScope;
2417 friend class Bootstrapper;
2418 friend class Deserializer;
2419 friend class Factory;
2420 friend class GCCallbacksScope;
2421 friend class GCTracer;
2422 friend class HeapIterator;
2423 friend class Isolate;
2424 friend class MarkCompactCollector;
2425 friend class MarkCompactMarkingVisitor;
2426 friend class MapCompact;
2429 DISALLOW_COPY_AND_ASSIGN(Heap);
2435 static const int kStartMarker = 0xDECADE00;
2436 static const int kEndMarker = 0xDECADE01;
2438 int* start_marker; // 0
2439 int* new_space_size; // 1
2440 int* new_space_capacity; // 2
2441 intptr_t* old_space_size; // 3
2442 intptr_t* old_space_capacity; // 4
2443 intptr_t* code_space_size; // 5
2444 intptr_t* code_space_capacity; // 6
2445 intptr_t* map_space_size; // 7
2446 intptr_t* map_space_capacity; // 8
2447 intptr_t* lo_space_size; // 9
2448 int* global_handle_count; // 10
2449 int* weak_global_handle_count; // 11
2450 int* pending_global_handle_count; // 12
2451 int* near_death_global_handle_count; // 13
2452 int* free_global_handle_count; // 14
2453 intptr_t* memory_allocator_size; // 15
2454 intptr_t* memory_allocator_capacity; // 16
2455 int* objects_per_type; // 17
2456 int* size_per_type; // 18
2457 int* os_error; // 19
2458 char* last_few_messages; // 20
2459 char* js_stacktrace; // 21
2460 int* end_marker; // 22
2464 class AlwaysAllocateScope {
2466 explicit inline AlwaysAllocateScope(Isolate* isolate);
2467 inline ~AlwaysAllocateScope();
2470 // Implicitly disable artificial allocation failures.
2472 DisallowAllocationFailure daf_;
2476 class GCCallbacksScope {
2478 explicit inline GCCallbacksScope(Heap* heap);
2479 inline ~GCCallbacksScope();
2481 inline bool CheckReenter();
2488 // Visitor class to verify interior pointers in spaces that do not contain
2489 // or care about intergenerational references. All heap object pointers have to
2490 // point into the heap to a location that has a map pointer at its first word.
2491 // Caveat: Heap::Contains is an approximation because it can return true for
2492 // objects in a heap space but above the allocation pointer.
2493 class VerifyPointersVisitor : public ObjectVisitor {
2495 inline void VisitPointers(Object** start, Object** end);
2499 // Verify that all objects are Smis.
2500 class VerifySmisVisitor : public ObjectVisitor {
2502 inline void VisitPointers(Object** start, Object** end);
2506 // Space iterator for iterating over all spaces of the heap. Returns each space
2507 // in turn, and null when it is done.
2508 class AllSpaces BASE_EMBEDDED {
2510 explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2519 // Space iterator for iterating over all old spaces of the heap: Old space
2520 // and code space. Returns each space in turn, and null when it is done.
2521 class OldSpaces BASE_EMBEDDED {
2523 explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
2532 // Space iterator for iterating over all the paged spaces of the heap: Map
2533 // space, old space, code space and cell space. Returns
2534 // each space in turn, and null when it is done.
2535 class PagedSpaces BASE_EMBEDDED {
2537 explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
2546 // Space iterator for iterating over all spaces of the heap.
2547 // For each space an object iterator is provided. The deallocation of the
2548 // returned object iterators is handled by the space iterator.
2549 class SpaceIterator : public Malloced {
2551 explicit SpaceIterator(Heap* heap);
2552 SpaceIterator(Heap* heap, HeapObjectCallback size_func);
2553 virtual ~SpaceIterator();
2556 ObjectIterator* next();
2559 ObjectIterator* CreateIterator();
2562 int current_space_; // from enum AllocationSpace.
2563 ObjectIterator* iterator_; // object iterator for the current space.
2564 HeapObjectCallback size_func_;
2568 // A HeapIterator provides iteration over the whole heap. It
2569 // aggregates the specific iterators for the different spaces as
2570 // these can only iterate over one space only.
2572 // HeapIterator ensures there is no allocation during its lifetime
2573 // (using an embedded DisallowHeapAllocation instance).
2575 // HeapIterator can skip free list nodes (that is, de-allocated heap
2576 // objects that still remain in the heap). As implementation of free
2577 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2578 // phases. Also, it is forbidden to interrupt iteration in this mode,
2579 // as this will leave heap objects marked (and thus, unusable).
2580 class HeapObjectsFilter;
2582 class HeapIterator BASE_EMBEDDED {
2584 enum HeapObjectsFiltering { kNoFiltering, kFilterUnreachable };
2586 explicit HeapIterator(Heap* heap);
2587 HeapIterator(Heap* heap, HeapObjectsFiltering filtering);
2594 struct MakeHeapIterableHelper {
2595 explicit MakeHeapIterableHelper(Heap* heap) { heap->MakeHeapIterable(); }
2598 // Perform the initialization.
2600 // Perform all necessary shutdown (destruction) work.
2602 HeapObject* NextObject();
2604 MakeHeapIterableHelper make_heap_iterable_helper_;
2605 DisallowHeapAllocation no_heap_allocation_;
2607 HeapObjectsFiltering filtering_;
2608 HeapObjectsFilter* filter_;
2609 // Space iterator for iterating all the spaces.
2610 SpaceIterator* space_iterator_;
2611 // Object iterator for the space currently being iterated.
2612 ObjectIterator* object_iterator_;
2616 // Cache for mapping (map, property name) into field offset.
2617 // Cleared at startup and prior to mark sweep collection.
2618 class KeyedLookupCache {
2620 // Lookup field offset for (map, name). If absent, -1 is returned.
2621 int Lookup(Handle<Map> map, Handle<Name> name);
2623 // Update an element in the cache.
2624 void Update(Handle<Map> map, Handle<Name> name, int field_offset);
2629 static const int kLength = 256;
2630 static const int kCapacityMask = kLength - 1;
2631 static const int kMapHashShift = 5;
2632 static const int kHashMask = -4; // Zero the last two bits.
2633 static const int kEntriesPerBucket = 4;
2634 static const int kEntryLength = 2;
2635 static const int kMapIndex = 0;
2636 static const int kKeyIndex = 1;
2637 static const int kNotFound = -1;
2639 // kEntriesPerBucket should be a power of 2.
2640 STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2641 STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2644 KeyedLookupCache() {
2645 for (int i = 0; i < kLength; ++i) {
2646 keys_[i].map = NULL;
2647 keys_[i].name = NULL;
2648 field_offsets_[i] = kNotFound;
2652 static inline int Hash(Handle<Map> map, Handle<Name> name);
2654 // Get the address of the keys and field_offsets arrays. Used in
2655 // generated code to perform cache lookups.
2656 Address keys_address() { return reinterpret_cast<Address>(&keys_); }
2658 Address field_offsets_address() {
2659 return reinterpret_cast<Address>(&field_offsets_);
2668 int field_offsets_[kLength];
2670 friend class ExternalReference;
2671 friend class Isolate;
2672 DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2676 // Cache for mapping (map, property name) into descriptor index.
2677 // The cache contains both positive and negative results.
2678 // Descriptor index equals kNotFound means the property is absent.
2679 // Cleared at startup and prior to any gc.
2680 class DescriptorLookupCache {
2682 // Lookup descriptor index for (map, name).
2683 // If absent, kAbsent is returned.
2684 int Lookup(Map* source, Name* name) {
2685 if (!name->IsUniqueName()) return kAbsent;
2686 int index = Hash(source, name);
2687 Key& key = keys_[index];
2688 if ((key.source == source) && (key.name == name)) return results_[index];
2692 // Update an element in the cache.
2693 void Update(Map* source, Name* name, int result) {
2694 DCHECK(result != kAbsent);
2695 if (name->IsUniqueName()) {
2696 int index = Hash(source, name);
2697 Key& key = keys_[index];
2698 key.source = source;
2700 results_[index] = result;
2707 static const int kAbsent = -2;
2710 DescriptorLookupCache() {
2711 for (int i = 0; i < kLength; ++i) {
2712 keys_[i].source = NULL;
2713 keys_[i].name = NULL;
2714 results_[i] = kAbsent;
2718 static int Hash(Object* source, Name* name) {
2719 // Uses only lower 32 bits if pointers are larger.
2720 uint32_t source_hash =
2721 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(source)) >>
2723 uint32_t name_hash =
2724 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >>
2726 return (source_hash ^ name_hash) % kLength;
2729 static const int kLength = 64;
2736 int results_[kLength];
2738 friend class Isolate;
2739 DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2743 class RegExpResultsCache {
2745 enum ResultsCacheType { REGEXP_MULTIPLE_INDICES, STRING_SPLIT_SUBSTRINGS };
2747 // Attempt to retrieve a cached result. On failure, 0 is returned as a Smi.
2748 // On success, the returned result is guaranteed to be a COW-array.
2749 static Object* Lookup(Heap* heap, String* key_string, Object* key_pattern,
2750 ResultsCacheType type);
2751 // Attempt to add value_array to the cache specified by type. On success,
2752 // value_array is turned into a COW-array.
2753 static void Enter(Isolate* isolate, Handle<String> key_string,
2754 Handle<Object> key_pattern, Handle<FixedArray> value_array,
2755 ResultsCacheType type);
2756 static void Clear(FixedArray* cache);
2757 static const int kRegExpResultsCacheSize = 0x100;
2760 static const int kArrayEntriesPerCacheEntry = 4;
2761 static const int kStringOffset = 0;
2762 static const int kPatternOffset = 1;
2763 static const int kArrayOffset = 2;
2767 // Abstract base class for checking whether a weak object should be retained.
2768 class WeakObjectRetainer {
2770 virtual ~WeakObjectRetainer() {}
2772 // Return whether this object should be retained. If NULL is returned the
2773 // object has no references. Otherwise the address of the retained object
2774 // should be returned as in some GC situations the object has been moved.
2775 virtual Object* RetainAs(Object* object) = 0;
2779 // Intrusive object marking uses least significant bit of
2780 // heap object's map word to mark objects.
2781 // Normally all map words have least significant bit set
2782 // because they contain tagged map pointer.
2783 // If the bit is not set object is marked.
2784 // All objects should be unmarked before resuming
2785 // JavaScript execution.
2786 class IntrusiveMarking {
2788 static bool IsMarked(HeapObject* object) {
2789 return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
2792 static void ClearMark(HeapObject* object) {
2793 uintptr_t map_word = object->map_word().ToRawValue();
2794 object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
2795 DCHECK(!IsMarked(object));
2798 static void SetMark(HeapObject* object) {
2799 uintptr_t map_word = object->map_word().ToRawValue();
2800 object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
2801 DCHECK(IsMarked(object));
2804 static Map* MapOfMarkedObject(HeapObject* object) {
2805 uintptr_t map_word = object->map_word().ToRawValue();
2806 return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
2809 static int SizeOfMarkedObject(HeapObject* object) {
2810 return object->SizeFromMap(MapOfMarkedObject(object));
2814 static const uintptr_t kNotMarkedBit = 0x1;
2815 STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0); // NOLINT
2820 // Helper class for tracing paths to a search target Object from all roots.
2821 // The TracePathFrom() method can be used to trace paths from a specific
2822 // object to the search target object.
2823 class PathTracer : public ObjectVisitor {
2826 FIND_ALL, // Will find all matches.
2827 FIND_FIRST // Will stop the search after first match.
2830 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2831 static const int kMarkTag = 2;
2833 // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2834 // after the first match. If FIND_ALL is specified, then tracing will be
2835 // done for all matches.
2836 PathTracer(Object* search_target, WhatToFind what_to_find,
2837 VisitMode visit_mode)
2838 : search_target_(search_target),
2839 found_target_(false),
2840 found_target_in_trace_(false),
2841 what_to_find_(what_to_find),
2842 visit_mode_(visit_mode),
2846 virtual void VisitPointers(Object** start, Object** end);
2849 void TracePathFrom(Object** root);
2851 bool found() const { return found_target_; }
2853 static Object* const kAnyGlobalObject;
2857 class UnmarkVisitor;
2859 void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2860 void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2861 virtual void ProcessResults();
2863 Object* search_target_;
2865 bool found_target_in_trace_;
2866 WhatToFind what_to_find_;
2867 VisitMode visit_mode_;
2868 List<Object*> object_stack_;
2870 DisallowHeapAllocation no_allocation; // i.e. no gc allowed.
2873 DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2877 } // namespace v8::internal
2879 #endif // V8_HEAP_HEAP_H_