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