blob: 945745356195522c417e1d7e12c55539cc141e11 [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// 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.
4
5#ifndef V8_HEAP_HEAP_H_
6#define V8_HEAP_HEAP_H_
7
8#include <cmath>
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00009#include <map>
Ben Murdochb8a8cc12014-11-26 15:28:44 +000010
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000011// Clients of this interface shouldn't depend on lots of heap internals.
12// Do not include anything from src/heap here!
Ben Murdochda12d292016-06-02 14:46:10 +010013#include "include/v8.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000014#include "src/allocation.h"
15#include "src/assert-scope.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000016#include "src/atomic-utils.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000017#include "src/globals.h"
Ben Murdoch097c5b22016-05-18 11:27:45 +010018#include "src/heap-symbols.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000019// TODO(mstarzinger): Two more includes to kill!
Ben Murdochb8a8cc12014-11-26 15:28:44 +000020#include "src/heap/spaces.h"
21#include "src/heap/store-buffer.h"
22#include "src/list.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000023
24namespace v8 {
25namespace internal {
26
Ben Murdochda12d292016-06-02 14:46:10 +010027using v8::MemoryPressureLevel;
28
Ben Murdochb8a8cc12014-11-26 15:28:44 +000029// 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. */ \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000036 V(Oddball, undefined_value, UndefinedValue) \
37 V(Oddball, the_hole_value, TheHoleValue) \
38 V(Oddball, null_value, NullValue) \
39 V(Oddball, true_value, TrueValue) \
40 V(Oddball, false_value, FalseValue) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000041 V(String, empty_string, empty_string) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000042 V(Oddball, uninitialized_value, UninitializedValue) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000043 V(Map, cell_map, CellMap) \
44 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
45 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
46 V(Map, meta_map, MetaMap) \
47 V(Map, heap_number_map, HeapNumberMap) \
48 V(Map, mutable_heap_number_map, MutableHeapNumberMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000049 V(Map, float32x4_map, Float32x4Map) \
50 V(Map, int32x4_map, Int32x4Map) \
51 V(Map, uint32x4_map, Uint32x4Map) \
52 V(Map, bool32x4_map, Bool32x4Map) \
53 V(Map, int16x8_map, Int16x8Map) \
54 V(Map, uint16x8_map, Uint16x8Map) \
55 V(Map, bool16x8_map, Bool16x8Map) \
56 V(Map, int8x16_map, Int8x16Map) \
57 V(Map, uint8x16_map, Uint8x16Map) \
58 V(Map, bool8x16_map, Bool8x16Map) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000059 V(Map, native_context_map, NativeContextMap) \
60 V(Map, fixed_array_map, FixedArrayMap) \
61 V(Map, code_map, CodeMap) \
62 V(Map, scope_info_map, ScopeInfoMap) \
63 V(Map, fixed_cow_array_map, FixedCOWArrayMap) \
64 V(Map, fixed_double_array_map, FixedDoubleArrayMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -040065 V(Map, weak_cell_map, WeakCellMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000066 V(Map, transition_array_map, TransitionArrayMap) \
67 V(Map, one_byte_string_map, OneByteStringMap) \
68 V(Map, one_byte_internalized_string_map, OneByteInternalizedStringMap) \
69 V(Map, function_context_map, FunctionContextMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000070 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
71 V(ByteArray, empty_byte_array, EmptyByteArray) \
72 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000073 /* The roots above this line should be boring from a GC point of view. */ \
74 /* This means they are never in new space and never on a page that is */ \
75 /* being compacted. */ \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000076 V(Oddball, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
77 V(Oddball, arguments_marker, ArgumentsMarker) \
78 V(Oddball, exception, Exception) \
79 V(Oddball, termination_exception, TerminationException) \
Ben Murdochda12d292016-06-02 14:46:10 +010080 V(Oddball, optimized_out, OptimizedOut) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000081 V(FixedArray, number_string_cache, NumberStringCache) \
82 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
83 V(Object, instanceof_cache_map, InstanceofCacheMap) \
84 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
85 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
86 V(FixedArray, string_split_cache, StringSplitCache) \
87 V(FixedArray, regexp_multiple_cache, RegExpMultipleCache) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000088 V(Smi, hash_seed, HashSeed) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000089 V(Map, hash_table_map, HashTableMap) \
90 V(Map, ordered_hash_table_map, OrderedHashTableMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000091 V(Map, symbol_map, SymbolMap) \
92 V(Map, string_map, StringMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000093 V(Map, cons_one_byte_string_map, ConsOneByteStringMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000094 V(Map, cons_string_map, ConsStringMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +000095 V(Map, sliced_string_map, SlicedStringMap) \
96 V(Map, sliced_one_byte_string_map, SlicedOneByteStringMap) \
97 V(Map, external_string_map, ExternalStringMap) \
98 V(Map, external_string_with_one_byte_data_map, \
99 ExternalStringWithOneByteDataMap) \
100 V(Map, external_one_byte_string_map, ExternalOneByteStringMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400101 V(Map, native_source_string_map, NativeSourceStringMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000102 V(Map, short_external_string_map, ShortExternalStringMap) \
103 V(Map, short_external_string_with_one_byte_data_map, \
104 ShortExternalStringWithOneByteDataMap) \
105 V(Map, internalized_string_map, InternalizedStringMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000106 V(Map, external_internalized_string_map, ExternalInternalizedStringMap) \
107 V(Map, external_internalized_string_with_one_byte_data_map, \
108 ExternalInternalizedStringWithOneByteDataMap) \
109 V(Map, external_one_byte_internalized_string_map, \
110 ExternalOneByteInternalizedStringMap) \
111 V(Map, short_external_internalized_string_map, \
112 ShortExternalInternalizedStringMap) \
113 V(Map, short_external_internalized_string_with_one_byte_data_map, \
114 ShortExternalInternalizedStringWithOneByteDataMap) \
115 V(Map, short_external_one_byte_internalized_string_map, \
116 ShortExternalOneByteInternalizedStringMap) \
117 V(Map, short_external_one_byte_string_map, ShortExternalOneByteStringMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000118 V(Map, fixed_uint8_array_map, FixedUint8ArrayMap) \
119 V(Map, fixed_int8_array_map, FixedInt8ArrayMap) \
120 V(Map, fixed_uint16_array_map, FixedUint16ArrayMap) \
121 V(Map, fixed_int16_array_map, FixedInt16ArrayMap) \
122 V(Map, fixed_uint32_array_map, FixedUint32ArrayMap) \
123 V(Map, fixed_int32_array_map, FixedInt32ArrayMap) \
124 V(Map, fixed_float32_array_map, FixedFloat32ArrayMap) \
125 V(Map, fixed_float64_array_map, FixedFloat64ArrayMap) \
126 V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap) \
127 V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array) \
128 V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array) \
129 V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array) \
130 V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array) \
131 V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array) \
132 V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array) \
133 V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array) \
134 V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array) \
135 V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array, \
136 EmptyFixedUint8ClampedArray) \
137 V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000138 V(Map, catch_context_map, CatchContextMap) \
139 V(Map, with_context_map, WithContextMap) \
Ben Murdochda12d292016-06-02 14:46:10 +0100140 V(Map, debug_evaluate_context_map, DebugEvaluateContextMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000141 V(Map, block_context_map, BlockContextMap) \
142 V(Map, module_context_map, ModuleContextMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400143 V(Map, script_context_map, ScriptContextMap) \
144 V(Map, script_context_table_map, ScriptContextTableMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000145 V(Map, undefined_map, UndefinedMap) \
146 V(Map, the_hole_map, TheHoleMap) \
147 V(Map, null_map, NullMap) \
148 V(Map, boolean_map, BooleanMap) \
149 V(Map, uninitialized_map, UninitializedMap) \
150 V(Map, arguments_marker_map, ArgumentsMarkerMap) \
151 V(Map, no_interceptor_result_sentinel_map, NoInterceptorResultSentinelMap) \
152 V(Map, exception_map, ExceptionMap) \
153 V(Map, termination_exception_map, TerminationExceptionMap) \
Ben Murdochda12d292016-06-02 14:46:10 +0100154 V(Map, optimized_out_map, OptimizedOutMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000155 V(Map, message_object_map, JSMessageObjectMap) \
156 V(Map, foreign_map, ForeignMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000157 V(Map, neander_map, NeanderMap) \
158 V(Map, external_map, ExternalMap) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000159 V(HeapNumber, nan_value, NanValue) \
160 V(HeapNumber, infinity_value, InfinityValue) \
161 V(HeapNumber, minus_zero_value, MinusZeroValue) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000162 V(HeapNumber, minus_infinity_value, MinusInfinityValue) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000163 V(JSObject, message_listeners, MessageListeners) \
164 V(UnseededNumberDictionary, code_stubs, CodeStubs) \
165 V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
166 V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache) \
167 V(Code, js_entry_code, JsEntryCode) \
168 V(Code, js_construct_entry_code, JsConstructEntryCode) \
169 V(FixedArray, natives_source_cache, NativesSourceCache) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000170 V(FixedArray, experimental_natives_source_cache, \
171 ExperimentalNativesSourceCache) \
172 V(FixedArray, extra_natives_source_cache, ExtraNativesSourceCache) \
173 V(FixedArray, experimental_extra_natives_source_cache, \
174 ExperimentalExtraNativesSourceCache) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000175 V(Script, empty_script, EmptyScript) \
176 V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000177 V(NameDictionary, empty_properties_dictionary, EmptyPropertiesDictionary) \
178 V(Cell, undefined_cell, UndefinedCell) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000179 V(JSObject, observation_state, ObservationState) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000180 V(Object, symbol_registry, SymbolRegistry) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000181 V(Object, script_list, ScriptList) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000182 V(SeededNumberDictionary, empty_slow_element_dictionary, \
183 EmptySlowElementDictionary) \
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000184 V(FixedArray, materialized_objects, MaterializedObjects) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000185 V(FixedArray, microtask_queue, MicrotaskQueue) \
186 V(TypeFeedbackVector, dummy_vector, DummyVector) \
187 V(FixedArray, cleared_optimized_code_map, ClearedOptimizedCodeMap) \
188 V(FixedArray, detached_contexts, DetachedContexts) \
189 V(ArrayList, retained_maps, RetainedMaps) \
190 V(WeakHashTable, weak_object_to_code_table, WeakObjectToCodeTable) \
191 V(PropertyCell, array_protector, ArrayProtector) \
192 V(PropertyCell, empty_property_cell, EmptyPropertyCell) \
193 V(Object, weak_stack_trace_list, WeakStackTraceList) \
194 V(Object, noscript_shared_function_infos, NoScriptSharedFunctionInfos) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000195 V(Map, bytecode_array_map, BytecodeArrayMap) \
196 V(WeakCell, empty_weak_cell, EmptyWeakCell) \
Ben Murdoch097c5b22016-05-18 11:27:45 +0100197 V(PropertyCell, species_protector, SpeciesProtector)
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000198
199// Entries in this list are limited to Smis and are not visited during GC.
200#define SMI_ROOT_LIST(V) \
201 V(Smi, stack_limit, StackLimit) \
202 V(Smi, real_stack_limit, RealStackLimit) \
203 V(Smi, last_script_id, LastScriptId) \
204 V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset) \
205 V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset) \
206 V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset) \
207 V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
208
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000209
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000210#define ROOT_LIST(V) \
211 STRONG_ROOT_LIST(V) \
212 SMI_ROOT_LIST(V) \
213 V(StringTable, string_table, StringTable)
214
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400215
216// Heap roots that are known to be immortal immovable, for which we can safely
217// skip write barriers. This list is not complete and has omissions.
218#define IMMORTAL_IMMOVABLE_ROOT_LIST(V) \
219 V(ByteArrayMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000220 V(BytecodeArrayMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400221 V(FreeSpaceMap) \
222 V(OnePointerFillerMap) \
223 V(TwoPointerFillerMap) \
224 V(UndefinedValue) \
225 V(TheHoleValue) \
226 V(NullValue) \
227 V(TrueValue) \
228 V(FalseValue) \
229 V(UninitializedValue) \
230 V(CellMap) \
231 V(GlobalPropertyCellMap) \
232 V(SharedFunctionInfoMap) \
233 V(MetaMap) \
234 V(HeapNumberMap) \
235 V(MutableHeapNumberMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000236 V(Float32x4Map) \
237 V(Int32x4Map) \
238 V(Uint32x4Map) \
239 V(Bool32x4Map) \
240 V(Int16x8Map) \
241 V(Uint16x8Map) \
242 V(Bool16x8Map) \
243 V(Int8x16Map) \
244 V(Uint8x16Map) \
245 V(Bool8x16Map) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400246 V(NativeContextMap) \
247 V(FixedArrayMap) \
248 V(CodeMap) \
249 V(ScopeInfoMap) \
250 V(FixedCOWArrayMap) \
251 V(FixedDoubleArrayMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400252 V(WeakCellMap) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000253 V(TransitionArrayMap) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400254 V(NoInterceptorResultSentinel) \
255 V(HashTableMap) \
256 V(OrderedHashTableMap) \
257 V(EmptyFixedArray) \
258 V(EmptyByteArray) \
259 V(EmptyDescriptorArray) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400260 V(ArgumentsMarker) \
261 V(SymbolMap) \
262 V(SloppyArgumentsElementsMap) \
263 V(FunctionContextMap) \
264 V(CatchContextMap) \
265 V(WithContextMap) \
266 V(BlockContextMap) \
267 V(ModuleContextMap) \
268 V(ScriptContextMap) \
269 V(UndefinedMap) \
270 V(TheHoleMap) \
271 V(NullMap) \
272 V(BooleanMap) \
273 V(UninitializedMap) \
274 V(ArgumentsMarkerMap) \
275 V(JSMessageObjectMap) \
276 V(ForeignMap) \
277 V(NeanderMap) \
Ben Murdochda12d292016-06-02 14:46:10 +0100278 V(NanValue) \
279 V(InfinityValue) \
280 V(MinusZeroValue) \
281 V(MinusInfinityValue) \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000282 V(EmptyWeakCell) \
283 V(empty_string) \
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400284 PRIVATE_SYMBOL_LIST(V)
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000285
286// Forward declarations.
Ben Murdoch097c5b22016-05-18 11:27:45 +0100287class AllocationObserver;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000288class ArrayBufferTracker;
289class GCIdleTimeAction;
290class GCIdleTimeHandler;
291class GCIdleTimeHeapState;
292class GCTracer;
293class HeapObjectsFilter;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000294class HeapStats;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000295class HistogramTimer;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000296class Isolate;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000297class MemoryReducer;
298class ObjectStats;
299class Scavenger;
300class ScavengeJob;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000301class WeakObjectRetainer;
302
Ben Murdoch097c5b22016-05-18 11:27:45 +0100303typedef void (*ObjectSlotCallback)(HeapObject** from, HeapObject* to);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000304
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000305// A queue of objects promoted during scavenge. Each object is accompanied
306// by it's size to avoid dereferencing a map pointer for scanning.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000307// The last page in to-space is used for the promotion queue. On conflict
308// during scavenge, the promotion queue is allocated externally and all
309// entries are copied to the external queue.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000310class PromotionQueue {
311 public:
312 explicit PromotionQueue(Heap* heap)
313 : front_(NULL),
314 rear_(NULL),
315 limit_(NULL),
316 emergency_stack_(0),
317 heap_(heap) {}
318
319 void Initialize();
320
321 void Destroy() {
322 DCHECK(is_empty());
323 delete emergency_stack_;
324 emergency_stack_ = NULL;
325 }
326
327 Page* GetHeadPage() {
328 return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
329 }
330
331 void SetNewLimit(Address limit) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000332 // If we are already using an emergency stack, we can ignore it.
333 if (emergency_stack_) return;
334
335 // If the limit is not on the same page, we can ignore it.
336 if (Page::FromAllocationTop(limit) != GetHeadPage()) return;
337
Ben Murdochda12d292016-06-02 14:46:10 +0100338 limit_ = reinterpret_cast<struct Entry*>(limit);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000339
340 if (limit_ <= rear_) {
341 return;
342 }
343
344 RelocateQueueHead();
345 }
346
347 bool IsBelowPromotionQueue(Address to_space_top) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000348 // If an emergency stack is used, the to-space address cannot interfere
349 // with the promotion queue.
350 if (emergency_stack_) return true;
351
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000352 // If the given to-space top pointer and the head of the promotion queue
353 // are not on the same page, then the to-space objects are below the
354 // promotion queue.
355 if (GetHeadPage() != Page::FromAddress(to_space_top)) {
356 return true;
357 }
358 // If the to space top pointer is smaller or equal than the promotion
359 // queue head, then the to-space objects are below the promotion queue.
Ben Murdochda12d292016-06-02 14:46:10 +0100360 return reinterpret_cast<struct Entry*>(to_space_top) <= rear_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000361 }
362
363 bool is_empty() {
364 return (front_ == rear_) &&
365 (emergency_stack_ == NULL || emergency_stack_->length() == 0);
366 }
367
Ben Murdochda12d292016-06-02 14:46:10 +0100368 inline void insert(HeapObject* target, int32_t size, bool was_marked_black);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000369
Ben Murdochda12d292016-06-02 14:46:10 +0100370 void remove(HeapObject** target, int32_t* size, bool* was_marked_black) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000371 DCHECK(!is_empty());
372 if (front_ == rear_) {
373 Entry e = emergency_stack_->RemoveLast();
374 *target = e.obj_;
375 *size = e.size_;
Ben Murdochda12d292016-06-02 14:46:10 +0100376 *was_marked_black = e.was_marked_black_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000377 return;
378 }
379
Ben Murdochda12d292016-06-02 14:46:10 +0100380 struct Entry* entry = reinterpret_cast<struct Entry*>(--front_);
381 *target = entry->obj_;
382 *size = entry->size_;
383 *was_marked_black = entry->was_marked_black_;
384
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000385 // Assert no underflow.
386 SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
387 reinterpret_cast<Address>(front_));
388 }
389
390 private:
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000391 struct Entry {
Ben Murdochda12d292016-06-02 14:46:10 +0100392 Entry(HeapObject* obj, int32_t size, bool was_marked_black)
393 : obj_(obj), size_(size), was_marked_black_(was_marked_black) {}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000394
395 HeapObject* obj_;
Ben Murdochda12d292016-06-02 14:46:10 +0100396 int32_t size_ : 31;
397 bool was_marked_black_ : 1;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000398 };
Ben Murdochda12d292016-06-02 14:46:10 +0100399
400 void RelocateQueueHead();
401
402 // The front of the queue is higher in the memory page chain than the rear.
403 struct Entry* front_;
404 struct Entry* rear_;
405 struct Entry* limit_;
406
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000407 List<Entry>* emergency_stack_;
408
409 Heap* heap_;
410
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000411 DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
412};
413
414
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000415enum ArrayStorageAllocationMode {
416 DONT_INITIALIZE_ARRAY_ELEMENTS,
417 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
418};
419
Ben Murdochda12d292016-06-02 14:46:10 +0100420enum class ClearRecordedSlots { kYes, kNo };
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000421
422class Heap {
423 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000424 // Declare all the root indices. This defines the root list order.
425 enum RootListIndex {
426#define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
427 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
428#undef ROOT_INDEX_DECLARATION
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000429
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000430#define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
431 INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
432#undef STRING_DECLARATION
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000433
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000434#define SYMBOL_INDEX_DECLARATION(name) k##name##RootIndex,
435 PRIVATE_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
436#undef SYMBOL_INDEX_DECLARATION
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000437
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000438#define SYMBOL_INDEX_DECLARATION(name, description) k##name##RootIndex,
439 PUBLIC_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
440 WELL_KNOWN_SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
441#undef SYMBOL_INDEX_DECLARATION
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000442
443// Utility type maps
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000444#define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
445 STRUCT_LIST(DECLARE_STRUCT_MAP)
446#undef DECLARE_STRUCT_MAP
447 kStringTableRootIndex,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000448
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000449#define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
450 SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
451#undef ROOT_INDEX_DECLARATION
452 kRootListLength,
453 kStrongRootListLength = kStringTableRootIndex,
454 kSmiRootsStart = kStringTableRootIndex + 1
455 };
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000456
Ben Murdoch097c5b22016-05-18 11:27:45 +0100457 enum FindMementoMode { kForRuntime, kForGC };
458
459 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
460
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000461 // Indicates whether live bytes adjustment is triggered
462 // - from within the GC code before sweeping started (SEQUENTIAL_TO_SWEEPER),
463 // - or from within GC (CONCURRENT_TO_SWEEPER),
464 // - or mutator code (CONCURRENT_TO_SWEEPER).
465 enum InvocationMode { SEQUENTIAL_TO_SWEEPER, CONCURRENT_TO_SWEEPER };
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400466
Ben Murdoch097c5b22016-05-18 11:27:45 +0100467 enum UpdateAllocationSiteMode { kGlobal, kCached };
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000468
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000469 // Taking this lock prevents the GC from entering a phase that relocates
470 // object references.
471 class RelocationLock {
472 public:
473 explicit RelocationLock(Heap* heap) : heap_(heap) {
474 heap_->relocation_mutex_.Lock();
475 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000476
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000477 ~RelocationLock() { heap_->relocation_mutex_.Unlock(); }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000478
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000479 private:
480 Heap* heap_;
481 };
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000482
483 // Support for partial snapshots. After calling this we have a linear
484 // space to write objects in each space.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400485 struct Chunk {
486 uint32_t size;
487 Address start;
488 Address end;
489 };
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400490 typedef List<Chunk> Reservation;
491
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000492 static const intptr_t kMinimumOldGenerationAllocationLimit =
493 8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
494
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000495 static const int kInitalOldGenerationLimitFactor = 2;
496
497#if V8_OS_ANDROID
498 // Don't apply pointer multiplier on Android since it has no swap space and
499 // should instead adapt it's heap size based on available physical memory.
500 static const int kPointerMultiplier = 1;
501#else
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000502 static const int kPointerMultiplier = i::kPointerSize / 4;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000503#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000504
505 // The new space size has to be a power of 2. Sizes are in MB.
506 static const int kMaxSemiSpaceSizeLowMemoryDevice = 1 * kPointerMultiplier;
507 static const int kMaxSemiSpaceSizeMediumMemoryDevice = 4 * kPointerMultiplier;
508 static const int kMaxSemiSpaceSizeHighMemoryDevice = 8 * kPointerMultiplier;
509 static const int kMaxSemiSpaceSizeHugeMemoryDevice = 8 * kPointerMultiplier;
510
511 // The old space size has to be a multiple of Page::kPageSize.
512 // Sizes are in MB.
513 static const int kMaxOldSpaceSizeLowMemoryDevice = 128 * kPointerMultiplier;
514 static const int kMaxOldSpaceSizeMediumMemoryDevice =
515 256 * kPointerMultiplier;
516 static const int kMaxOldSpaceSizeHighMemoryDevice = 512 * kPointerMultiplier;
517 static const int kMaxOldSpaceSizeHugeMemoryDevice = 700 * kPointerMultiplier;
518
519 // The executable size has to be a multiple of Page::kPageSize.
520 // Sizes are in MB.
521 static const int kMaxExecutableSizeLowMemoryDevice = 96 * kPointerMultiplier;
522 static const int kMaxExecutableSizeMediumMemoryDevice =
523 192 * kPointerMultiplier;
524 static const int kMaxExecutableSizeHighMemoryDevice =
525 256 * kPointerMultiplier;
526 static const int kMaxExecutableSizeHugeMemoryDevice =
527 256 * kPointerMultiplier;
528
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000529 static const int kTraceRingBufferSize = 512;
530 static const int kStacktraceBufferSize = 512;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000531
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000532 static const double kMinHeapGrowingFactor;
533 static const double kMaxHeapGrowingFactor;
534 static const double kMaxHeapGrowingFactorMemoryConstrained;
535 static const double kMaxHeapGrowingFactorIdle;
536 static const double kTargetMutatorUtilization;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000537
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000538 static const int kNoGCFlags = 0;
539 static const int kReduceMemoryFootprintMask = 1;
540 static const int kAbortIncrementalMarkingMask = 2;
541 static const int kFinalizeIncrementalMarkingMask = 4;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400542
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000543 // Making the heap iterable requires us to abort incremental marking.
544 static const int kMakeHeapIterableMask = kAbortIncrementalMarkingMask;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400545
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000546 // The roots that have an index less than this are always in old space.
547 static const int kOldSpaceRoots = 0x20;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000548
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000549 // The minimum size of a HeapObject on the heap.
550 static const int kMinObjectSizeInWords = 2;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400551
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000552 STATIC_ASSERT(kUndefinedValueRootIndex ==
553 Internals::kUndefinedValueRootIndex);
Ben Murdochda12d292016-06-02 14:46:10 +0100554 STATIC_ASSERT(kTheHoleValueRootIndex == Internals::kTheHoleValueRootIndex);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000555 STATIC_ASSERT(kNullValueRootIndex == Internals::kNullValueRootIndex);
556 STATIC_ASSERT(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
557 STATIC_ASSERT(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
558 STATIC_ASSERT(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
559
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000560 // Calculates the maximum amount of filler that could be required by the
561 // given alignment.
562 static int GetMaximumFillToAlign(AllocationAlignment alignment);
563 // Calculates the actual amount of filler required for a given address at the
564 // given alignment.
565 static int GetFillToAlign(Address address, AllocationAlignment alignment);
566
567 template <typename T>
568 static inline bool IsOneByte(T t, int chars);
569
570 static void FatalProcessOutOfMemory(const char* location,
571 bool take_snapshot = false);
572
573 static bool RootIsImmortalImmovable(int root_index);
574
575 // Checks whether the space is valid.
576 static bool IsValidAllocationSpace(AllocationSpace space);
577
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000578 // Generated code can embed direct references to non-writable roots if
579 // they are in new space.
580 static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000581
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000582 // Zapping is needed for verify heap, and always done in debug builds.
583 static inline bool ShouldZapGarbage() {
584#ifdef DEBUG
585 return true;
586#else
587#ifdef VERIFY_HEAP
588 return FLAG_verify_heap;
589#else
590 return false;
591#endif
592#endif
593 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000594
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000595 static double HeapGrowingFactor(double gc_speed, double mutator_speed);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000596
597 // Copy block of memory from src to dst. Size of block should be aligned
598 // by pointer size.
599 static inline void CopyBlock(Address dst, Address src, int byte_size);
600
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000601 // Determines a static visitor id based on the given {map} that can then be
602 // stored on the map to facilitate fast dispatch for {StaticVisitorBase}.
603 static int GetStaticVisitorIdForMap(Map* map);
604
605 // Notifies the heap that is ok to start marking or other activities that
606 // should not happen during deserialization.
607 void NotifyDeserializationComplete();
608
609 intptr_t old_generation_allocation_limit() const {
610 return old_generation_allocation_limit_;
611 }
612
613 bool always_allocate() { return always_allocate_scope_count_.Value() != 0; }
614
615 Address* NewSpaceAllocationTopAddress() {
616 return new_space_.allocation_top_address();
617 }
618 Address* NewSpaceAllocationLimitAddress() {
619 return new_space_.allocation_limit_address();
620 }
621
622 Address* OldSpaceAllocationTopAddress() {
623 return old_space_->allocation_top_address();
624 }
625 Address* OldSpaceAllocationLimitAddress() {
626 return old_space_->allocation_limit_address();
627 }
628
629 // TODO(hpayer): There is still a missmatch between capacity and actual
630 // committed memory size.
631 bool CanExpandOldGeneration(int size = 0) {
632 if (force_oom_) return false;
633 return (CommittedOldGenerationMemory() + size) < MaxOldGenerationSize();
634 }
635
636 // Clear the Instanceof cache (used when a prototype changes).
637 inline void ClearInstanceofCache();
638
639 // FreeSpace objects have a null map after deserialization. Update the map.
640 void RepairFreeListsAfterDeserialization();
641
642 // Move len elements within a given array from src_index index to dst_index
643 // index.
644 void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
645
646 // Initialize a filler object to keep the ability to iterate over the heap
Ben Murdochda12d292016-06-02 14:46:10 +0100647 // when introducing gaps within pages. If slots could have been recorded in
648 // the freed area, then pass ClearRecordedSlots::kYes as the mode. Otherwise,
649 // pass ClearRecordedSlots::kNo.
650 void CreateFillerObjectAt(Address addr, int size, ClearRecordedSlots mode);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000651
652 bool CanMoveObjectStart(HeapObject* object);
653
654 // Maintain consistency of live bytes during incremental marking.
655 void AdjustLiveBytes(HeapObject* object, int by, InvocationMode mode);
656
657 // Trim the given array from the left. Note that this relocates the object
658 // start and hence is only valid if there is only a single reference to it.
659 FixedArrayBase* LeftTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
660
661 // Trim the given array from the right.
662 template<Heap::InvocationMode mode>
663 void RightTrimFixedArray(FixedArrayBase* obj, int elements_to_trim);
664
665 // Converts the given boolean condition to JavaScript boolean value.
Ben Murdochda12d292016-06-02 14:46:10 +0100666 inline Oddball* ToBoolean(bool condition);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000667
668 // Check whether the heap is currently iterable.
669 bool IsHeapIterable();
670
671 // Notify the heap that a context has been disposed.
672 int NotifyContextDisposed(bool dependant_context);
673
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000674 void set_native_contexts_list(Object* object) {
675 native_contexts_list_ = object;
676 }
677 Object* native_contexts_list() const { return native_contexts_list_; }
678
679 void set_allocation_sites_list(Object* object) {
680 allocation_sites_list_ = object;
681 }
682 Object* allocation_sites_list() { return allocation_sites_list_; }
683
684 // Used in CreateAllocationSiteStub and the (de)serializer.
685 Object** allocation_sites_list_address() { return &allocation_sites_list_; }
686
687 void set_encountered_weak_collections(Object* weak_collection) {
688 encountered_weak_collections_ = weak_collection;
689 }
690 Object* encountered_weak_collections() const {
691 return encountered_weak_collections_;
692 }
693
694 void set_encountered_weak_cells(Object* weak_cell) {
695 encountered_weak_cells_ = weak_cell;
696 }
697 Object* encountered_weak_cells() const { return encountered_weak_cells_; }
698
699 void set_encountered_transition_arrays(Object* transition_array) {
700 encountered_transition_arrays_ = transition_array;
701 }
702 Object* encountered_transition_arrays() const {
703 return encountered_transition_arrays_;
704 }
705
706 // Number of mark-sweeps.
707 int ms_count() const { return ms_count_; }
708
709 // Checks whether the given object is allowed to be migrated from it's
710 // current space into the given destination space. Used for debugging.
711 inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
712
713 void CheckHandleCount();
714
715 // Number of "runtime allocations" done so far.
716 uint32_t allocations_count() { return allocations_count_; }
717
718 // Print short heap statistics.
719 void PrintShortHeapStatistics();
720
721 inline HeapState gc_state() { return gc_state_; }
722
723 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
724
725 // If an object has an AllocationMemento trailing it, return it, otherwise
726 // return NULL;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100727 template <FindMementoMode mode>
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000728 inline AllocationMemento* FindAllocationMemento(HeapObject* object);
729
730 // Returns false if not able to reserve.
731 bool ReserveSpace(Reservation* reservations);
732
733 //
734 // Support for the API.
735 //
736
737 void CreateApiObjects();
738
739 // Implements the corresponding V8 API function.
740 bool IdleNotification(double deadline_in_seconds);
741 bool IdleNotification(int idle_time_in_ms);
742
Ben Murdochda12d292016-06-02 14:46:10 +0100743 void MemoryPressureNotification(MemoryPressureLevel level,
744 bool is_isolate_locked);
745 void CheckMemoryPressure();
746
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000747 double MonotonicallyIncreasingTimeInMs();
748
749 void RecordStats(HeapStats* stats, bool take_snapshot = false);
750
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000751 // Check new space expansion criteria and expand semispaces if it was hit.
752 void CheckNewSpaceExpansionCriteria();
753
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000754 inline bool HeapIsFullEnoughToStartIncrementalMarking(intptr_t limit) {
755 if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
756
757 intptr_t adjusted_allocation_limit = limit - new_space_.Capacity();
758
759 if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
760
Ben Murdochda12d292016-06-02 14:46:10 +0100761 if (HighMemoryPressure()) return true;
762
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000763 return false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000764 }
765
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000766 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
767
768 // An object should be promoted if the object has survived a
769 // scavenge operation.
770 inline bool ShouldBePromoted(Address old_address, int object_size);
771
772 void ClearNormalizedMapCaches();
773
774 void IncrementDeferredCount(v8::Isolate::UseCounterFeature feature);
775
776 inline bool OldGenerationAllocationLimitReached();
777
778 void QueueMemoryChunkForFree(MemoryChunk* chunk);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 void FreeQueuedChunks(MemoryChunk* list_head);
780 void FreeQueuedChunks();
781 void WaitUntilUnmappingOfFreeChunksCompleted();
782
783 // Completely clear the Instanceof cache (to stop it keeping objects alive
784 // around a GC).
785 inline void CompletelyClearInstanceofCache();
786
787 inline uint32_t HashSeed();
788
789 inline int NextScriptId();
790
791 inline void SetArgumentsAdaptorDeoptPCOffset(int pc_offset);
792 inline void SetConstructStubDeoptPCOffset(int pc_offset);
793 inline void SetGetterStubDeoptPCOffset(int pc_offset);
794 inline void SetSetterStubDeoptPCOffset(int pc_offset);
795
796 // For post mortem debugging.
797 void RememberUnmappedPage(Address page, bool compacted);
798
799 // Global inline caching age: it is incremented on some GCs after context
800 // disposal. We use it to flush inline caches.
801 int global_ic_age() { return global_ic_age_; }
802
803 void AgeInlineCaches() {
804 global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
805 }
806
807 int64_t amount_of_external_allocated_memory() {
808 return amount_of_external_allocated_memory_;
809 }
810
811 void update_amount_of_external_allocated_memory(int64_t delta) {
812 amount_of_external_allocated_memory_ += delta;
813 }
814
815 void DeoptMarkedAllocationSites();
816
817 bool DeoptMaybeTenuredAllocationSites() {
818 return new_space_.IsAtMaximumCapacity() && maximum_size_scavenges_ == 0;
819 }
820
821 void AddWeakObjectToCodeDependency(Handle<HeapObject> obj,
822 Handle<DependentCode> dep);
823
824 DependentCode* LookupWeakObjectToCodeDependency(Handle<HeapObject> obj);
825
826 void AddRetainedMap(Handle<Map> map);
827
828 // This event is triggered after successful allocation of a new object made
829 // by runtime. Allocations of target space for object evacuation do not
830 // trigger the event. In order to track ALL allocations one must turn off
831 // FLAG_inline_new and FLAG_use_allocation_folding.
832 inline void OnAllocationEvent(HeapObject* object, int size_in_bytes);
833
834 // This event is triggered after object is moved to a new place.
835 inline void OnMoveEvent(HeapObject* target, HeapObject* source,
836 int size_in_bytes);
837
838 bool deserialization_complete() const { return deserialization_complete_; }
839
840 bool HasLowAllocationRate();
841 bool HasHighFragmentation();
842 bool HasHighFragmentation(intptr_t used, intptr_t committed);
843
844 void SetOptimizeForLatency() { optimize_for_memory_usage_ = false; }
Ben Murdoch097c5b22016-05-18 11:27:45 +0100845 void SetOptimizeForMemoryUsage();
Ben Murdochda12d292016-06-02 14:46:10 +0100846 bool ShouldOptimizeForMemoryUsage() {
847 return optimize_for_memory_usage_ || HighMemoryPressure();
848 }
849 bool HighMemoryPressure() {
850 return memory_pressure_level_.Value() != MemoryPressureLevel::kNone;
851 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000852
853 // ===========================================================================
854 // Initialization. ===========================================================
855 // ===========================================================================
856
857 // Configure heap size in MB before setup. Return false if the heap has been
858 // set up already.
859 bool ConfigureHeap(int max_semi_space_size, int max_old_space_size,
860 int max_executable_size, size_t code_range_size);
861 bool ConfigureHeapDefault();
862
863 // Prepares the heap, setting up memory areas that are needed in the isolate
864 // without actually creating any objects.
865 bool SetUp();
866
867 // Bootstraps the object heap with the core set of objects required to run.
868 // Returns whether it succeeded.
869 bool CreateHeapObjects();
870
871 // Destroys all memory allocated by the heap.
872 void TearDown();
873
874 // Returns whether SetUp has been called.
875 bool HasBeenSetUp();
876
877 // ===========================================================================
878 // Getters for spaces. =======================================================
879 // ===========================================================================
880
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000881 Address NewSpaceTop() { return new_space_.top(); }
882
883 NewSpace* new_space() { return &new_space_; }
884 OldSpace* old_space() { return old_space_; }
885 OldSpace* code_space() { return code_space_; }
886 MapSpace* map_space() { return map_space_; }
887 LargeObjectSpace* lo_space() { return lo_space_; }
888
889 PagedSpace* paged_space(int idx) {
890 switch (idx) {
891 case OLD_SPACE:
892 return old_space();
893 case MAP_SPACE:
894 return map_space();
895 case CODE_SPACE:
896 return code_space();
897 case NEW_SPACE:
898 case LO_SPACE:
899 UNREACHABLE();
900 }
901 return NULL;
902 }
903
904 Space* space(int idx) {
905 switch (idx) {
906 case NEW_SPACE:
907 return new_space();
908 case LO_SPACE:
909 return lo_space();
910 default:
911 return paged_space(idx);
912 }
913 }
914
915 // Returns name of the space.
916 const char* GetSpaceName(int idx);
917
918 // ===========================================================================
Ben Murdochda12d292016-06-02 14:46:10 +0100919 // API. ======================================================================
920 // ===========================================================================
921
922 void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
923
924 void RegisterExternallyReferencedObject(Object** object);
925
926 // ===========================================================================
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000927 // Getters to other components. ==============================================
928 // ===========================================================================
929
930 GCTracer* tracer() { return tracer_; }
931
Ben Murdochda12d292016-06-02 14:46:10 +0100932 EmbedderHeapTracer* embedder_heap_tracer() { return embedder_heap_tracer_; }
933
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000934 PromotionQueue* promotion_queue() { return &promotion_queue_; }
935
936 inline Isolate* isolate();
937
938 MarkCompactCollector* mark_compact_collector() {
939 return mark_compact_collector_;
940 }
941
942 // ===========================================================================
943 // Root set access. ==========================================================
944 // ===========================================================================
945
946 // Heap root getters.
947#define ROOT_ACCESSOR(type, name, camel_name) inline type* name();
948 ROOT_LIST(ROOT_ACCESSOR)
949#undef ROOT_ACCESSOR
950
951 // Utility type maps.
952#define STRUCT_MAP_ACCESSOR(NAME, Name, name) inline Map* name##_map();
953 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
954#undef STRUCT_MAP_ACCESSOR
955
956#define STRING_ACCESSOR(name, str) inline String* name();
957 INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
958#undef STRING_ACCESSOR
959
960#define SYMBOL_ACCESSOR(name) inline Symbol* name();
961 PRIVATE_SYMBOL_LIST(SYMBOL_ACCESSOR)
962#undef SYMBOL_ACCESSOR
963
964#define SYMBOL_ACCESSOR(name, description) inline Symbol* name();
965 PUBLIC_SYMBOL_LIST(SYMBOL_ACCESSOR)
966 WELL_KNOWN_SYMBOL_LIST(SYMBOL_ACCESSOR)
967#undef SYMBOL_ACCESSOR
968
969 Object* root(RootListIndex index) { return roots_[index]; }
970 Handle<Object> root_handle(RootListIndex index) {
971 return Handle<Object>(&roots_[index]);
972 }
973
974 // Generated code can embed this address to get access to the roots.
975 Object** roots_array_start() { return roots_; }
976
977 // Sets the stub_cache_ (only used when expanding the dictionary).
978 void SetRootCodeStubs(UnseededNumberDictionary* value) {
979 roots_[kCodeStubsRootIndex] = value;
980 }
981
982 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
983 void SetRootNonMonomorphicCache(UnseededNumberDictionary* value) {
984 roots_[kNonMonomorphicCacheRootIndex] = value;
985 }
986
987 void SetRootMaterializedObjects(FixedArray* objects) {
988 roots_[kMaterializedObjectsRootIndex] = objects;
989 }
990
991 void SetRootScriptList(Object* value) {
992 roots_[kScriptListRootIndex] = value;
993 }
994
995 void SetRootStringTable(StringTable* value) {
996 roots_[kStringTableRootIndex] = value;
997 }
998
999 void SetRootNoScriptSharedFunctionInfos(Object* value) {
1000 roots_[kNoScriptSharedFunctionInfosRootIndex] = value;
1001 }
1002
1003 // Set the stack limit in the roots_ array. Some architectures generate
1004 // code that looks here, because it is faster than loading from the static
1005 // jslimit_/real_jslimit_ variable in the StackGuard.
1006 void SetStackLimits();
1007
Ben Murdochda12d292016-06-02 14:46:10 +01001008 // The stack limit is thread-dependent. To be able to reproduce the same
1009 // snapshot blob, we need to reset it before serializing.
1010 void ClearStackLimits();
1011
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001012 // Generated code can treat direct references to this root as constant.
1013 bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1014
1015 Map* MapForFixedTypedArray(ExternalArrayType array_type);
1016 RootListIndex RootIndexForFixedTypedArray(ExternalArrayType array_type);
1017
1018 RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1019 FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1020
1021 void RegisterStrongRoots(Object** start, Object** end);
1022 void UnregisterStrongRoots(Object** start);
1023
1024 // ===========================================================================
1025 // Inline allocation. ========================================================
1026 // ===========================================================================
1027
1028 // Indicates whether inline bump-pointer allocation has been disabled.
1029 bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1030
1031 // Switch whether inline bump-pointer allocation should be used.
1032 void EnableInlineAllocation();
1033 void DisableInlineAllocation();
1034
1035 // ===========================================================================
1036 // Methods triggering GCs. ===================================================
1037 // ===========================================================================
1038
1039 // Performs garbage collection operation.
1040 // Returns whether there is a chance that another major GC could
1041 // collect more garbage.
1042 inline bool CollectGarbage(
1043 AllocationSpace space, const char* gc_reason = NULL,
1044 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1045
1046 // Performs a full garbage collection. If (flags & kMakeHeapIterableMask) is
1047 // non-zero, then the slower precise sweeper is used, which leaves the heap
1048 // in a state where we can iterate over the heap visiting all objects.
1049 void CollectAllGarbage(
1050 int flags = kFinalizeIncrementalMarkingMask, const char* gc_reason = NULL,
1051 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1052
1053 // Last hope GC, should try to squeeze as much as possible.
1054 void CollectAllAvailableGarbage(const char* gc_reason = NULL);
1055
1056 // Reports and external memory pressure event, either performs a major GC or
1057 // completes incremental marking in order to free external resources.
1058 void ReportExternalMemoryPressure(const char* gc_reason = NULL);
1059
1060 // Invoked when GC was requested via the stack guard.
1061 void HandleGCRequest();
1062
1063 // ===========================================================================
1064 // Iterators. ================================================================
1065 // ===========================================================================
1066
1067 // Iterates over all roots in the heap.
1068 void IterateRoots(ObjectVisitor* v, VisitMode mode);
1069 // Iterates over all strong roots in the heap.
1070 void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
1071 // Iterates over entries in the smi roots list. Only interesting to the
1072 // serializer/deserializer, since GC does not care about smis.
1073 void IterateSmiRoots(ObjectVisitor* v);
1074 // Iterates over all the other roots in the heap.
1075 void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
1076
Ben Murdochda12d292016-06-02 14:46:10 +01001077 // Iterate pointers of promoted objects.
1078 void IteratePromotedObject(HeapObject* target, int size,
1079 bool was_marked_black,
1080 ObjectSlotCallback callback);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001081
Ben Murdochda12d292016-06-02 14:46:10 +01001082 void IteratePromotedObjectPointers(HeapObject* object, Address start,
1083 Address end, bool record_slots,
1084 ObjectSlotCallback callback);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001085
1086 // ===========================================================================
1087 // Store buffer API. =========================================================
1088 // ===========================================================================
1089
Ben Murdoch097c5b22016-05-18 11:27:45 +01001090 // Write barrier support for object[offset] = o;
1091 inline void RecordWrite(Object* object, int offset, Object* o);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001092
Ben Murdochda12d292016-06-02 14:46:10 +01001093 Address* store_buffer_top_address() { return store_buffer()->top_address(); }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001094
Ben Murdoch097c5b22016-05-18 11:27:45 +01001095 void ClearRecordedSlot(HeapObject* object, Object** slot);
Ben Murdochda12d292016-06-02 14:46:10 +01001096 void ClearRecordedSlotRange(Address start, Address end);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001097
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001098 // ===========================================================================
1099 // Incremental marking API. ==================================================
1100 // ===========================================================================
1101
1102 // Start incremental marking and ensure that idle time handler can perform
1103 // incremental steps.
1104 void StartIdleIncrementalMarking();
1105
1106 // Starts incremental marking assuming incremental marking is currently
1107 // stopped.
1108 void StartIncrementalMarking(int gc_flags = kNoGCFlags,
1109 const GCCallbackFlags gc_callback_flags =
1110 GCCallbackFlags::kNoGCCallbackFlags,
1111 const char* reason = nullptr);
1112
1113 void FinalizeIncrementalMarkingIfComplete(const char* comment);
1114
1115 bool TryFinalizeIdleIncrementalMarking(double idle_time_in_ms);
1116
Ben Murdochda12d292016-06-02 14:46:10 +01001117 void RegisterReservationsForBlackAllocation(Reservation* reservations);
1118
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001119 IncrementalMarking* incremental_marking() { return incremental_marking_; }
1120
1121 // ===========================================================================
1122 // External string table API. ================================================
1123 // ===========================================================================
1124
1125 // Registers an external string.
1126 inline void RegisterExternalString(String* string);
1127
1128 // Finalizes an external string by deleting the associated external
1129 // data and clearing the resource pointer.
1130 inline void FinalizeExternalString(String* string);
1131
1132 // ===========================================================================
1133 // Methods checking/returning the space of a given object/address. ===========
1134 // ===========================================================================
1135
1136 // Returns whether the object resides in new space.
1137 inline bool InNewSpace(Object* object);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001138 inline bool InFromSpace(Object* object);
1139 inline bool InToSpace(Object* object);
1140
1141 // Returns whether the object resides in old space.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001142 inline bool InOldSpace(Object* object);
1143
1144 // Checks whether an address/object in the heap (including auxiliary
1145 // area and unused area).
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001146 bool Contains(HeapObject* value);
1147
1148 // Checks whether an address/object in a space.
1149 // Currently used by tests, serialization and heap verification only.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001150 bool InSpace(HeapObject* value, AllocationSpace space);
1151
Ben Murdoch097c5b22016-05-18 11:27:45 +01001152 // Slow methods that can be used for verification as they can also be used
1153 // with off-heap Addresses.
1154 bool ContainsSlow(Address addr);
1155 bool InSpaceSlow(Address addr, AllocationSpace space);
1156 inline bool InNewSpaceSlow(Address address);
1157 inline bool InOldSpaceSlow(Address address);
1158
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001159 // ===========================================================================
1160 // Object statistics tracking. ===============================================
1161 // ===========================================================================
1162
1163 // Returns the number of buckets used by object statistics tracking during a
1164 // major GC. Note that the following methods fail gracefully when the bounds
1165 // are exceeded though.
1166 size_t NumberOfTrackedHeapObjectTypes();
1167
1168 // Returns object statistics about count and size at the last major GC.
1169 // Objects are being grouped into buckets that roughly resemble existing
1170 // instance types.
1171 size_t ObjectCountAtLastGC(size_t index);
1172 size_t ObjectSizeAtLastGC(size_t index);
1173
1174 // Retrieves names of buckets used by object statistics tracking.
1175 bool GetObjectTypeName(size_t index, const char** object_type,
1176 const char** object_sub_type);
1177
1178 // ===========================================================================
1179 // GC statistics. ============================================================
1180 // ===========================================================================
1181
Ben Murdochda12d292016-06-02 14:46:10 +01001182 // Returns the maximum amount of memory reserved for the heap.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001183 intptr_t MaxReserved() {
Ben Murdochda12d292016-06-02 14:46:10 +01001184 return 2 * max_semi_space_size_ + max_old_generation_size_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001185 }
1186 int MaxSemiSpaceSize() { return max_semi_space_size_; }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001187 int InitialSemiSpaceSize() { return initial_semispace_size_; }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001188 intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
1189 intptr_t MaxExecutableSize() { return max_executable_size_; }
1190
1191 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
1192 // more spaces are needed until it reaches the limit.
1193 intptr_t Capacity();
1194
1195 // Returns the amount of memory currently committed for the heap.
1196 intptr_t CommittedMemory();
1197
1198 // Returns the amount of memory currently committed for the old space.
1199 intptr_t CommittedOldGenerationMemory();
1200
1201 // Returns the amount of executable memory currently committed for the heap.
1202 intptr_t CommittedMemoryExecutable();
1203
1204 // Returns the amount of phyical memory currently committed for the heap.
1205 size_t CommittedPhysicalMemory();
1206
1207 // Returns the maximum amount of memory ever committed for the heap.
1208 intptr_t MaximumCommittedMemory() { return maximum_committed_; }
1209
1210 // Updates the maximum committed memory for the heap. Should be called
1211 // whenever a space grows.
1212 void UpdateMaximumCommitted();
1213
1214 // Returns the available bytes in space w/o growing.
1215 // Heap doesn't guarantee that it can allocate an object that requires
1216 // all available bytes. Check MaxHeapObjectSize() instead.
1217 intptr_t Available();
1218
1219 // Returns of size of all objects residing in the heap.
1220 intptr_t SizeOfObjects();
1221
1222 void UpdateSurvivalStatistics(int start_new_space_size);
1223
Ben Murdoch097c5b22016-05-18 11:27:45 +01001224 inline void IncrementPromotedObjectsSize(intptr_t object_size) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001225 DCHECK_GE(object_size, 0);
1226 promoted_objects_size_ += object_size;
1227 }
1228 inline intptr_t promoted_objects_size() { return promoted_objects_size_; }
1229
Ben Murdoch097c5b22016-05-18 11:27:45 +01001230 inline void IncrementSemiSpaceCopiedObjectSize(intptr_t object_size) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001231 DCHECK_GE(object_size, 0);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001232 semi_space_copied_object_size_ += object_size;
1233 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001234 inline intptr_t semi_space_copied_object_size() {
1235 return semi_space_copied_object_size_;
1236 }
1237
1238 inline intptr_t SurvivedNewSpaceObjectSize() {
1239 return promoted_objects_size_ + semi_space_copied_object_size_;
1240 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001241
1242 inline void IncrementNodesDiedInNewSpace() { nodes_died_in_new_space_++; }
1243
1244 inline void IncrementNodesCopiedInNewSpace() { nodes_copied_in_new_space_++; }
1245
1246 inline void IncrementNodesPromoted() { nodes_promoted_++; }
1247
Ben Murdoch097c5b22016-05-18 11:27:45 +01001248 inline void IncrementYoungSurvivorsCounter(intptr_t survived) {
1249 DCHECK_GE(survived, 0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001250 survived_last_scavenge_ = survived;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001251 survived_since_last_expansion_ += survived;
1252 }
1253
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001254 inline intptr_t PromotedTotalSize() {
1255 int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1256 if (total > std::numeric_limits<intptr_t>::max()) {
1257 // TODO(erikcorry): Use uintptr_t everywhere we do heap size calculations.
1258 return std::numeric_limits<intptr_t>::max();
1259 }
1260 if (total < 0) return 0;
1261 return static_cast<intptr_t>(total);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001262 }
1263
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001264 void UpdateNewSpaceAllocationCounter() {
1265 new_space_allocation_counter_ = NewSpaceAllocationCounter();
1266 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001267
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001268 size_t NewSpaceAllocationCounter() {
1269 return new_space_allocation_counter_ + new_space()->AllocatedSinceLastGC();
1270 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001271
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001272 // This should be used only for testing.
1273 void set_new_space_allocation_counter(size_t new_value) {
1274 new_space_allocation_counter_ = new_value;
1275 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001276
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001277 void UpdateOldGenerationAllocationCounter() {
1278 old_generation_allocation_counter_ = OldGenerationAllocationCounter();
1279 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001280
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001281 size_t OldGenerationAllocationCounter() {
1282 return old_generation_allocation_counter_ + PromotedSinceLastGC();
1283 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001284
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001285 // This should be used only for testing.
1286 void set_old_generation_allocation_counter(size_t new_value) {
1287 old_generation_allocation_counter_ = new_value;
1288 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001289
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001290 size_t PromotedSinceLastGC() {
1291 return PromotedSpaceSizeOfObjects() - old_generation_size_at_last_gc_;
1292 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001293
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001294 int gc_count() const { return gc_count_; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001295
1296 // Returns the size of objects residing in non new spaces.
1297 intptr_t PromotedSpaceSizeOfObjects();
1298
1299 double total_regexp_code_generated() { return total_regexp_code_generated_; }
1300 void IncreaseTotalRegexpCodeGenerated(int size) {
1301 total_regexp_code_generated_ += size;
1302 }
1303
1304 void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1305 if (is_crankshafted) {
1306 crankshaft_codegen_bytes_generated_ += size;
1307 } else {
1308 full_codegen_bytes_generated_ += size;
1309 }
1310 }
1311
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001312 // ===========================================================================
1313 // Prologue/epilogue callback methods.========================================
1314 // ===========================================================================
1315
1316 void AddGCPrologueCallback(v8::Isolate::GCCallback callback,
1317 GCType gc_type_filter, bool pass_isolate = true);
1318 void RemoveGCPrologueCallback(v8::Isolate::GCCallback callback);
1319
1320 void AddGCEpilogueCallback(v8::Isolate::GCCallback callback,
1321 GCType gc_type_filter, bool pass_isolate = true);
1322 void RemoveGCEpilogueCallback(v8::Isolate::GCCallback callback);
1323
1324 void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1325 void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1326
1327 // ===========================================================================
1328 // Allocation methods. =======================================================
1329 // ===========================================================================
1330
1331 // Creates a filler object and returns a heap object immediately after it.
1332 MUST_USE_RESULT HeapObject* PrecedeWithFiller(HeapObject* object,
1333 int filler_size);
1334
1335 // Creates a filler object if needed for alignment and returns a heap object
1336 // immediately after it. If any space is left after the returned object,
1337 // another filler object is created so the over allocated memory is iterable.
1338 MUST_USE_RESULT HeapObject* AlignWithFiller(HeapObject* object,
1339 int object_size,
1340 int allocation_size,
1341 AllocationAlignment alignment);
1342
1343 // ===========================================================================
1344 // ArrayBuffer tracking. =====================================================
1345 // ===========================================================================
1346
1347 void RegisterNewArrayBuffer(JSArrayBuffer* buffer);
1348 void UnregisterArrayBuffer(JSArrayBuffer* buffer);
1349
1350 inline ArrayBufferTracker* array_buffer_tracker() {
1351 return array_buffer_tracker_;
1352 }
1353
1354 // ===========================================================================
1355 // Allocation site tracking. =================================================
1356 // ===========================================================================
1357
1358 // Updates the AllocationSite of a given {object}. If the global prenuring
1359 // storage is passed as {pretenuring_feedback} the memento found count on
1360 // the corresponding allocation site is immediately updated and an entry
1361 // in the hash map is created. Otherwise the entry (including a the count
1362 // value) is cached on the local pretenuring feedback.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001363 template <UpdateAllocationSiteMode mode>
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001364 inline void UpdateAllocationSite(HeapObject* object,
1365 HashMap* pretenuring_feedback);
1366
1367 // Removes an entry from the global pretenuring storage.
1368 inline void RemoveAllocationSitePretenuringFeedback(AllocationSite* site);
1369
1370 // Merges local pretenuring feedback into the global one. Note that this
1371 // method needs to be called after evacuation, as allocation sites may be
1372 // evacuated and this method resolves forward pointers accordingly.
1373 void MergeAllocationSitePretenuringFeedback(
1374 const HashMap& local_pretenuring_feedback);
1375
1376// =============================================================================
1377
1378#ifdef VERIFY_HEAP
1379 // Verify the heap is in its normal state before or after a GC.
1380 void Verify();
1381#endif
1382
1383#ifdef DEBUG
1384 void set_allocation_timeout(int timeout) { allocation_timeout_ = timeout; }
1385
1386 void TracePathToObjectFrom(Object* target, Object* root);
1387 void TracePathToObject(Object* target);
1388 void TracePathToGlobal();
1389
1390 void Print();
1391 void PrintHandles();
1392
1393 // Report heap statistics.
1394 void ReportHeapStatistics(const char* title);
1395 void ReportCodeStatistics(const char* title);
1396#endif
Ben Murdoch097c5b22016-05-18 11:27:45 +01001397#ifdef ENABLE_SLOW_DCHECKS
1398 int CountHandlesForObject(Object* object);
1399#endif
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001400
1401 private:
1402 class PretenuringScope;
1403 class UnmapFreeMemoryTask;
1404
1405 // External strings table is a place where all external strings are
1406 // registered. We need to keep track of such strings to properly
1407 // finalize them.
1408 class ExternalStringTable {
1409 public:
1410 // Registers an external string.
1411 inline void AddString(String* string);
1412
1413 inline void Iterate(ObjectVisitor* v);
1414
1415 // Restores internal invariant and gets rid of collected strings.
1416 // Must be called after each Iterate() that modified the strings.
1417 void CleanUp();
1418
1419 // Destroys all allocated memory.
1420 void TearDown();
1421
1422 private:
1423 explicit ExternalStringTable(Heap* heap) : heap_(heap) {}
1424
1425 inline void Verify();
1426
1427 inline void AddOldString(String* string);
1428
1429 // Notifies the table that only a prefix of the new list is valid.
1430 inline void ShrinkNewStrings(int position);
1431
1432 // To speed up scavenge collections new space string are kept
1433 // separate from old space strings.
1434 List<Object*> new_space_strings_;
1435 List<Object*> old_space_strings_;
1436
1437 Heap* heap_;
1438
1439 friend class Heap;
1440
1441 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
1442 };
1443
1444 struct StrongRootsList;
1445
1446 struct StringTypeTable {
1447 InstanceType type;
1448 int size;
1449 RootListIndex index;
1450 };
1451
1452 struct ConstantStringTable {
1453 const char* contents;
1454 RootListIndex index;
1455 };
1456
1457 struct StructTable {
1458 InstanceType type;
1459 int size;
1460 RootListIndex index;
1461 };
1462
1463 struct GCCallbackPair {
1464 GCCallbackPair(v8::Isolate::GCCallback callback, GCType gc_type,
1465 bool pass_isolate)
1466 : callback(callback), gc_type(gc_type), pass_isolate(pass_isolate) {}
1467
1468 bool operator==(const GCCallbackPair& other) const {
1469 return other.callback == callback;
1470 }
1471
1472 v8::Isolate::GCCallback callback;
1473 GCType gc_type;
1474 bool pass_isolate;
1475 };
1476
1477 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
1478 Object** pointer);
1479
1480 static const int kInitialStringTableSize = 2048;
1481 static const int kInitialEvalCacheSize = 64;
1482 static const int kInitialNumberStringCacheSize = 256;
1483
1484 static const int kRememberedUnmappedPages = 128;
1485
1486 static const StringTypeTable string_type_table[];
1487 static const ConstantStringTable constant_string_table[];
1488 static const StructTable struct_table[];
1489
1490 static const int kYoungSurvivalRateHighThreshold = 90;
1491 static const int kYoungSurvivalRateAllowedDeviation = 15;
1492 static const int kOldSurvivalRateLowThreshold = 10;
1493
1494 static const int kMaxMarkCompactsInIdleRound = 7;
1495 static const int kIdleScavengeThreshold = 5;
1496
1497 static const int kInitialFeedbackCapacity = 256;
1498
1499 Heap();
1500
1501 static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
1502 Heap* heap, Object** pointer);
1503
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001504 // Selects the proper allocation space based on the pretenuring decision.
1505 static AllocationSpace SelectSpace(PretenureFlag pretenure) {
1506 return (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1507 }
1508
1509#define ROOT_ACCESSOR(type, name, camel_name) \
1510 inline void set_##name(type* value);
1511 ROOT_LIST(ROOT_ACCESSOR)
1512#undef ROOT_ACCESSOR
1513
1514 StoreBuffer* store_buffer() { return &store_buffer_; }
1515
1516 void set_current_gc_flags(int flags) {
1517 current_gc_flags_ = flags;
1518 DCHECK(!ShouldFinalizeIncrementalMarking() ||
1519 !ShouldAbortIncrementalMarking());
1520 }
1521
1522 inline bool ShouldReduceMemory() const {
1523 return current_gc_flags_ & kReduceMemoryFootprintMask;
1524 }
1525
1526 inline bool ShouldAbortIncrementalMarking() const {
1527 return current_gc_flags_ & kAbortIncrementalMarkingMask;
1528 }
1529
1530 inline bool ShouldFinalizeIncrementalMarking() const {
1531 return current_gc_flags_ & kFinalizeIncrementalMarkingMask;
1532 }
1533
1534 void PreprocessStackTraces();
1535
1536 // Checks whether a global GC is necessary
1537 GarbageCollector SelectGarbageCollector(AllocationSpace space,
1538 const char** reason);
1539
1540 // Make sure there is a filler value behind the top of the new space
1541 // so that the GC does not confuse some unintialized/stale memory
1542 // with the allocation memento of the object at the top
1543 void EnsureFillerObjectAtTop();
1544
1545 // Ensure that we have swept all spaces in such a way that we can iterate
1546 // over all objects. May cause a GC.
1547 void MakeHeapIterable();
1548
1549 // Performs garbage collection operation.
1550 // Returns whether there is a chance that another major GC could
1551 // collect more garbage.
1552 bool CollectGarbage(
1553 GarbageCollector collector, const char* gc_reason,
1554 const char* collector_reason,
1555 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1556
1557 // Performs garbage collection
1558 // Returns whether there is a chance another major GC could
1559 // collect more garbage.
1560 bool PerformGarbageCollection(
1561 GarbageCollector collector,
1562 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1563
1564 inline void UpdateOldSpaceLimits();
1565
1566 // Initializes a JSObject based on its map.
1567 void InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties,
1568 Map* map);
1569
1570 // Initializes JSObject body starting at given offset.
1571 void InitializeJSObjectBody(JSObject* obj, Map* map, int start_offset);
1572
1573 void InitializeAllocationMemento(AllocationMemento* memento,
1574 AllocationSite* allocation_site);
1575
1576 bool CreateInitialMaps();
1577 void CreateInitialObjects();
1578
1579 // These five Create*EntryStub functions are here and forced to not be inlined
1580 // because of a gcc-4.4 bug that assigns wrong vtable entries.
1581 NO_INLINE(void CreateJSEntryStub());
1582 NO_INLINE(void CreateJSConstructEntryStub());
1583
1584 void CreateFixedStubs();
1585
1586 HeapObject* DoubleAlignForDeserialization(HeapObject* object, int size);
1587
1588 // Commits from space if it is uncommitted.
1589 void EnsureFromSpaceIsCommitted();
1590
1591 // Uncommit unused semi space.
1592 bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
1593
1594 // Fill in bogus values in from space
1595 void ZapFromSpace();
1596
1597 // Deopts all code that contains allocation instruction which are tenured or
1598 // not tenured. Moreover it clears the pretenuring allocation site statistics.
1599 void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
1600
1601 // Evaluates local pretenuring for the old space and calls
1602 // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
1603 // the old space.
1604 void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
1605
1606 // Record statistics before and after garbage collection.
1607 void ReportStatisticsBeforeGC();
1608 void ReportStatisticsAfterGC();
1609
1610 // Creates and installs the full-sized number string cache.
1611 int FullSizeNumberStringCacheLength();
1612 // Flush the number to string cache.
1613 void FlushNumberStringCache();
1614
1615 // TODO(hpayer): Allocation site pretenuring may make this method obsolete.
1616 // Re-visit incremental marking heuristics.
1617 bool IsHighSurvivalRate() { return high_survival_rate_period_length_ > 0; }
1618
1619 void ConfigureInitialOldGenerationSize();
1620
1621 bool HasLowYoungGenerationAllocationRate();
1622 bool HasLowOldGenerationAllocationRate();
1623 double YoungGenerationMutatorUtilization();
1624 double OldGenerationMutatorUtilization();
1625
1626 void ReduceNewSpaceSize();
1627
1628 bool TryFinalizeIdleIncrementalMarking(
1629 double idle_time_in_ms, size_t size_of_objects,
1630 size_t mark_compact_speed_in_bytes_per_ms);
1631
1632 GCIdleTimeHeapState ComputeHeapState();
1633
1634 bool PerformIdleTimeAction(GCIdleTimeAction action,
1635 GCIdleTimeHeapState heap_state,
1636 double deadline_in_ms);
1637
1638 void IdleNotificationEpilogue(GCIdleTimeAction action,
1639 GCIdleTimeHeapState heap_state, double start_ms,
1640 double deadline_in_ms);
1641
1642 inline void UpdateAllocationsHash(HeapObject* object);
1643 inline void UpdateAllocationsHash(uint32_t value);
1644 void PrintAlloctionsHash();
1645
1646 void AddToRingBuffer(const char* string);
1647 void GetFromRingBuffer(char* buffer);
1648
1649 void CompactRetainedMaps(ArrayList* retained_maps);
1650
Ben Murdochda12d292016-06-02 14:46:10 +01001651 void CollectGarbageOnMemoryPressure(const char* source);
1652
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001653 // Attempt to over-approximate the weak closure by marking object groups and
1654 // implicit references from global handles, but don't atomically complete
1655 // marking. If we continue to mark incrementally, we might have marked
1656 // objects that die later.
1657 void FinalizeIncrementalMarking(const char* gc_reason);
1658
1659 // Returns the timer used for a given GC type.
1660 // - GCScavenger: young generation GC
1661 // - GCCompactor: full GC
1662 // - GCFinalzeMC: finalization of incremental full GC
1663 // - GCFinalizeMCReduceMemory: finalization of incremental full GC with
1664 // memory reduction
1665 HistogramTimer* GCTypeTimer(GarbageCollector collector);
1666
1667 // ===========================================================================
1668 // Pretenuring. ==============================================================
1669 // ===========================================================================
1670
1671 // Pretenuring decisions are made based on feedback collected during new space
1672 // evacuation. Note that between feedback collection and calling this method
1673 // object in old space must not move.
1674 void ProcessPretenuringFeedback();
1675
1676 // ===========================================================================
1677 // Actual GC. ================================================================
1678 // ===========================================================================
1679
1680 // Code that should be run before and after each GC. Includes some
1681 // reporting/verification activities when compiled with DEBUG set.
1682 void GarbageCollectionPrologue();
1683 void GarbageCollectionEpilogue();
1684
1685 // Performs a major collection in the whole heap.
1686 void MarkCompact();
1687
1688 // Code to be run before and after mark-compact.
1689 void MarkCompactPrologue();
1690 void MarkCompactEpilogue();
1691
1692 // Performs a minor collection in new generation.
1693 void Scavenge();
1694
1695 Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
1696
1697 void UpdateNewSpaceReferencesInExternalStringTable(
1698 ExternalStringTableUpdaterCallback updater_func);
1699
1700 void UpdateReferencesInExternalStringTable(
1701 ExternalStringTableUpdaterCallback updater_func);
1702
1703 void ProcessAllWeakReferences(WeakObjectRetainer* retainer);
1704 void ProcessYoungWeakReferences(WeakObjectRetainer* retainer);
1705 void ProcessNativeContexts(WeakObjectRetainer* retainer);
1706 void ProcessAllocationSites(WeakObjectRetainer* retainer);
Ben Murdochda12d292016-06-02 14:46:10 +01001707 void ProcessWeakListRoots(WeakObjectRetainer* retainer);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001708
1709 // ===========================================================================
1710 // GC statistics. ============================================================
1711 // ===========================================================================
1712
1713 inline intptr_t OldGenerationSpaceAvailable() {
1714 return old_generation_allocation_limit_ - PromotedTotalSize();
1715 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001716
1717 // Returns maximum GC pause.
1718 double get_max_gc_pause() { return max_gc_pause_; }
1719
1720 // Returns maximum size of objects alive after GC.
1721 intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1722
1723 // Returns minimal interval between two subsequent collections.
1724 double get_min_in_mutator() { return min_in_mutator_; }
1725
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001726 // Update GC statistics that are tracked on the Heap.
1727 void UpdateCumulativeGCStatistics(double duration, double spent_in_mutator,
1728 double marking_time);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001729
1730 bool MaximumSizeScavenge() { return maximum_size_scavenges_ > 0; }
1731
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001732 // ===========================================================================
1733 // Growing strategy. =========================================================
1734 // ===========================================================================
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001735
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001736 // Decrease the allocation limit if the new limit based on the given
1737 // parameters is lower than the current limit.
1738 void DampenOldGenerationAllocationLimit(intptr_t old_gen_size,
1739 double gc_speed,
1740 double mutator_speed);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001741
1742
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001743 // Calculates the allocation limit based on a given growing factor and a
1744 // given old generation size.
1745 intptr_t CalculateOldGenerationAllocationLimit(double factor,
1746 intptr_t old_gen_size);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001747
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001748 // Sets the allocation limit to trigger the next full garbage collection.
1749 void SetOldGenerationAllocationLimit(intptr_t old_gen_size, double gc_speed,
1750 double mutator_speed);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001751
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001752 // ===========================================================================
1753 // Idle notification. ========================================================
1754 // ===========================================================================
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001755
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001756 bool RecentIdleNotificationHappened();
1757 void ScheduleIdleScavengeIfNeeded(int bytes_allocated);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001758
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001759 // ===========================================================================
1760 // HeapIterator helpers. =====================================================
1761 // ===========================================================================
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001762
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001763 void heap_iterator_start() { heap_iterator_depth_++; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001764
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001765 void heap_iterator_end() { heap_iterator_depth_--; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001766
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001767 bool in_heap_iterator() { return heap_iterator_depth_ > 0; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001768
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001769 // ===========================================================================
1770 // Allocation methods. =======================================================
1771 // ===========================================================================
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001772
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001773 // Returns a deep copy of the JavaScript object.
1774 // Properties and elements are copied too.
1775 // Optionally takes an AllocationSite to be appended in an AllocationMemento.
1776 MUST_USE_RESULT AllocationResult CopyJSObject(JSObject* source,
1777 AllocationSite* site = NULL);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001778
1779 // Allocates a JS Map in the heap.
1780 MUST_USE_RESULT AllocationResult
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001781 AllocateMap(InstanceType instance_type, int instance_size,
1782 ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001783
1784 // Allocates and initializes a new JavaScript object based on a
1785 // constructor.
1786 // If allocation_site is non-null, then a memento is emitted after the object
1787 // that points to the site.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001788 MUST_USE_RESULT AllocationResult AllocateJSObject(
1789 JSFunction* constructor, PretenureFlag pretenure = NOT_TENURED,
1790 AllocationSite* allocation_site = NULL);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001791
1792 // Allocates and initializes a new JavaScript object based on a map.
1793 // Passing an allocation site means that a memento will be created that
1794 // points to the site.
1795 MUST_USE_RESULT AllocationResult
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001796 AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure = NOT_TENURED,
1797 AllocationSite* allocation_site = NULL);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001798
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001799 // Allocates a HeapNumber from value.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001800 MUST_USE_RESULT AllocationResult
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001801 AllocateHeapNumber(double value, MutableMode mode = IMMUTABLE,
1802 PretenureFlag pretenure = NOT_TENURED);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001803
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001804// Allocates SIMD values from the given lane values.
1805#define SIMD_ALLOCATE_DECLARATION(TYPE, Type, type, lane_count, lane_type) \
1806 AllocationResult Allocate##Type(lane_type lanes[lane_count], \
1807 PretenureFlag pretenure = NOT_TENURED);
1808 SIMD128_TYPES(SIMD_ALLOCATE_DECLARATION)
1809#undef SIMD_ALLOCATE_DECLARATION
1810
1811 // Allocates a byte array of the specified length
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001812 MUST_USE_RESULT AllocationResult
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001813 AllocateByteArray(int length, PretenureFlag pretenure = NOT_TENURED);
1814
1815 // Allocates a bytecode array with given contents.
1816 MUST_USE_RESULT AllocationResult
1817 AllocateBytecodeArray(int length, const byte* raw_bytecodes, int frame_size,
1818 int parameter_count, FixedArray* constant_pool);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001819
1820 // Copy the code and scope info part of the code object, but insert
1821 // the provided data as the relocation information.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001822 MUST_USE_RESULT AllocationResult CopyCode(Code* code,
1823 Vector<byte> reloc_info);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001824
1825 MUST_USE_RESULT AllocationResult CopyCode(Code* code);
1826
Ben Murdoch097c5b22016-05-18 11:27:45 +01001827 MUST_USE_RESULT AllocationResult
1828 CopyBytecodeArray(BytecodeArray* bytecode_array);
1829
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001830 // Allocates a fixed array initialized with undefined values
1831 MUST_USE_RESULT AllocationResult
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001832 AllocateFixedArray(int length, PretenureFlag pretenure = NOT_TENURED);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001833
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001834 // Allocate an uninitialized object. The memory is non-executable if the
1835 // hardware and OS allow. This is the single choke-point for allocations
1836 // performed by the runtime and should not be bypassed (to extend this to
1837 // inlined allocations, use the Heap::DisableInlineAllocation() support).
1838 MUST_USE_RESULT inline AllocationResult AllocateRaw(
1839 int size_in_bytes, AllocationSpace space,
1840 AllocationAlignment aligment = kWordAligned);
1841
1842 // Allocates a heap object based on the map.
1843 MUST_USE_RESULT AllocationResult
1844 Allocate(Map* map, AllocationSpace space,
1845 AllocationSite* allocation_site = NULL);
1846
1847 // Allocates a partial map for bootstrapping.
1848 MUST_USE_RESULT AllocationResult
1849 AllocatePartialMap(InstanceType instance_type, int instance_size);
1850
1851 // Allocate a block of memory in the given space (filled with a filler).
1852 // Used as a fall-back for generated code when the space is full.
1853 MUST_USE_RESULT AllocationResult
1854 AllocateFillerObject(int size, bool double_align, AllocationSpace space);
1855
1856 // Allocate an uninitialized fixed array.
1857 MUST_USE_RESULT AllocationResult
1858 AllocateRawFixedArray(int length, PretenureFlag pretenure);
1859
1860 // Allocate an uninitialized fixed double array.
1861 MUST_USE_RESULT AllocationResult
1862 AllocateRawFixedDoubleArray(int length, PretenureFlag pretenure);
1863
1864 // Allocate an initialized fixed array with the given filler value.
1865 MUST_USE_RESULT AllocationResult
1866 AllocateFixedArrayWithFiller(int length, PretenureFlag pretenure,
1867 Object* filler);
1868
1869 // Allocate and partially initializes a String. There are two String
1870 // encodings: one-byte and two-byte. These functions allocate a string of
1871 // the given length and set its map and length fields. The characters of
1872 // the string are uninitialized.
1873 MUST_USE_RESULT AllocationResult
1874 AllocateRawOneByteString(int length, PretenureFlag pretenure);
1875 MUST_USE_RESULT AllocationResult
1876 AllocateRawTwoByteString(int length, PretenureFlag pretenure);
1877
1878 // Allocates an internalized string in old space based on the character
1879 // stream.
1880 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringFromUtf8(
1881 Vector<const char> str, int chars, uint32_t hash_field);
1882
1883 MUST_USE_RESULT inline AllocationResult AllocateOneByteInternalizedString(
1884 Vector<const uint8_t> str, uint32_t hash_field);
1885
1886 MUST_USE_RESULT inline AllocationResult AllocateTwoByteInternalizedString(
1887 Vector<const uc16> str, uint32_t hash_field);
1888
1889 template <bool is_one_byte, typename T>
1890 MUST_USE_RESULT AllocationResult
1891 AllocateInternalizedStringImpl(T t, int chars, uint32_t hash_field);
1892
1893 template <typename T>
1894 MUST_USE_RESULT inline AllocationResult AllocateInternalizedStringImpl(
1895 T t, int chars, uint32_t hash_field);
1896
1897 // Allocates an uninitialized fixed array. It must be filled by the caller.
1898 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedArray(int length);
1899
1900 // Make a copy of src and return it.
1901 MUST_USE_RESULT inline AllocationResult CopyFixedArray(FixedArray* src);
1902
1903 // Make a copy of src, also grow the copy, and return the copy.
1904 MUST_USE_RESULT AllocationResult
1905 CopyFixedArrayAndGrow(FixedArray* src, int grow_by, PretenureFlag pretenure);
1906
Ben Murdoch097c5b22016-05-18 11:27:45 +01001907 // Make a copy of src, also grow the copy, and return the copy.
1908 MUST_USE_RESULT AllocationResult CopyFixedArrayUpTo(FixedArray* src,
1909 int new_len,
1910 PretenureFlag pretenure);
1911
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001912 // Make a copy of src, set the map, and return the copy.
1913 MUST_USE_RESULT AllocationResult
1914 CopyFixedArrayWithMap(FixedArray* src, Map* map);
1915
1916 // Make a copy of src and return it.
1917 MUST_USE_RESULT inline AllocationResult CopyFixedDoubleArray(
1918 FixedDoubleArray* src);
1919
1920 // Computes a single character string where the character has code.
1921 // A cache is used for one-byte (Latin1) codes.
1922 MUST_USE_RESULT AllocationResult
1923 LookupSingleCharacterStringFromCode(uint16_t code);
1924
1925 // Allocate a symbol in old space.
1926 MUST_USE_RESULT AllocationResult AllocateSymbol();
1927
1928 // Allocates an external array of the specified length and type.
1929 MUST_USE_RESULT AllocationResult AllocateFixedTypedArrayWithExternalPointer(
1930 int length, ExternalArrayType array_type, void* external_pointer,
1931 PretenureFlag pretenure);
1932
1933 // Allocates a fixed typed array of the specified length and type.
1934 MUST_USE_RESULT AllocationResult
1935 AllocateFixedTypedArray(int length, ExternalArrayType array_type,
1936 bool initialize, PretenureFlag pretenure);
1937
1938 // Make a copy of src and return it.
1939 MUST_USE_RESULT AllocationResult CopyAndTenureFixedCOWArray(FixedArray* src);
1940
1941 // Make a copy of src, set the map, and return the copy.
1942 MUST_USE_RESULT AllocationResult
1943 CopyFixedDoubleArrayWithMap(FixedDoubleArray* src, Map* map);
1944
1945 // Allocates a fixed double array with uninitialized values. Returns
1946 MUST_USE_RESULT AllocationResult AllocateUninitializedFixedDoubleArray(
1947 int length, PretenureFlag pretenure = NOT_TENURED);
1948
1949 // Allocate empty fixed array.
1950 MUST_USE_RESULT AllocationResult AllocateEmptyFixedArray();
1951
1952 // Allocate empty fixed typed array of given type.
1953 MUST_USE_RESULT AllocationResult
1954 AllocateEmptyFixedTypedArray(ExternalArrayType array_type);
1955
1956 // Allocate a tenured simple cell.
1957 MUST_USE_RESULT AllocationResult AllocateCell(Object* value);
1958
1959 // Allocate a tenured JS global property cell initialized with the hole.
1960 MUST_USE_RESULT AllocationResult AllocatePropertyCell();
1961
1962 MUST_USE_RESULT AllocationResult AllocateWeakCell(HeapObject* value);
1963
1964 MUST_USE_RESULT AllocationResult AllocateTransitionArray(int capacity);
1965
1966 // Allocates a new utility object in the old generation.
1967 MUST_USE_RESULT AllocationResult AllocateStruct(InstanceType type);
1968
1969 // Allocates a new foreign object.
1970 MUST_USE_RESULT AllocationResult
1971 AllocateForeign(Address address, PretenureFlag pretenure = NOT_TENURED);
1972
1973 MUST_USE_RESULT AllocationResult
1974 AllocateCode(int object_size, bool immovable);
1975
1976 MUST_USE_RESULT AllocationResult InternalizeStringWithKey(HashTableKey* key);
1977
1978 MUST_USE_RESULT AllocationResult InternalizeString(String* str);
1979
1980 // ===========================================================================
1981
1982 void set_force_oom(bool value) { force_oom_ = value; }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001983
1984 // The amount of external memory registered through the API kept alive
1985 // by global handles
1986 int64_t amount_of_external_allocated_memory_;
1987
1988 // Caches the amount of external memory registered at the last global gc.
1989 int64_t amount_of_external_allocated_memory_at_last_global_gc_;
1990
1991 // This can be calculated directly from a pointer to the heap; however, it is
1992 // more expedient to get at the isolate directly from within Heap methods.
1993 Isolate* isolate_;
1994
1995 Object* roots_[kRootListLength];
1996
1997 size_t code_range_size_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001998 int max_semi_space_size_;
1999 int initial_semispace_size_;
2000 intptr_t max_old_generation_size_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002001 intptr_t initial_old_generation_size_;
2002 bool old_generation_size_configured_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002003 intptr_t max_executable_size_;
2004 intptr_t maximum_committed_;
2005
2006 // For keeping track of how much data has survived
2007 // scavenge since last new space expansion.
Ben Murdoch097c5b22016-05-18 11:27:45 +01002008 intptr_t survived_since_last_expansion_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002009
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002010 // ... and since the last scavenge.
Ben Murdoch097c5b22016-05-18 11:27:45 +01002011 intptr_t survived_last_scavenge_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002012
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002013 // This is not the depth of nested AlwaysAllocateScope's but rather a single
2014 // count, as scopes can be acquired from multiple tasks (read: threads).
2015 AtomicNumber<size_t> always_allocate_scope_count_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002016
Ben Murdochda12d292016-06-02 14:46:10 +01002017 // Stores the memory pressure level that set by MemoryPressureNotification
2018 // and reset by a mark-compact garbage collection.
2019 AtomicValue<MemoryPressureLevel> memory_pressure_level_;
2020
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002021 // For keeping track of context disposals.
2022 int contexts_disposed_;
2023
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002024 // The length of the retained_maps array at the time of context disposal.
2025 // This separates maps in the retained_maps array that were created before
2026 // and after context disposal.
2027 int number_of_disposed_maps_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002028
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002029 int global_ic_age_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002030
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002031 NewSpace new_space_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002032 OldSpace* old_space_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002033 OldSpace* code_space_;
2034 MapSpace* map_space_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002035 LargeObjectSpace* lo_space_;
2036 HeapState gc_state_;
2037 int gc_post_processing_depth_;
2038 Address new_space_top_after_last_gc_;
2039
2040 // Returns the amount of external memory registered since last global gc.
2041 int64_t PromotedExternalMemorySize();
2042
2043 // How many "runtime allocations" happened.
2044 uint32_t allocations_count_;
2045
2046 // Running hash over allocations performed.
2047 uint32_t raw_allocations_hash_;
2048
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002049 // How many mark-sweep collections happened.
2050 unsigned int ms_count_;
2051
2052 // How many gc happened.
2053 unsigned int gc_count_;
2054
2055 // For post mortem debugging.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002056 int remembered_unmapped_pages_index_;
2057 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
2058
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002059#ifdef DEBUG
2060 // If the --gc-interval flag is set to a positive value, this
2061 // variable holds the value indicating the number of allocations
2062 // remain until the next failure and garbage collection.
2063 int allocation_timeout_;
2064#endif // DEBUG
2065
2066 // Limit that triggers a global GC on the next (normally caused) GC. This
2067 // is checked when we have already decided to do a GC to help determine
2068 // which collector to invoke, before expanding a paged space in the old
2069 // generation and on every allocation in large object space.
2070 intptr_t old_generation_allocation_limit_;
2071
2072 // Indicates that an allocation has failed in the old generation since the
2073 // last GC.
2074 bool old_gen_exhausted_;
2075
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002076 // Indicates that memory usage is more important than latency.
2077 // TODO(ulan): Merge it with memory reducer once chromium:490559 is fixed.
2078 bool optimize_for_memory_usage_;
2079
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002080 // Indicates that inline bump-pointer allocation has been globally disabled
2081 // for all spaces. This is used to disable allocations in generated code.
2082 bool inline_allocation_disabled_;
2083
2084 // Weak list heads, threaded through the objects.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002085 // List heads are initialized lazily and contain the undefined_value at start.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002086 Object* native_contexts_list_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002087 Object* allocation_sites_list_;
2088
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002089 // List of encountered weak collections (JSWeakMap and JSWeakSet) during
2090 // marking. It is initialized during marking, destroyed after marking and
2091 // contains Smi(0) while marking is not active.
2092 Object* encountered_weak_collections_;
2093
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002094 Object* encountered_weak_cells_;
2095
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002096 Object* encountered_transition_arrays_;
2097
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002098 List<GCCallbackPair> gc_epilogue_callbacks_;
2099 List<GCCallbackPair> gc_prologue_callbacks_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002100
2101 // Total RegExp code ever generated
2102 double total_regexp_code_generated_;
2103
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002104 int deferred_counters_[v8::Isolate::kUseCounterFeatureCount];
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002105
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002106 GCTracer* tracer_;
Ben Murdochda12d292016-06-02 14:46:10 +01002107 EmbedderHeapTracer* embedder_heap_tracer_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002108
2109 int high_survival_rate_period_length_;
2110 intptr_t promoted_objects_size_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002111 double promotion_ratio_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002112 double promotion_rate_;
2113 intptr_t semi_space_copied_object_size_;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002114 intptr_t previous_semi_space_copied_object_size_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002115 double semi_space_copied_rate_;
2116 int nodes_died_in_new_space_;
2117 int nodes_copied_in_new_space_;
2118 int nodes_promoted_;
2119
2120 // This is the pretenuring trigger for allocation sites that are in maybe
2121 // tenure state. When we switched to the maximum new space size we deoptimize
2122 // the code that belongs to the allocation site and derive the lifetime
2123 // of the allocation site.
2124 unsigned int maximum_size_scavenges_;
2125
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002126 // Maximum GC pause.
2127 double max_gc_pause_;
2128
2129 // Total time spent in GC.
2130 double total_gc_time_ms_;
2131
2132 // Maximum size of objects alive after GC.
2133 intptr_t max_alive_after_gc_;
2134
2135 // Minimal interval between two subsequent collections.
2136 double min_in_mutator_;
2137
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002138 // Cumulative GC time spent in marking.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002139 double marking_time_;
2140
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002141 // Cumulative GC time spent in sweeping.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002142 double sweeping_time_;
2143
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002144 // Last time an idle notification happened.
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002145 double last_idle_notification_time_;
2146
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002147 // Last time a garbage collection happened.
2148 double last_gc_time_;
2149
2150 Scavenger* scavenge_collector_;
2151
2152 MarkCompactCollector* mark_compact_collector_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002153
2154 StoreBuffer store_buffer_;
2155
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002156 IncrementalMarking* incremental_marking_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002157
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002158 GCIdleTimeHandler* gc_idle_time_handler_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002159
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002160 MemoryReducer* memory_reducer_;
2161
2162 ObjectStats* object_stats_;
2163
2164 ScavengeJob* scavenge_job_;
2165
Ben Murdoch097c5b22016-05-18 11:27:45 +01002166 AllocationObserver* idle_scavenge_observer_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002167
2168 // These two counters are monotomically increasing and never reset.
2169 size_t full_codegen_bytes_generated_;
2170 size_t crankshaft_codegen_bytes_generated_;
2171
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002172 // This counter is increased before each GC and never reset.
2173 // To account for the bytes allocated since the last GC, use the
2174 // NewSpaceAllocationCounter() function.
2175 size_t new_space_allocation_counter_;
2176
2177 // This counter is increased before each GC and never reset. To
2178 // account for the bytes allocated since the last GC, use the
2179 // OldGenerationAllocationCounter() function.
2180 size_t old_generation_allocation_counter_;
2181
2182 // The size of objects in old generation after the last MarkCompact GC.
2183 size_t old_generation_size_at_last_gc_;
2184
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002185 // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2186 // this variable holds the number of garbage collections since the last
2187 // deoptimization triggered by garbage collection.
2188 int gcs_since_last_deopt_;
2189
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002190 // The feedback storage is used to store allocation sites (keys) and how often
2191 // they have been visited (values) by finding a memento behind an object. The
2192 // storage is only alive temporary during a GC. The invariant is that all
2193 // pointers in this map are already fixed, i.e., they do not point to
2194 // forwarding pointers.
2195 HashMap* global_pretenuring_feedback_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002196
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002197 char trace_ring_buffer_[kTraceRingBufferSize];
2198 // If it's not full then the data is from 0 to ring_buffer_end_. If it's
2199 // full then the data is from ring_buffer_end_ to the end of the buffer and
2200 // from 0 to ring_buffer_end_.
2201 bool ring_buffer_full_;
2202 size_t ring_buffer_end_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002203
2204 // Shared state read by the scavenge collector and set by ScavengeObject.
2205 PromotionQueue promotion_queue_;
2206
2207 // Flag is set when the heap has been configured. The heap can be repeatedly
2208 // configured through the API until it is set up.
2209 bool configured_;
2210
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002211 // Currently set GC flags that are respected by all GC components.
2212 int current_gc_flags_;
2213
2214 // Currently set GC callback flags that are used to pass information between
2215 // the embedder and V8's GC.
2216 GCCallbackFlags current_gc_callback_flags_;
2217
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002218 ExternalStringTable external_string_table_;
2219
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002220 MemoryChunk* chunks_queued_for_free_;
2221
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002222 size_t concurrent_unmapping_tasks_active_;
2223
2224 base::Semaphore pending_unmapping_tasks_semaphore_;
2225
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002226 base::Mutex relocation_mutex_;
2227
2228 int gc_callbacks_depth_;
2229
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002230 bool deserialization_complete_;
2231
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002232 StrongRootsList* strong_roots_list_;
2233
2234 ArrayBufferTracker* array_buffer_tracker_;
2235
2236 // The depth of HeapIterator nestings.
2237 int heap_iterator_depth_;
2238
2239 // Used for testing purposes.
2240 bool force_oom_;
2241
2242 // Classes in "heap" can be friends.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002243 friend class AlwaysAllocateScope;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002244 friend class GCCallbacksScope;
2245 friend class GCTracer;
2246 friend class HeapIterator;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002247 friend class IdleScavengeObserver;
2248 friend class IncrementalMarking;
Ben Murdochda12d292016-06-02 14:46:10 +01002249 friend class IteratePromotedObjectsVisitor;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002250 friend class MarkCompactCollector;
2251 friend class MarkCompactMarkingVisitor;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002252 friend class NewSpace;
2253 friend class ObjectStatsVisitor;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002254 friend class Page;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002255 friend class Scavenger;
2256 friend class StoreBuffer;
2257
2258 // The allocator interface.
2259 friend class Factory;
2260
2261 // The Isolate constructs us.
2262 friend class Isolate;
2263
2264 // Used in cctest.
2265 friend class HeapTester;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002266
2267 DISALLOW_COPY_AND_ASSIGN(Heap);
2268};
2269
2270
2271class HeapStats {
2272 public:
2273 static const int kStartMarker = 0xDECADE00;
2274 static const int kEndMarker = 0xDECADE01;
2275
2276 int* start_marker; // 0
2277 int* new_space_size; // 1
2278 int* new_space_capacity; // 2
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002279 intptr_t* old_space_size; // 3
2280 intptr_t* old_space_capacity; // 4
2281 intptr_t* code_space_size; // 5
2282 intptr_t* code_space_capacity; // 6
2283 intptr_t* map_space_size; // 7
2284 intptr_t* map_space_capacity; // 8
2285 intptr_t* lo_space_size; // 9
2286 int* global_handle_count; // 10
2287 int* weak_global_handle_count; // 11
2288 int* pending_global_handle_count; // 12
2289 int* near_death_global_handle_count; // 13
2290 int* free_global_handle_count; // 14
2291 intptr_t* memory_allocator_size; // 15
2292 intptr_t* memory_allocator_capacity; // 16
2293 int* objects_per_type; // 17
2294 int* size_per_type; // 18
2295 int* os_error; // 19
2296 char* last_few_messages; // 20
2297 char* js_stacktrace; // 21
2298 int* end_marker; // 22
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002299};
2300
2301
2302class AlwaysAllocateScope {
2303 public:
2304 explicit inline AlwaysAllocateScope(Isolate* isolate);
2305 inline ~AlwaysAllocateScope();
2306
2307 private:
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002308 Heap* heap_;
2309};
2310
2311
2312// Visitor class to verify interior pointers in spaces that do not contain
2313// or care about intergenerational references. All heap object pointers have to
2314// point into the heap to a location that has a map pointer at its first word.
2315// Caveat: Heap::Contains is an approximation because it can return true for
2316// objects in a heap space but above the allocation pointer.
2317class VerifyPointersVisitor : public ObjectVisitor {
2318 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002319 inline void VisitPointers(Object** start, Object** end) override;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002320};
2321
2322
2323// Verify that all objects are Smis.
2324class VerifySmisVisitor : public ObjectVisitor {
2325 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002326 inline void VisitPointers(Object** start, Object** end) override;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002327};
2328
2329
2330// Space iterator for iterating over all spaces of the heap. Returns each space
2331// in turn, and null when it is done.
2332class AllSpaces BASE_EMBEDDED {
2333 public:
2334 explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2335 Space* next();
2336
2337 private:
2338 Heap* heap_;
2339 int counter_;
2340};
2341
2342
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002343// Space iterator for iterating over all old spaces of the heap: Old space
2344// and code space. Returns each space in turn, and null when it is done.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002345class OldSpaces BASE_EMBEDDED {
2346 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002347 explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002348 OldSpace* next();
2349
2350 private:
2351 Heap* heap_;
2352 int counter_;
2353};
2354
2355
2356// Space iterator for iterating over all the paged spaces of the heap: Map
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002357// space, old space, code space and cell space. Returns
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002358// each space in turn, and null when it is done.
2359class PagedSpaces BASE_EMBEDDED {
2360 public:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002361 explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_SPACE) {}
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002362 PagedSpace* next();
2363
2364 private:
2365 Heap* heap_;
2366 int counter_;
2367};
2368
2369
2370// Space iterator for iterating over all spaces of the heap.
2371// For each space an object iterator is provided. The deallocation of the
2372// returned object iterators is handled by the space iterator.
2373class SpaceIterator : public Malloced {
2374 public:
2375 explicit SpaceIterator(Heap* heap);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002376 virtual ~SpaceIterator();
2377
2378 bool has_next();
2379 ObjectIterator* next();
2380
2381 private:
2382 ObjectIterator* CreateIterator();
2383
2384 Heap* heap_;
2385 int current_space_; // from enum AllocationSpace.
2386 ObjectIterator* iterator_; // object iterator for the current space.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002387};
2388
2389
2390// A HeapIterator provides iteration over the whole heap. It
2391// aggregates the specific iterators for the different spaces as
2392// these can only iterate over one space only.
2393//
2394// HeapIterator ensures there is no allocation during its lifetime
2395// (using an embedded DisallowHeapAllocation instance).
2396//
2397// HeapIterator can skip free list nodes (that is, de-allocated heap
2398// objects that still remain in the heap). As implementation of free
2399// nodes filtering uses GC marks, it can't be used during MS/MC GC
2400// phases. Also, it is forbidden to interrupt iteration in this mode,
2401// as this will leave heap objects marked (and thus, unusable).
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002402class HeapIterator BASE_EMBEDDED {
2403 public:
2404 enum HeapObjectsFiltering { kNoFiltering, kFilterUnreachable };
2405
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002406 explicit HeapIterator(Heap* heap,
2407 HeapObjectsFiltering filtering = kNoFiltering);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002408 ~HeapIterator();
2409
2410 HeapObject* next();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002411
2412 private:
2413 struct MakeHeapIterableHelper {
2414 explicit MakeHeapIterableHelper(Heap* heap) { heap->MakeHeapIterable(); }
2415 };
2416
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002417 HeapObject* NextObject();
2418
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002419 // The following two fields need to be declared in this order. Initialization
2420 // order guarantees that we first make the heap iterable (which may involve
2421 // allocations) and only then lock it down by not allowing further
2422 // allocations.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002423 MakeHeapIterableHelper make_heap_iterable_helper_;
2424 DisallowHeapAllocation no_heap_allocation_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002425
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002426 Heap* heap_;
2427 HeapObjectsFiltering filtering_;
2428 HeapObjectsFilter* filter_;
2429 // Space iterator for iterating all the spaces.
2430 SpaceIterator* space_iterator_;
2431 // Object iterator for the space currently being iterated.
2432 ObjectIterator* object_iterator_;
2433};
2434
2435
2436// Cache for mapping (map, property name) into field offset.
2437// Cleared at startup and prior to mark sweep collection.
2438class KeyedLookupCache {
2439 public:
2440 // Lookup field offset for (map, name). If absent, -1 is returned.
2441 int Lookup(Handle<Map> map, Handle<Name> name);
2442
2443 // Update an element in the cache.
2444 void Update(Handle<Map> map, Handle<Name> name, int field_offset);
2445
2446 // Clear the cache.
2447 void Clear();
2448
2449 static const int kLength = 256;
2450 static const int kCapacityMask = kLength - 1;
2451 static const int kMapHashShift = 5;
2452 static const int kHashMask = -4; // Zero the last two bits.
2453 static const int kEntriesPerBucket = 4;
2454 static const int kEntryLength = 2;
2455 static const int kMapIndex = 0;
2456 static const int kKeyIndex = 1;
2457 static const int kNotFound = -1;
2458
2459 // kEntriesPerBucket should be a power of 2.
2460 STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2461 STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2462
2463 private:
2464 KeyedLookupCache() {
2465 for (int i = 0; i < kLength; ++i) {
2466 keys_[i].map = NULL;
2467 keys_[i].name = NULL;
2468 field_offsets_[i] = kNotFound;
2469 }
2470 }
2471
2472 static inline int Hash(Handle<Map> map, Handle<Name> name);
2473
2474 // Get the address of the keys and field_offsets arrays. Used in
2475 // generated code to perform cache lookups.
2476 Address keys_address() { return reinterpret_cast<Address>(&keys_); }
2477
2478 Address field_offsets_address() {
2479 return reinterpret_cast<Address>(&field_offsets_);
2480 }
2481
2482 struct Key {
2483 Map* map;
2484 Name* name;
2485 };
2486
2487 Key keys_[kLength];
2488 int field_offsets_[kLength];
2489
2490 friend class ExternalReference;
2491 friend class Isolate;
2492 DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2493};
2494
2495
2496// Cache for mapping (map, property name) into descriptor index.
2497// The cache contains both positive and negative results.
2498// Descriptor index equals kNotFound means the property is absent.
2499// Cleared at startup and prior to any gc.
2500class DescriptorLookupCache {
2501 public:
2502 // Lookup descriptor index for (map, name).
2503 // If absent, kAbsent is returned.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002504 inline int Lookup(Map* source, Name* name);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002505
2506 // Update an element in the cache.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002507 inline void Update(Map* source, Name* name, int result);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002508
2509 // Clear the cache.
2510 void Clear();
2511
2512 static const int kAbsent = -2;
2513
2514 private:
2515 DescriptorLookupCache() {
2516 for (int i = 0; i < kLength; ++i) {
2517 keys_[i].source = NULL;
2518 keys_[i].name = NULL;
2519 results_[i] = kAbsent;
2520 }
2521 }
2522
Ben Murdoch097c5b22016-05-18 11:27:45 +01002523 static inline int Hash(Object* source, Name* name);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002524
2525 static const int kLength = 64;
2526 struct Key {
2527 Map* source;
2528 Name* name;
2529 };
2530
2531 Key keys_[kLength];
2532 int results_[kLength];
2533
2534 friend class Isolate;
2535 DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2536};
2537
2538
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002539// Abstract base class for checking whether a weak object should be retained.
2540class WeakObjectRetainer {
2541 public:
2542 virtual ~WeakObjectRetainer() {}
2543
2544 // Return whether this object should be retained. If NULL is returned the
2545 // object has no references. Otherwise the address of the retained object
2546 // should be returned as in some GC situations the object has been moved.
2547 virtual Object* RetainAs(Object* object) = 0;
2548};
2549
2550
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002551#ifdef DEBUG
2552// Helper class for tracing paths to a search target Object from all roots.
2553// The TracePathFrom() method can be used to trace paths from a specific
2554// object to the search target object.
2555class PathTracer : public ObjectVisitor {
2556 public:
2557 enum WhatToFind {
2558 FIND_ALL, // Will find all matches.
2559 FIND_FIRST // Will stop the search after first match.
2560 };
2561
2562 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2563 static const int kMarkTag = 2;
2564
2565 // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2566 // after the first match. If FIND_ALL is specified, then tracing will be
2567 // done for all matches.
2568 PathTracer(Object* search_target, WhatToFind what_to_find,
2569 VisitMode visit_mode)
2570 : search_target_(search_target),
2571 found_target_(false),
2572 found_target_in_trace_(false),
2573 what_to_find_(what_to_find),
2574 visit_mode_(visit_mode),
2575 object_stack_(20),
2576 no_allocation() {}
2577
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002578 void VisitPointers(Object** start, Object** end) override;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002579
2580 void Reset();
2581 void TracePathFrom(Object** root);
2582
2583 bool found() const { return found_target_; }
2584
2585 static Object* const kAnyGlobalObject;
2586
2587 protected:
2588 class MarkVisitor;
2589 class UnmarkVisitor;
2590
2591 void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2592 void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2593 virtual void ProcessResults();
2594
2595 Object* search_target_;
2596 bool found_target_;
2597 bool found_target_in_trace_;
2598 WhatToFind what_to_find_;
2599 VisitMode visit_mode_;
2600 List<Object*> object_stack_;
2601
2602 DisallowHeapAllocation no_allocation; // i.e. no gc allowed.
2603
2604 private:
2605 DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2606};
2607#endif // DEBUG
Ben Murdoch097c5b22016-05-18 11:27:45 +01002608
2609// -----------------------------------------------------------------------------
2610// Allows observation of allocations.
2611class AllocationObserver {
2612 public:
2613 explicit AllocationObserver(intptr_t step_size)
2614 : step_size_(step_size), bytes_to_next_step_(step_size) {
2615 DCHECK(step_size >= kPointerSize);
2616 }
2617 virtual ~AllocationObserver() {}
2618
2619 // Called each time the observed space does an allocation step. This may be
2620 // more frequently than the step_size we are monitoring (e.g. when there are
2621 // multiple observers, or when page or space boundary is encountered.)
2622 void AllocationStep(int bytes_allocated, Address soon_object, size_t size) {
2623 bytes_to_next_step_ -= bytes_allocated;
2624 if (bytes_to_next_step_ <= 0) {
2625 Step(static_cast<int>(step_size_ - bytes_to_next_step_), soon_object,
2626 size);
2627 step_size_ = GetNextStepSize();
2628 bytes_to_next_step_ = step_size_;
2629 }
2630 }
2631
2632 protected:
2633 intptr_t step_size() const { return step_size_; }
2634 intptr_t bytes_to_next_step() const { return bytes_to_next_step_; }
2635
2636 // Pure virtual method provided by the subclasses that gets called when at
2637 // least step_size bytes have been allocated. soon_object is the address just
2638 // allocated (but not yet initialized.) size is the size of the object as
2639 // requested (i.e. w/o the alignment fillers). Some complexities to be aware
2640 // of:
2641 // 1) soon_object will be nullptr in cases where we end up observing an
2642 // allocation that happens to be a filler space (e.g. page boundaries.)
2643 // 2) size is the requested size at the time of allocation. Right-trimming
2644 // may change the object size dynamically.
2645 // 3) soon_object may actually be the first object in an allocation-folding
2646 // group. In such a case size is the size of the group rather than the
2647 // first object.
2648 virtual void Step(int bytes_allocated, Address soon_object, size_t size) = 0;
2649
2650 // Subclasses can override this method to make step size dynamic.
2651 virtual intptr_t GetNextStepSize() { return step_size_; }
2652
2653 intptr_t step_size_;
2654 intptr_t bytes_to_next_step_;
2655
2656 private:
2657 friend class LargeObjectSpace;
2658 friend class NewSpace;
2659 friend class PagedSpace;
2660 DISALLOW_COPY_AND_ASSIGN(AllocationObserver);
2661};
2662
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002663} // namespace internal
2664} // namespace v8
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002665
2666#endif // V8_HEAP_HEAP_H_