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