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