Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / v8 / src / heap.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #ifndef V8_HEAP_H_
29 #define V8_HEAP_H_
30
31 #include <cmath>
32
33 #include "allocation.h"
34 #include "assert-scope.h"
35 #include "globals.h"
36 #include "incremental-marking.h"
37 #include "list.h"
38 #include "mark-compact.h"
39 #include "objects-visiting.h"
40 #include "spaces.h"
41 #include "splay-tree-inl.h"
42 #include "store-buffer.h"
43 #include "v8-counters.h"
44 #include "v8globals.h"
45
46 namespace v8 {
47 namespace internal {
48
49 // Defines all the roots in Heap.
50 #define STRONG_ROOT_LIST(V)                                                    \
51   V(Map, byte_array_map, ByteArrayMap)                                         \
52   V(Map, free_space_map, FreeSpaceMap)                                         \
53   V(Map, one_pointer_filler_map, OnePointerFillerMap)                          \
54   V(Map, two_pointer_filler_map, TwoPointerFillerMap)                          \
55   /* Cluster the most popular ones in a few cache lines here at the top.    */ \
56   V(Smi, store_buffer_top, StoreBufferTop)                                     \
57   V(Oddball, undefined_value, UndefinedValue)                                  \
58   V(Oddball, the_hole_value, TheHoleValue)                                     \
59   V(Oddball, null_value, NullValue)                                            \
60   V(Oddball, true_value, TrueValue)                                            \
61   V(Oddball, false_value, FalseValue)                                          \
62   V(Oddball, uninitialized_value, UninitializedValue)                          \
63   V(Map, cell_map, CellMap)                                                    \
64   V(Map, global_property_cell_map, GlobalPropertyCellMap)                      \
65   V(Map, shared_function_info_map, SharedFunctionInfoMap)                      \
66   V(Map, meta_map, MetaMap)                                                    \
67   V(Map, heap_number_map, HeapNumberMap)                                       \
68   V(Map, float32x4_map, Float32x4Map)                                          \
69   V(Map, int32x4_map, Int32x4Map)                                              \
70   V(Map, native_context_map, NativeContextMap)                                 \
71   V(Map, fixed_array_map, FixedArrayMap)                                       \
72   V(Map, code_map, CodeMap)                                                    \
73   V(Map, scope_info_map, ScopeInfoMap)                                         \
74   V(Map, fixed_cow_array_map, FixedCOWArrayMap)                                \
75   V(Map, fixed_double_array_map, FixedDoubleArrayMap)                          \
76   V(Map, constant_pool_array_map, ConstantPoolArrayMap)                        \
77   V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel)       \
78   V(Map, hash_table_map, HashTableMap)                                         \
79   V(FixedArray, empty_fixed_array, EmptyFixedArray)                            \
80   V(ByteArray, empty_byte_array, EmptyByteArray)                               \
81   V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray)             \
82   V(ConstantPoolArray, empty_constant_pool_array, EmptyConstantPoolArray)      \
83   V(Oddball, arguments_marker, ArgumentsMarker)                                \
84   /* The roots above this line should be boring from a GC point of view.    */ \
85   /* This means they are never in new space and never on a page that is     */ \
86   /* being compacted.                                                       */ \
87   V(FixedArray, number_string_cache, NumberStringCache)                        \
88   V(Object, instanceof_cache_function, InstanceofCacheFunction)                \
89   V(Object, instanceof_cache_map, InstanceofCacheMap)                          \
90   V(Object, instanceof_cache_answer, InstanceofCacheAnswer)                    \
91   V(FixedArray, single_character_string_cache, SingleCharacterStringCache)     \
92   V(FixedArray, string_split_cache, StringSplitCache)                          \
93   V(FixedArray, regexp_multiple_cache, RegExpMultipleCache)                    \
94   V(Object, termination_exception, TerminationException)                       \
95   V(Smi, hash_seed, HashSeed)                                                  \
96   V(Map, symbol_map, SymbolMap)                                                \
97   V(Map, string_map, StringMap)                                                \
98   V(Map, ascii_string_map, AsciiStringMap)                                     \
99   V(Map, cons_string_map, ConsStringMap)                                       \
100   V(Map, cons_ascii_string_map, ConsAsciiStringMap)                            \
101   V(Map, sliced_string_map, SlicedStringMap)                                   \
102   V(Map, sliced_ascii_string_map, SlicedAsciiStringMap)                        \
103   V(Map, external_string_map, ExternalStringMap)                               \
104   V(Map,                                                                       \
105     external_string_with_one_byte_data_map,                                    \
106     ExternalStringWithOneByteDataMap)                                          \
107   V(Map, external_ascii_string_map, ExternalAsciiStringMap)                    \
108   V(Map, short_external_string_map, ShortExternalStringMap)                    \
109   V(Map,                                                                       \
110     short_external_string_with_one_byte_data_map,                              \
111     ShortExternalStringWithOneByteDataMap)                                     \
112   V(Map, internalized_string_map, InternalizedStringMap)                       \
113   V(Map, ascii_internalized_string_map, AsciiInternalizedStringMap)            \
114   V(Map, cons_internalized_string_map, ConsInternalizedStringMap)              \
115   V(Map, cons_ascii_internalized_string_map, ConsAsciiInternalizedStringMap)   \
116   V(Map,                                                                       \
117     external_internalized_string_map,                                          \
118     ExternalInternalizedStringMap)                                             \
119   V(Map,                                                                       \
120     external_internalized_string_with_one_byte_data_map,                       \
121     ExternalInternalizedStringWithOneByteDataMap)                              \
122   V(Map,                                                                       \
123     external_ascii_internalized_string_map,                                    \
124     ExternalAsciiInternalizedStringMap)                                        \
125   V(Map,                                                                       \
126     short_external_internalized_string_map,                                    \
127     ShortExternalInternalizedStringMap)                                        \
128   V(Map,                                                                       \
129     short_external_internalized_string_with_one_byte_data_map,                 \
130     ShortExternalInternalizedStringWithOneByteDataMap)                         \
131   V(Map,                                                                       \
132     short_external_ascii_internalized_string_map,                              \
133     ShortExternalAsciiInternalizedStringMap)                                   \
134   V(Map, short_external_ascii_string_map, ShortExternalAsciiStringMap)         \
135   V(Map, undetectable_string_map, UndetectableStringMap)                       \
136   V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap)            \
137   V(Map, external_int8_array_map, ExternalInt8ArrayMap)                        \
138   V(Map, external_uint8_array_map, ExternalUint8ArrayMap)                      \
139   V(Map, external_int16_array_map, ExternalInt16ArrayMap)                      \
140   V(Map, external_uint16_array_map, ExternalUint16ArrayMap)                    \
141   V(Map, external_int32_array_map, ExternalInt32ArrayMap)                      \
142   V(Map, external_int32x4_array_map, ExternalInt32x4ArrayMap)                  \
143   V(Map, external_uint32_array_map, ExternalUint32ArrayMap)                    \
144   V(Map, external_float32_array_map, ExternalFloat32ArrayMap)                  \
145   V(Map, external_float32x4_array_map, ExternalFloat32x4ArrayMap)              \
146   V(Map, external_float64_array_map, ExternalFloat64ArrayMap)                  \
147   V(Map, external_uint8_clamped_array_map, ExternalUint8ClampedArrayMap)       \
148   V(ExternalArray, empty_external_int8_array,                                  \
149       EmptyExternalInt8Array)                                                  \
150   V(ExternalArray, empty_external_uint8_array,                                 \
151       EmptyExternalUint8Array)                                                 \
152   V(ExternalArray, empty_external_int16_array, EmptyExternalInt16Array)        \
153   V(ExternalArray, empty_external_uint16_array,                                \
154       EmptyExternalUint16Array)                                                \
155   V(ExternalArray, empty_external_int32_array, EmptyExternalInt32Array)        \
156   V(ExternalArray, empty_external_int32x4_array, EmptyExternalInt32x4Array)    \
157   V(ExternalArray, empty_external_uint32_array,                                \
158       EmptyExternalUint32Array)                                                \
159   V(ExternalArray, empty_external_float32_array, EmptyExternalFloat32Array)    \
160   V(ExternalArray, empty_external_float32x4_array, EmptyExternalFloat32x4Array)\
161   V(ExternalArray, empty_external_float64_array, EmptyExternalFloat64Array)    \
162   V(ExternalArray, empty_external_uint8_clamped_array,                         \
163       EmptyExternalUint8ClampedArray)                                          \
164   V(Map, fixed_uint8_array_map, FixedUint8ArrayMap)                            \
165   V(Map, fixed_int8_array_map, FixedInt8ArrayMap)                              \
166   V(Map, fixed_uint16_array_map, FixedUint16ArrayMap)                          \
167   V(Map, fixed_int16_array_map, FixedInt16ArrayMap)                            \
168   V(Map, fixed_uint32_array_map, FixedUint32ArrayMap)                          \
169   V(Map, fixed_int32_array_map, FixedInt32ArrayMap)                            \
170   V(Map, fixed_int32x4_array_map, FixedInt32x4ArrayMap)                        \
171   V(Map, fixed_float32_array_map, FixedFloat32ArrayMap)                        \
172   V(Map, fixed_float32x4_array_map, FixedFloat32x4ArrayMap)                    \
173   V(Map, fixed_float64_array_map, FixedFloat64ArrayMap)                        \
174   V(Map, fixed_uint8_clamped_array_map, FixedUint8ClampedArrayMap)             \
175   V(FixedTypedArrayBase, empty_fixed_uint8_array, EmptyFixedUint8Array)        \
176   V(FixedTypedArrayBase, empty_fixed_int8_array, EmptyFixedInt8Array)          \
177   V(FixedTypedArrayBase, empty_fixed_uint16_array, EmptyFixedUint16Array)      \
178   V(FixedTypedArrayBase, empty_fixed_int16_array, EmptyFixedInt16Array)        \
179   V(FixedTypedArrayBase, empty_fixed_uint32_array, EmptyFixedUint32Array)      \
180   V(FixedTypedArrayBase, empty_fixed_int32_array, EmptyFixedInt32Array)        \
181   V(FixedTypedArrayBase, empty_fixed_float32_array, EmptyFixedFloat32Array)    \
182   V(FixedTypedArrayBase, empty_fixed_float32x4_array,                          \
183       EmptyFixedFloat32x4Array)                                                \
184   V(FixedTypedArrayBase, empty_fixed_int32x4_array, EmptyFixedInt32x4Array)    \
185   V(FixedTypedArrayBase, empty_fixed_float64_array, EmptyFixedFloat64Array)    \
186   V(FixedTypedArrayBase, empty_fixed_uint8_clamped_array,                      \
187       EmptyFixedUint8ClampedArray)                                             \
188   V(Map, sloppy_arguments_elements_map, SloppyArgumentsElementsMap)            \
189   V(Map, function_context_map, FunctionContextMap)                             \
190   V(Map, catch_context_map, CatchContextMap)                                   \
191   V(Map, with_context_map, WithContextMap)                                     \
192   V(Map, block_context_map, BlockContextMap)                                   \
193   V(Map, module_context_map, ModuleContextMap)                                 \
194   V(Map, global_context_map, GlobalContextMap)                                 \
195   V(Map, oddball_map, OddballMap)                                              \
196   V(Map, message_object_map, JSMessageObjectMap)                               \
197   V(Map, foreign_map, ForeignMap)                                              \
198   V(HeapNumber, nan_value, NanValue)                                           \
199   V(HeapNumber, infinity_value, InfinityValue)                                 \
200   V(HeapNumber, minus_zero_value, MinusZeroValue)                              \
201   V(Map, neander_map, NeanderMap)                                              \
202   V(JSObject, message_listeners, MessageListeners)                             \
203   V(UnseededNumberDictionary, code_stubs, CodeStubs)                           \
204   V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache)      \
205   V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache)        \
206   V(Code, js_entry_code, JsEntryCode)                                          \
207   V(Code, js_construct_entry_code, JsConstructEntryCode)                       \
208   V(FixedArray, natives_source_cache, NativesSourceCache)                      \
209   V(Script, empty_script, EmptyScript)                                         \
210   V(NameDictionary, intrinsic_function_names, IntrinsicFunctionNames)          \
211   V(Cell, undefined_cell, UndefineCell)                                        \
212   V(JSObject, observation_state, ObservationState)                             \
213   V(Map, external_map, ExternalMap)                                            \
214   V(Object, symbol_registry, SymbolRegistry)                                   \
215   V(Symbol, frozen_symbol, FrozenSymbol)                                       \
216   V(Symbol, nonexistent_symbol, NonExistentSymbol)                             \
217   V(Symbol, elements_transition_symbol, ElementsTransitionSymbol)              \
218   V(SeededNumberDictionary, empty_slow_element_dictionary,                     \
219       EmptySlowElementDictionary)                                              \
220   V(Symbol, observed_symbol, ObservedSymbol)                                   \
221   V(Symbol, uninitialized_symbol, UninitializedSymbol)                         \
222   V(Symbol, megamorphic_symbol, MegamorphicSymbol)                             \
223   V(FixedArray, materialized_objects, MaterializedObjects)                     \
224   V(FixedArray, allocation_sites_scratchpad, AllocationSitesScratchpad)        \
225   V(JSObject, microtask_state, MicrotaskState)
226
227 // Entries in this list are limited to Smis and are not visited during GC.
228 #define SMI_ROOT_LIST(V)                                                       \
229   V(Smi, stack_limit, StackLimit)                                              \
230   V(Smi, real_stack_limit, RealStackLimit)                                     \
231   V(Smi, last_script_id, LastScriptId)                                         \
232   V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset)     \
233   V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset)           \
234   V(Smi, getter_stub_deopt_pc_offset, GetterStubDeoptPCOffset)                 \
235   V(Smi, setter_stub_deopt_pc_offset, SetterStubDeoptPCOffset)
236
237 #define ROOT_LIST(V)                                  \
238   STRONG_ROOT_LIST(V)                                 \
239   SMI_ROOT_LIST(V)                                    \
240   V(StringTable, string_table, StringTable)
241
242 // Heap roots that are known to be immortal immovable, for which we can safely
243 // skip write barriers.
244 #define IMMORTAL_IMMOVABLE_ROOT_LIST(V)   \
245   V(byte_array_map)                       \
246   V(free_space_map)                       \
247   V(one_pointer_filler_map)               \
248   V(two_pointer_filler_map)               \
249   V(undefined_value)                      \
250   V(the_hole_value)                       \
251   V(null_value)                           \
252   V(true_value)                           \
253   V(false_value)                          \
254   V(uninitialized_value)                  \
255   V(cell_map)                             \
256   V(global_property_cell_map)             \
257   V(shared_function_info_map)             \
258   V(meta_map)                             \
259   V(heap_number_map)                      \
260   V(native_context_map)                   \
261   V(fixed_array_map)                      \
262   V(code_map)                             \
263   V(scope_info_map)                       \
264   V(fixed_cow_array_map)                  \
265   V(fixed_double_array_map)               \
266   V(constant_pool_array_map)              \
267   V(no_interceptor_result_sentinel)       \
268   V(hash_table_map)                       \
269   V(empty_fixed_array)                    \
270   V(empty_byte_array)                     \
271   V(empty_descriptor_array)               \
272   V(empty_constant_pool_array)            \
273   V(arguments_marker)                     \
274   V(symbol_map)                           \
275   V(sloppy_arguments_elements_map)        \
276   V(function_context_map)                 \
277   V(catch_context_map)                    \
278   V(with_context_map)                     \
279   V(block_context_map)                    \
280   V(module_context_map)                   \
281   V(global_context_map)                   \
282   V(oddball_map)                          \
283   V(message_object_map)                   \
284   V(foreign_map)                          \
285   V(neander_map)
286
287 #define INTERNALIZED_STRING_LIST(V)                                      \
288   V(Array_string, "Array")                                               \
289   V(Object_string, "Object")                                             \
290   V(proto_string, "__proto__")                                           \
291   V(arguments_string, "arguments")                                       \
292   V(Arguments_string, "Arguments")                                       \
293   V(call_string, "call")                                                 \
294   V(apply_string, "apply")                                               \
295   V(caller_string, "caller")                                             \
296   V(boolean_string, "boolean")                                           \
297   V(Boolean_string, "Boolean")                                           \
298   V(callee_string, "callee")                                             \
299   V(constructor_string, "constructor")                                   \
300   V(dot_result_string, ".result")                                        \
301   V(dot_for_string, ".for.")                                             \
302   V(dot_iterator_string, ".iterator")                                    \
303   V(dot_generator_object_string, ".generator_object")                    \
304   V(eval_string, "eval")                                                 \
305   V(empty_string, "")                                                    \
306   V(function_string, "function")                                         \
307   V(length_string, "length")                                             \
308   V(module_string, "module")                                             \
309   V(name_string, "name")                                                 \
310   V(native_string, "native")                                             \
311   V(null_string, "null")                                                 \
312   V(number_string, "number")                                             \
313   V(Number_string, "Number")                                             \
314   V(float32x4_string, "float32x4")                                       \
315   V(int32x4_string, "int32x4")                                           \
316   V(nan_string, "NaN")                                                   \
317   V(RegExp_string, "RegExp")                                             \
318   V(source_string, "source")                                             \
319   V(global_string, "global")                                             \
320   V(ignore_case_string, "ignoreCase")                                    \
321   V(multiline_string, "multiline")                                       \
322   V(input_string, "input")                                               \
323   V(index_string, "index")                                               \
324   V(last_index_string, "lastIndex")                                      \
325   V(object_string, "object")                                             \
326   V(literals_string, "literals")                                         \
327   V(prototype_string, "prototype")                                       \
328   V(string_string, "string")                                             \
329   V(String_string, "String")                                             \
330   V(symbol_string, "symbol")                                             \
331   V(Symbol_string, "Symbol")                                             \
332   V(for_string, "for")                                                   \
333   V(for_api_string, "for_api")                                           \
334   V(for_intern_string, "for_intern")                                     \
335   V(private_api_string, "private_api")                                   \
336   V(private_intern_string, "private_intern")                             \
337   V(Date_string, "Date")                                                 \
338   V(this_string, "this")                                                 \
339   V(to_string_string, "toString")                                        \
340   V(char_at_string, "CharAt")                                            \
341   V(undefined_string, "undefined")                                       \
342   V(value_of_string, "valueOf")                                          \
343   V(stack_string, "stack")                                               \
344   V(toJSON_string, "toJSON")                                             \
345   V(InitializeVarGlobal_string, "InitializeVarGlobal")                   \
346   V(InitializeConstGlobal_string, "InitializeConstGlobal")               \
347   V(KeyedLoadElementMonomorphic_string,                                  \
348     "KeyedLoadElementMonomorphic")                                       \
349   V(KeyedStoreElementMonomorphic_string,                                 \
350     "KeyedStoreElementMonomorphic")                                      \
351   V(stack_overflow_string, "kStackOverflowBoilerplate")                  \
352   V(illegal_access_string, "illegal access")                             \
353   V(illegal_execution_state_string, "illegal execution state")           \
354   V(get_string, "get")                                                   \
355   V(set_string, "set")                                                   \
356   V(map_field_string, "%map")                                            \
357   V(elements_field_string, "%elements")                                  \
358   V(length_field_string, "%length")                                      \
359   V(cell_value_string, "%cell_value")                                    \
360   V(function_class_string, "Function")                                   \
361   V(illegal_argument_string, "illegal argument")                         \
362   V(MakeReferenceError_string, "MakeReferenceError")                     \
363   V(MakeSyntaxError_string, "MakeSyntaxError")                           \
364   V(MakeTypeError_string, "MakeTypeError")                               \
365   V(unknown_label_string, "unknown_label")                               \
366   V(space_string, " ")                                                   \
367   V(exec_string, "exec")                                                 \
368   V(zero_string, "0")                                                    \
369   V(global_eval_string, "GlobalEval")                                    \
370   V(identity_hash_string, "v8::IdentityHash")                            \
371   V(closure_string, "(closure)")                                         \
372   V(use_strict_string, "use strict")                                     \
373   V(dot_string, ".")                                                     \
374   V(anonymous_function_string, "(anonymous function)")                   \
375   V(compare_ic_string, "==")                                             \
376   V(strict_compare_ic_string, "===")                                     \
377   V(infinity_string, "Infinity")                                         \
378   V(minus_infinity_string, "-Infinity")                                  \
379   V(hidden_stack_trace_string, "v8::hidden_stack_trace")                 \
380   V(query_colon_string, "(?:)")                                          \
381   V(Generator_string, "Generator")                                       \
382   V(throw_string, "throw")                                               \
383   V(done_string, "done")                                                 \
384   V(value_string, "value")                                               \
385   V(signMask, "signMask")                                                \
386   V(x, "x")                                                              \
387   V(y, "y")                                                              \
388   V(z, "z")                                                              \
389   V(w, "w")                                                              \
390   V(flagX, "flagX")                                                      \
391   V(flagY, "flagY")                                                      \
392   V(flagZ, "flagZ")                                                      \
393   V(flagW, "flagW")                                                      \
394   V(simd, "SIMD")                                                        \
395   V(next_string, "next")                                                 \
396   V(byte_length_string, "byteLength")                                    \
397   V(byte_offset_string, "byteOffset")                                    \
398   V(buffer_string, "buffer")                                             \
399   V(intl_initialized_marker_string, "v8::intl_initialized_marker")       \
400   V(intl_impl_object_string, "v8::intl_object")
401
402 // Forward declarations.
403 class GCTracer;
404 class HeapStats;
405 class Isolate;
406 class WeakObjectRetainer;
407
408
409 typedef String* (*ExternalStringTableUpdaterCallback)(Heap* heap,
410                                                       Object** pointer);
411
412 class StoreBufferRebuilder {
413  public:
414   explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
415       : store_buffer_(store_buffer) {
416   }
417
418   void Callback(MemoryChunk* page, StoreBufferEvent event);
419
420  private:
421   StoreBuffer* store_buffer_;
422
423   // We record in this variable how full the store buffer was when we started
424   // iterating over the current page, finding pointers to new space.  If the
425   // store buffer overflows again we can exempt the page from the store buffer
426   // by rewinding to this point instead of having to search the store buffer.
427   Object*** start_of_current_page_;
428   // The current page we are scanning in the store buffer iterator.
429   MemoryChunk* current_page_;
430 };
431
432
433
434 // A queue of objects promoted during scavenge. Each object is accompanied
435 // by it's size to avoid dereferencing a map pointer for scanning.
436 class PromotionQueue {
437  public:
438   explicit PromotionQueue(Heap* heap)
439       : front_(NULL),
440         rear_(NULL),
441         limit_(NULL),
442         emergency_stack_(0),
443         heap_(heap) { }
444
445   void Initialize();
446
447   void Destroy() {
448     ASSERT(is_empty());
449     delete emergency_stack_;
450     emergency_stack_ = NULL;
451   }
452
453   inline void ActivateGuardIfOnTheSamePage();
454
455   Page* GetHeadPage() {
456     return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
457   }
458
459   void SetNewLimit(Address limit) {
460     if (!guard_) {
461       return;
462     }
463
464     ASSERT(GetHeadPage() == Page::FromAllocationTop(limit));
465     limit_ = reinterpret_cast<intptr_t*>(limit);
466
467     if (limit_ <= rear_) {
468       return;
469     }
470
471     RelocateQueueHead();
472   }
473
474   bool is_empty() {
475     return (front_ == rear_) &&
476         (emergency_stack_ == NULL || emergency_stack_->length() == 0);
477   }
478
479   inline void insert(HeapObject* target, int size);
480
481   void remove(HeapObject** target, int* size) {
482     ASSERT(!is_empty());
483     if (front_ == rear_) {
484       Entry e = emergency_stack_->RemoveLast();
485       *target = e.obj_;
486       *size = e.size_;
487       return;
488     }
489
490     if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(front_))) {
491       NewSpacePage* front_page =
492           NewSpacePage::FromAddress(reinterpret_cast<Address>(front_));
493       ASSERT(!front_page->prev_page()->is_anchor());
494       front_ =
495           reinterpret_cast<intptr_t*>(front_page->prev_page()->area_end());
496     }
497     *target = reinterpret_cast<HeapObject*>(*(--front_));
498     *size = static_cast<int>(*(--front_));
499     // Assert no underflow.
500     SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
501                                 reinterpret_cast<Address>(front_));
502   }
503
504  private:
505   // The front of the queue is higher in the memory page chain than the rear.
506   intptr_t* front_;
507   intptr_t* rear_;
508   intptr_t* limit_;
509
510   bool guard_;
511
512   static const int kEntrySizeInWords = 2;
513
514   struct Entry {
515     Entry(HeapObject* obj, int size) : obj_(obj), size_(size) { }
516
517     HeapObject* obj_;
518     int size_;
519   };
520   List<Entry>* emergency_stack_;
521
522   Heap* heap_;
523
524   void RelocateQueueHead();
525
526   DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
527 };
528
529
530 typedef void (*ScavengingCallback)(Map* map,
531                                    HeapObject** slot,
532                                    HeapObject* object);
533
534
535 // External strings table is a place where all external strings are
536 // registered.  We need to keep track of such strings to properly
537 // finalize them.
538 class ExternalStringTable {
539  public:
540   // Registers an external string.
541   inline void AddString(String* string);
542
543   inline void Iterate(ObjectVisitor* v);
544
545   // Restores internal invariant and gets rid of collected strings.
546   // Must be called after each Iterate() that modified the strings.
547   void CleanUp();
548
549   // Destroys all allocated memory.
550   void TearDown();
551
552  private:
553   explicit ExternalStringTable(Heap* heap) : heap_(heap) { }
554
555   friend class Heap;
556
557   inline void Verify();
558
559   inline void AddOldString(String* string);
560
561   // Notifies the table that only a prefix of the new list is valid.
562   inline void ShrinkNewStrings(int position);
563
564   // To speed up scavenge collections new space string are kept
565   // separate from old space strings.
566   List<Object*> new_space_strings_;
567   List<Object*> old_space_strings_;
568
569   Heap* heap_;
570
571   DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
572 };
573
574
575 enum ArrayStorageAllocationMode {
576   DONT_INITIALIZE_ARRAY_ELEMENTS,
577   INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
578 };
579
580
581 class Heap {
582  public:
583   // Configure heap size before setup. Return false if the heap has been
584   // set up already.
585   bool ConfigureHeap(int max_semispace_size,
586                      intptr_t max_old_gen_size,
587                      intptr_t max_executable_size);
588   bool ConfigureHeapDefault();
589
590   // Prepares the heap, setting up memory areas that are needed in the isolate
591   // without actually creating any objects.
592   bool SetUp();
593
594   // Bootstraps the object heap with the core set of objects required to run.
595   // Returns whether it succeeded.
596   bool CreateHeapObjects();
597
598   // Destroys all memory allocated by the heap.
599   void TearDown();
600
601   // Set the stack limit in the roots_ array.  Some architectures generate
602   // code that looks here, because it is faster than loading from the static
603   // jslimit_/real_jslimit_ variable in the StackGuard.
604   void SetStackLimits();
605
606   // Returns whether SetUp has been called.
607   bool HasBeenSetUp();
608
609   // Returns the maximum amount of memory reserved for the heap.  For
610   // the young generation, we reserve 4 times the amount needed for a
611   // semi space.  The young generation consists of two semi spaces and
612   // we reserve twice the amount needed for those in order to ensure
613   // that new space can be aligned to its size.
614   intptr_t MaxReserved() {
615     return 4 * reserved_semispace_size_ + max_old_generation_size_;
616   }
617   int MaxSemiSpaceSize() { return max_semispace_size_; }
618   int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
619   int InitialSemiSpaceSize() { return initial_semispace_size_; }
620   intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
621   intptr_t MaxExecutableSize() { return max_executable_size_; }
622
623   // Returns the capacity of the heap in bytes w/o growing. Heap grows when
624   // more spaces are needed until it reaches the limit.
625   intptr_t Capacity();
626
627   // Returns the amount of memory currently committed for the heap.
628   intptr_t CommittedMemory();
629
630   // Returns the amount of executable memory currently committed for the heap.
631   intptr_t CommittedMemoryExecutable();
632
633   // Returns the amount of phyical memory currently committed for the heap.
634   size_t CommittedPhysicalMemory();
635
636   // Returns the maximum amount of memory ever committed for the heap.
637   intptr_t MaximumCommittedMemory() { return maximum_committed_; }
638
639   // Updates the maximum committed memory for the heap. Should be called
640   // whenever a space grows.
641   void UpdateMaximumCommitted();
642
643   // Returns the available bytes in space w/o growing.
644   // Heap doesn't guarantee that it can allocate an object that requires
645   // all available bytes. Check MaxHeapObjectSize() instead.
646   intptr_t Available();
647
648   // Returns of size of all objects residing in the heap.
649   intptr_t SizeOfObjects();
650
651   // Return the starting address and a mask for the new space.  And-masking an
652   // address with the mask will result in the start address of the new space
653   // for all addresses in either semispace.
654   Address NewSpaceStart() { return new_space_.start(); }
655   uintptr_t NewSpaceMask() { return new_space_.mask(); }
656   Address NewSpaceTop() { return new_space_.top(); }
657
658   NewSpace* new_space() { return &new_space_; }
659   OldSpace* old_pointer_space() { return old_pointer_space_; }
660   OldSpace* old_data_space() { return old_data_space_; }
661   OldSpace* code_space() { return code_space_; }
662   MapSpace* map_space() { return map_space_; }
663   CellSpace* cell_space() { return cell_space_; }
664   PropertyCellSpace* property_cell_space() {
665     return property_cell_space_;
666   }
667   LargeObjectSpace* lo_space() { return lo_space_; }
668   PagedSpace* paged_space(int idx) {
669     switch (idx) {
670       case OLD_POINTER_SPACE:
671         return old_pointer_space();
672       case OLD_DATA_SPACE:
673         return old_data_space();
674       case MAP_SPACE:
675         return map_space();
676       case CELL_SPACE:
677         return cell_space();
678       case PROPERTY_CELL_SPACE:
679         return property_cell_space();
680       case CODE_SPACE:
681         return code_space();
682       case NEW_SPACE:
683       case LO_SPACE:
684         UNREACHABLE();
685     }
686     return NULL;
687   }
688
689   bool always_allocate() { return always_allocate_scope_depth_ != 0; }
690   Address always_allocate_scope_depth_address() {
691     return reinterpret_cast<Address>(&always_allocate_scope_depth_);
692   }
693   bool linear_allocation() {
694     return linear_allocation_scope_depth_ != 0;
695   }
696
697   Address* NewSpaceAllocationTopAddress() {
698     return new_space_.allocation_top_address();
699   }
700   Address* NewSpaceAllocationLimitAddress() {
701     return new_space_.allocation_limit_address();
702   }
703
704   Address* OldPointerSpaceAllocationTopAddress() {
705     return old_pointer_space_->allocation_top_address();
706   }
707   Address* OldPointerSpaceAllocationLimitAddress() {
708     return old_pointer_space_->allocation_limit_address();
709   }
710
711   Address* OldDataSpaceAllocationTopAddress() {
712     return old_data_space_->allocation_top_address();
713   }
714   Address* OldDataSpaceAllocationLimitAddress() {
715     return old_data_space_->allocation_limit_address();
716   }
717
718   // Allocates and initializes a new JavaScript object based on a
719   // constructor.
720   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
721   // failed.
722   // If allocation_site is non-null, then a memento is emitted after the object
723   // that points to the site.
724   // Please note this does not perform a garbage collection.
725   MUST_USE_RESULT MaybeObject* AllocateJSObject(
726       JSFunction* constructor,
727       PretenureFlag pretenure = NOT_TENURED,
728       AllocationSite* allocation_site = NULL);
729
730   MUST_USE_RESULT MaybeObject* AllocateJSModule(Context* context,
731                                                 ScopeInfo* scope_info);
732
733   // Allocate a JSArray with no elements
734   MUST_USE_RESULT MaybeObject* AllocateEmptyJSArray(
735       ElementsKind elements_kind,
736       PretenureFlag pretenure = NOT_TENURED) {
737     return AllocateJSArrayAndStorage(elements_kind, 0, 0,
738                                      DONT_INITIALIZE_ARRAY_ELEMENTS,
739                                      pretenure);
740   }
741
742   // Allocate a JSArray with a specified length but elements that are left
743   // uninitialized.
744   MUST_USE_RESULT MaybeObject* AllocateJSArrayAndStorage(
745       ElementsKind elements_kind,
746       int length,
747       int capacity,
748       ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS,
749       PretenureFlag pretenure = NOT_TENURED);
750
751   MUST_USE_RESULT MaybeObject* AllocateJSArrayStorage(
752       JSArray* array,
753       int length,
754       int capacity,
755       ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS);
756
757   // Allocate a JSArray with no elements
758   MUST_USE_RESULT MaybeObject* AllocateJSArrayWithElements(
759       FixedArrayBase* array_base,
760       ElementsKind elements_kind,
761       int length,
762       PretenureFlag pretenure = NOT_TENURED);
763
764   // Returns a deep copy of the JavaScript object.
765   // Properties and elements are copied too.
766   // Returns failure if allocation failed.
767   // Optionally takes an AllocationSite to be appended in an AllocationMemento.
768   MUST_USE_RESULT MaybeObject* CopyJSObject(JSObject* source,
769                                             AllocationSite* site = NULL);
770
771   // Allocates a JS ArrayBuffer object.
772   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
773   // failed.
774   // Please note this does not perform a garbage collection.
775   MUST_USE_RESULT MaybeObject* AllocateJSArrayBuffer();
776
777   // Allocates a Harmony proxy or function proxy.
778   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
779   // failed.
780   // Please note this does not perform a garbage collection.
781   MUST_USE_RESULT MaybeObject* AllocateJSProxy(Object* handler,
782                                                Object* prototype);
783
784   MUST_USE_RESULT MaybeObject* AllocateJSFunctionProxy(Object* handler,
785                                                        Object* call_trap,
786                                                        Object* construct_trap,
787                                                        Object* prototype);
788
789   // Reinitialize a JSReceiver into an (empty) JS object of respective type and
790   // size, but keeping the original prototype.  The receiver must have at least
791   // the size of the new object.  The object is reinitialized and behaves as an
792   // object that has been freshly allocated.
793   // Returns failure if an error occured, otherwise object.
794   MUST_USE_RESULT MaybeObject* ReinitializeJSReceiver(JSReceiver* object,
795                                                       InstanceType type,
796                                                       int size);
797
798   // Reinitialize an JSGlobalProxy based on a constructor.  The object
799   // must have the same size as objects allocated using the
800   // constructor.  The object is reinitialized and behaves as an
801   // object that has been freshly allocated using the constructor.
802   MUST_USE_RESULT MaybeObject* ReinitializeJSGlobalProxy(
803       JSFunction* constructor, JSGlobalProxy* global);
804
805   // Allocates and initializes a new JavaScript object based on a map.
806   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
807   // failed.
808   // Passing an allocation site means that a memento will be created that
809   // points to the site.
810   // Please note this does not perform a garbage collection.
811   MUST_USE_RESULT MaybeObject* AllocateJSObjectFromMap(
812       Map* map,
813       PretenureFlag pretenure = NOT_TENURED,
814       bool alloc_props = true,
815       AllocationSite* allocation_site = NULL);
816
817   // Allocates a heap object based on the map.
818   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
819   // failed.
820   // Please note this function does not perform a garbage collection.
821   MUST_USE_RESULT MaybeObject* Allocate(Map* map, AllocationSpace space,
822                                         AllocationSite* allocation_site = NULL);
823
824   // Allocates a JS Map in the heap.
825   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
826   // failed.
827   // Please note this function does not perform a garbage collection.
828   MUST_USE_RESULT MaybeObject* AllocateMap(
829       InstanceType instance_type,
830       int instance_size,
831       ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND);
832
833   // Allocates a partial map for bootstrapping.
834   MUST_USE_RESULT MaybeObject* AllocatePartialMap(InstanceType instance_type,
835                                                   int instance_size);
836
837   // Allocates an empty code cache.
838   MUST_USE_RESULT MaybeObject* AllocateCodeCache();
839
840   // Allocates a serialized scope info.
841   MUST_USE_RESULT MaybeObject* AllocateScopeInfo(int length);
842
843   // Allocates an External object for v8's external API.
844   MUST_USE_RESULT MaybeObject* AllocateExternal(void* value);
845
846   // Allocates an empty PolymorphicCodeCache.
847   MUST_USE_RESULT MaybeObject* AllocatePolymorphicCodeCache();
848
849   // Allocates a pre-tenured empty AccessorPair.
850   MUST_USE_RESULT MaybeObject* AllocateAccessorPair();
851
852   // Allocates an empty TypeFeedbackInfo.
853   MUST_USE_RESULT MaybeObject* AllocateTypeFeedbackInfo();
854
855   // Allocates an AliasedArgumentsEntry.
856   MUST_USE_RESULT MaybeObject* AllocateAliasedArgumentsEntry(int slot);
857
858   // Clear the Instanceof cache (used when a prototype changes).
859   inline void ClearInstanceofCache();
860
861   // Iterates the whole code space to clear all ICs of the given kind.
862   void ClearAllICsByKind(Code::Kind kind);
863
864   // For use during bootup.
865   void RepairFreeListsAfterBoot();
866
867   // Allocates and fully initializes a String.  There are two String
868   // encodings: ASCII and two byte. One should choose between the three string
869   // allocation functions based on the encoding of the string buffer used to
870   // initialized the string.
871   //   - ...FromAscii initializes the string from a buffer that is ASCII
872   //     encoded (it does not check that the buffer is ASCII encoded) and the
873   //     result will be ASCII encoded.
874   //   - ...FromUTF8 initializes the string from a buffer that is UTF-8
875   //     encoded.  If the characters are all single-byte characters, the
876   //     result will be ASCII encoded, otherwise it will converted to two
877   //     byte.
878   //   - ...FromTwoByte initializes the string from a buffer that is two-byte
879   //     encoded.  If the characters are all single-byte characters, the
880   //     result will be converted to ASCII, otherwise it will be left as
881   //     two-byte.
882   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
883   // failed.
884   // Please note this does not perform a garbage collection.
885   MUST_USE_RESULT MaybeObject* AllocateStringFromOneByte(
886       Vector<const uint8_t> str,
887       PretenureFlag pretenure = NOT_TENURED);
888   // TODO(dcarney): remove this function.
889   MUST_USE_RESULT inline MaybeObject* AllocateStringFromOneByte(
890       Vector<const char> str,
891       PretenureFlag pretenure = NOT_TENURED) {
892     return AllocateStringFromOneByte(Vector<const uint8_t>::cast(str),
893                                      pretenure);
894   }
895   MUST_USE_RESULT inline MaybeObject* AllocateStringFromUtf8(
896       Vector<const char> str,
897       PretenureFlag pretenure = NOT_TENURED);
898   MUST_USE_RESULT MaybeObject* AllocateStringFromUtf8Slow(
899       Vector<const char> str,
900       int non_ascii_start,
901       PretenureFlag pretenure = NOT_TENURED);
902   MUST_USE_RESULT MaybeObject* AllocateStringFromTwoByte(
903       Vector<const uc16> str,
904       PretenureFlag pretenure = NOT_TENURED);
905
906   // Allocates an internalized string in old space based on the character
907   // stream. Returns Failure::RetryAfterGC(requested_bytes, space) if the
908   // allocation failed.
909   // Please note this function does not perform a garbage collection.
910   MUST_USE_RESULT inline MaybeObject* AllocateInternalizedStringFromUtf8(
911       Vector<const char> str,
912       int chars,
913       uint32_t hash_field);
914
915   MUST_USE_RESULT inline MaybeObject* AllocateOneByteInternalizedString(
916         Vector<const uint8_t> str,
917         uint32_t hash_field);
918
919   MUST_USE_RESULT inline MaybeObject* AllocateTwoByteInternalizedString(
920         Vector<const uc16> str,
921         uint32_t hash_field);
922
923   template<typename T>
924   static inline bool IsOneByte(T t, int chars);
925
926   template<typename T>
927   MUST_USE_RESULT inline MaybeObject* AllocateInternalizedStringImpl(
928       T t, int chars, uint32_t hash_field);
929
930   template<bool is_one_byte, typename T>
931   MUST_USE_RESULT MaybeObject* AllocateInternalizedStringImpl(
932       T t, int chars, uint32_t hash_field);
933
934   // Allocates and partially initializes a String.  There are two String
935   // encodings: ASCII and two byte.  These functions allocate a string of the
936   // given length and set its map and length fields.  The characters of the
937   // string are uninitialized.
938   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
939   // failed.
940   // Please note this does not perform a garbage collection.
941   MUST_USE_RESULT MaybeObject* AllocateRawOneByteString(
942       int length,
943       PretenureFlag pretenure = NOT_TENURED);
944   MUST_USE_RESULT MaybeObject* AllocateRawTwoByteString(
945       int length,
946       PretenureFlag pretenure = NOT_TENURED);
947
948   // Computes a single character string where the character has code.
949   // A cache is used for ASCII codes.
950   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
951   // failed. Please note this does not perform a garbage collection.
952   MUST_USE_RESULT MaybeObject* LookupSingleCharacterStringFromCode(
953       uint16_t code);
954
955   // Allocate a byte array of the specified length
956   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
957   // failed.
958   // Please note this does not perform a garbage collection.
959   MUST_USE_RESULT MaybeObject* AllocateByteArray(
960       int length,
961       PretenureFlag pretenure = NOT_TENURED);
962
963   // Allocates an external array of the specified length and type.
964   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
965   // failed.
966   // Please note this does not perform a garbage collection.
967   MUST_USE_RESULT MaybeObject* AllocateExternalArray(
968       int length,
969       ExternalArrayType array_type,
970       void* external_pointer,
971       PretenureFlag pretenure);
972
973   // Allocates a fixed typed array of the specified length and type.
974   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
975   // failed.
976   // Please note this does not perform a garbage collection.
977   MUST_USE_RESULT MaybeObject* AllocateFixedTypedArray(
978       int length,
979       ExternalArrayType array_type,
980       PretenureFlag pretenure);
981
982   // Allocate a symbol in old space.
983   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
984   // failed.
985   // Please note this does not perform a garbage collection.
986   MUST_USE_RESULT MaybeObject* AllocateSymbol();
987   MUST_USE_RESULT MaybeObject* AllocatePrivateSymbol();
988
989   // Allocate a tenured AllocationSite. It's payload is null
990   MUST_USE_RESULT MaybeObject* AllocateAllocationSite();
991
992   // Allocates a fixed array initialized with undefined values
993   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
994   // failed.
995   // Please note this does not perform a garbage collection.
996   MUST_USE_RESULT MaybeObject* AllocateFixedArray(
997       int length,
998       PretenureFlag pretenure = NOT_TENURED);
999
1000   // Allocates an uninitialized fixed array. It must be filled by the caller.
1001   //
1002   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1003   // failed.
1004   // Please note this does not perform a garbage collection.
1005   MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedArray(int length);
1006
1007   // Move len elements within a given array from src_index index to dst_index
1008   // index.
1009   void MoveElements(FixedArray* array, int dst_index, int src_index, int len);
1010
1011   // Make a copy of src and return it. Returns
1012   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1013   MUST_USE_RESULT inline MaybeObject* CopyFixedArray(FixedArray* src);
1014
1015   // Make a copy of src and return it. Returns
1016   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1017   MUST_USE_RESULT MaybeObject* CopyAndTenureFixedCOWArray(FixedArray* src);
1018
1019   // Make a copy of src, set the map, and return the copy. Returns
1020   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1021   MUST_USE_RESULT MaybeObject* CopyFixedArrayWithMap(FixedArray* src, Map* map);
1022
1023   // Make a copy of src and return it. Returns
1024   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1025   MUST_USE_RESULT inline MaybeObject* CopyFixedDoubleArray(
1026       FixedDoubleArray* src);
1027
1028   // Make a copy of src, set the map, and return the copy. Returns
1029   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1030   MUST_USE_RESULT MaybeObject* CopyFixedDoubleArrayWithMap(
1031       FixedDoubleArray* src, Map* map);
1032
1033   // Make a copy of src and return it. Returns
1034   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1035   MUST_USE_RESULT inline MaybeObject* CopyConstantPoolArray(
1036       ConstantPoolArray* src);
1037
1038   // Make a copy of src, set the map, and return the copy. Returns
1039   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1040   MUST_USE_RESULT MaybeObject* CopyConstantPoolArrayWithMap(
1041       ConstantPoolArray* src, Map* map);
1042
1043   // Allocates a fixed array initialized with the hole values.
1044   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1045   // failed.
1046   // Please note this does not perform a garbage collection.
1047   MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithHoles(
1048       int length,
1049       PretenureFlag pretenure = NOT_TENURED);
1050
1051   MUST_USE_RESULT MaybeObject* AllocateConstantPoolArray(
1052       int number_of_int64_entries,
1053       int number_of_code_ptr_entries,
1054       int number_of_heap_ptr_entries,
1055       int number_of_int32_entries);
1056
1057   // Allocates a fixed double array with uninitialized values. Returns
1058   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1059   // Please note this does not perform a garbage collection.
1060   MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedDoubleArray(
1061       int length,
1062       PretenureFlag pretenure = NOT_TENURED);
1063
1064   // Allocates a fixed double array with hole values. Returns
1065   // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
1066   // Please note this does not perform a garbage collection.
1067   MUST_USE_RESULT MaybeObject* AllocateFixedDoubleArrayWithHoles(
1068       int length,
1069       PretenureFlag pretenure = NOT_TENURED);
1070
1071   // AllocateHashTable is identical to AllocateFixedArray except
1072   // that the resulting object has hash_table_map as map.
1073   MUST_USE_RESULT MaybeObject* AllocateHashTable(
1074       int length, PretenureFlag pretenure = NOT_TENURED);
1075
1076   // Allocate a native (but otherwise uninitialized) context.
1077   MUST_USE_RESULT MaybeObject* AllocateNativeContext();
1078
1079   // Allocate a global context.
1080   MUST_USE_RESULT MaybeObject* AllocateGlobalContext(JSFunction* function,
1081                                                      ScopeInfo* scope_info);
1082
1083   // Allocate a module context.
1084   MUST_USE_RESULT MaybeObject* AllocateModuleContext(ScopeInfo* scope_info);
1085
1086   // Allocate a function context.
1087   MUST_USE_RESULT MaybeObject* AllocateFunctionContext(int length,
1088                                                        JSFunction* function);
1089
1090   // Allocate a catch context.
1091   MUST_USE_RESULT MaybeObject* AllocateCatchContext(JSFunction* function,
1092                                                     Context* previous,
1093                                                     String* name,
1094                                                     Object* thrown_object);
1095   // Allocate a 'with' context.
1096   MUST_USE_RESULT MaybeObject* AllocateWithContext(JSFunction* function,
1097                                                    Context* previous,
1098                                                    JSReceiver* extension);
1099
1100   // Allocate a block context.
1101   MUST_USE_RESULT MaybeObject* AllocateBlockContext(JSFunction* function,
1102                                                     Context* previous,
1103                                                     ScopeInfo* info);
1104
1105   // Allocates a new utility object in the old generation.
1106   MUST_USE_RESULT MaybeObject* AllocateStruct(InstanceType type);
1107
1108   // Allocates a function initialized with a shared part.
1109   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1110   // failed.
1111   // Please note this does not perform a garbage collection.
1112   MUST_USE_RESULT MaybeObject* AllocateFunction(
1113       Map* function_map,
1114       SharedFunctionInfo* shared,
1115       Object* prototype,
1116       PretenureFlag pretenure = TENURED);
1117
1118   // Sloppy mode arguments object size.
1119   static const int kSloppyArgumentsObjectSize =
1120       JSObject::kHeaderSize + 2 * kPointerSize;
1121   // Strict mode arguments has no callee so it is smaller.
1122   static const int kStrictArgumentsObjectSize =
1123       JSObject::kHeaderSize + 1 * kPointerSize;
1124   // Indicies for direct access into argument objects.
1125   static const int kArgumentsLengthIndex = 0;
1126   // callee is only valid in sloppy mode.
1127   static const int kArgumentsCalleeIndex = 1;
1128
1129   // Allocates an arguments object - optionally with an elements array.
1130   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1131   // failed.
1132   // Please note this does not perform a garbage collection.
1133   MUST_USE_RESULT MaybeObject* AllocateArgumentsObject(
1134       Object* callee, int length);
1135
1136   // Same as NewNumberFromDouble, but may return a preallocated/immutable
1137   // number object (e.g., minus_zero_value_, nan_value_)
1138   MUST_USE_RESULT MaybeObject* NumberFromDouble(
1139       double value, PretenureFlag pretenure = NOT_TENURED);
1140
1141   // Allocated a HeapNumber from value.
1142   MUST_USE_RESULT MaybeObject* AllocateHeapNumber(
1143       double value, PretenureFlag pretenure = NOT_TENURED);
1144
1145   // Allocated a Float32x4 from value.
1146   MUST_USE_RESULT MaybeObject* AllocateFloat32x4(
1147       float32x4_value_t value,
1148       PretenureFlag pretenure = NOT_TENURED);
1149
1150   // Allocated a Int32x4 from value.
1151   MUST_USE_RESULT MaybeObject* AllocateInt32x4(
1152       int32x4_value_t value,
1153       PretenureFlag pretenure = NOT_TENURED);
1154
1155   // Converts an int into either a Smi or a HeapNumber object.
1156   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1157   // failed.
1158   // Please note this does not perform a garbage collection.
1159   MUST_USE_RESULT inline MaybeObject* NumberFromInt32(
1160       int32_t value, PretenureFlag pretenure = NOT_TENURED);
1161
1162   // Converts an int into either a Smi or a HeapNumber object.
1163   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1164   // failed.
1165   // Please note this does not perform a garbage collection.
1166   MUST_USE_RESULT inline MaybeObject* NumberFromUint32(
1167       uint32_t value, PretenureFlag pretenure = NOT_TENURED);
1168
1169   // Allocates a new foreign object.
1170   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1171   // failed.
1172   // Please note this does not perform a garbage collection.
1173   MUST_USE_RESULT MaybeObject* AllocateForeign(
1174       Address address, PretenureFlag pretenure = NOT_TENURED);
1175
1176   // Allocates a new SharedFunctionInfo object.
1177   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1178   // failed.
1179   // Please note this does not perform a garbage collection.
1180   MUST_USE_RESULT MaybeObject* AllocateSharedFunctionInfo(Object* name);
1181
1182   // Allocates a new JSMessageObject object.
1183   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1184   // failed.
1185   // Please note that this does not perform a garbage collection.
1186   MUST_USE_RESULT MaybeObject* AllocateJSMessageObject(
1187       String* type,
1188       JSArray* arguments,
1189       int start_position,
1190       int end_position,
1191       Object* script,
1192       Object* stack_frames);
1193
1194   // Allocate a new external string object, which is backed by a string
1195   // resource that resides outside the V8 heap.
1196   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1197   // failed.
1198   // Please note this does not perform a garbage collection.
1199   MUST_USE_RESULT MaybeObject* AllocateExternalStringFromAscii(
1200       const ExternalAsciiString::Resource* resource);
1201   MUST_USE_RESULT MaybeObject* AllocateExternalStringFromTwoByte(
1202       const ExternalTwoByteString::Resource* resource);
1203
1204   // Finalizes an external string by deleting the associated external
1205   // data and clearing the resource pointer.
1206   inline void FinalizeExternalString(String* string);
1207
1208   // Allocates an uninitialized object.  The memory is non-executable if the
1209   // hardware and OS allow.
1210   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1211   // failed.
1212   // Please note this function does not perform a garbage collection.
1213   MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes,
1214                                                   AllocationSpace space,
1215                                                   AllocationSpace retry_space);
1216
1217   // Initialize a filler object to keep the ability to iterate over the heap
1218   // when shortening objects.
1219   void CreateFillerObjectAt(Address addr, int size);
1220
1221   bool CanMoveObjectStart(HeapObject* object);
1222
1223   enum InvocationMode { FROM_GC, FROM_MUTATOR };
1224
1225   // Maintain marking consistency for IncrementalMarking.
1226   void AdjustLiveBytes(Address address, int by, InvocationMode mode);
1227
1228   // Makes a new native code object
1229   // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1230   // failed. On success, the pointer to the Code object is stored in the
1231   // self_reference. This allows generated code to reference its own Code
1232   // object by containing this pointer.
1233   // Please note this function does not perform a garbage collection.
1234   MUST_USE_RESULT MaybeObject* CreateCode(
1235       const CodeDesc& desc,
1236       Code::Flags flags,
1237       Handle<Object> self_reference,
1238       bool immovable = false,
1239       bool crankshafted = false,
1240       int prologue_offset = Code::kPrologueOffsetNotSet);
1241
1242   MUST_USE_RESULT MaybeObject* CopyCode(Code* code);
1243
1244   // Copy the code and scope info part of the code object, but insert
1245   // the provided data as the relocation information.
1246   MUST_USE_RESULT MaybeObject* CopyCode(Code* code, Vector<byte> reloc_info);
1247
1248   // Finds the internalized copy for string in the string table.
1249   // If not found, a new string is added to the table and returned.
1250   // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
1251   // failed.
1252   // Please note this function does not perform a garbage collection.
1253   MUST_USE_RESULT MaybeObject* InternalizeUtf8String(const char* str) {
1254     return InternalizeUtf8String(CStrVector(str));
1255   }
1256   MUST_USE_RESULT MaybeObject* InternalizeUtf8String(Vector<const char> str);
1257
1258   MUST_USE_RESULT MaybeObject* InternalizeString(String* str);
1259   MUST_USE_RESULT MaybeObject* InternalizeStringWithKey(HashTableKey* key);
1260
1261   bool InternalizeStringIfExists(String* str, String** result);
1262   bool InternalizeTwoCharsStringIfExists(String* str, String** result);
1263
1264   // Compute the matching internalized string map for a string if possible.
1265   // NULL is returned if string is in new space or not flattened.
1266   Map* InternalizedStringMapForString(String* str);
1267
1268   // Tries to flatten a string before compare operation.
1269   //
1270   // Returns a failure in case it was decided that flattening was
1271   // necessary and failed.  Note, if flattening is not necessary the
1272   // string might stay non-flat even when not a failure is returned.
1273   //
1274   // Please note this function does not perform a garbage collection.
1275   MUST_USE_RESULT inline MaybeObject* PrepareForCompare(String* str);
1276
1277   // Converts the given boolean condition to JavaScript boolean value.
1278   inline Object* ToBoolean(bool condition);
1279
1280   // Performs garbage collection operation.
1281   // Returns whether there is a chance that another major GC could
1282   // collect more garbage.
1283   inline bool CollectGarbage(
1284       AllocationSpace space,
1285       const char* gc_reason = NULL,
1286       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1287
1288   static const int kNoGCFlags = 0;
1289   static const int kSweepPreciselyMask = 1;
1290   static const int kReduceMemoryFootprintMask = 2;
1291   static const int kAbortIncrementalMarkingMask = 4;
1292
1293   // Making the heap iterable requires us to sweep precisely and abort any
1294   // incremental marking as well.
1295   static const int kMakeHeapIterableMask =
1296       kSweepPreciselyMask | kAbortIncrementalMarkingMask;
1297
1298   // Performs a full garbage collection.  If (flags & kMakeHeapIterableMask) is
1299   // non-zero, then the slower precise sweeper is used, which leaves the heap
1300   // in a state where we can iterate over the heap visiting all objects.
1301   void CollectAllGarbage(
1302       int flags,
1303       const char* gc_reason = NULL,
1304       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1305
1306   // Last hope GC, should try to squeeze as much as possible.
1307   void CollectAllAvailableGarbage(const char* gc_reason = NULL);
1308
1309   // Check whether the heap is currently iterable.
1310   bool IsHeapIterable();
1311
1312   // Ensure that we have swept all spaces in such a way that we can iterate
1313   // over all objects.  May cause a GC.
1314   void EnsureHeapIsIterable();
1315
1316   // Notify the heap that a context has been disposed.
1317   int NotifyContextDisposed();
1318
1319   inline void increment_scan_on_scavenge_pages() {
1320     scan_on_scavenge_pages_++;
1321     if (FLAG_gc_verbose) {
1322       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1323     }
1324   }
1325
1326   inline void decrement_scan_on_scavenge_pages() {
1327     scan_on_scavenge_pages_--;
1328     if (FLAG_gc_verbose) {
1329       PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1330     }
1331   }
1332
1333   PromotionQueue* promotion_queue() { return &promotion_queue_; }
1334
1335 #ifdef DEBUG
1336   // Utility used with flag gc-greedy.
1337   void GarbageCollectionGreedyCheck();
1338 #endif
1339
1340   void AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
1341                              GCType gc_type_filter,
1342                              bool pass_isolate = true);
1343   void RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback);
1344
1345   void AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
1346                              GCType gc_type_filter,
1347                              bool pass_isolate = true);
1348   void RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback);
1349
1350   // Heap root getters.  We have versions with and without type::cast() here.
1351   // You can't use type::cast during GC because the assert fails.
1352   // TODO(1490): Try removing the unchecked accessors, now that GC marking does
1353   // not corrupt the map.
1354 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
1355   type* name() {                                                               \
1356     return type::cast(roots_[k##camel_name##RootIndex]);                       \
1357   }                                                                            \
1358   type* raw_unchecked_##name() {                                               \
1359     return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]);          \
1360   }
1361   ROOT_LIST(ROOT_ACCESSOR)
1362 #undef ROOT_ACCESSOR
1363
1364 // Utility type maps
1365 #define STRUCT_MAP_ACCESSOR(NAME, Name, name)                                  \
1366     Map* name##_map() {                                                        \
1367       return Map::cast(roots_[k##Name##MapRootIndex]);                         \
1368     }
1369   STRUCT_LIST(STRUCT_MAP_ACCESSOR)
1370 #undef STRUCT_MAP_ACCESSOR
1371
1372 #define STRING_ACCESSOR(name, str) String* name() {                            \
1373     return String::cast(roots_[k##name##RootIndex]);                           \
1374   }
1375   INTERNALIZED_STRING_LIST(STRING_ACCESSOR)
1376 #undef STRING_ACCESSOR
1377
1378   // The hidden_string is special because it is the empty string, but does
1379   // not match the empty string.
1380   String* hidden_string() { return hidden_string_; }
1381
1382   void set_native_contexts_list(Object* object) {
1383     native_contexts_list_ = object;
1384   }
1385   Object* native_contexts_list() { return native_contexts_list_; }
1386
1387   void set_array_buffers_list(Object* object) {
1388     array_buffers_list_ = object;
1389   }
1390   Object* array_buffers_list() { return array_buffers_list_; }
1391
1392   void set_allocation_sites_list(Object* object) {
1393     allocation_sites_list_ = object;
1394   }
1395   Object* allocation_sites_list() { return allocation_sites_list_; }
1396   Object** allocation_sites_list_address() { return &allocation_sites_list_; }
1397
1398   Object* weak_object_to_code_table() { return weak_object_to_code_table_; }
1399
1400   // Number of mark-sweeps.
1401   unsigned int ms_count() { return ms_count_; }
1402
1403   // Iterates over all roots in the heap.
1404   void IterateRoots(ObjectVisitor* v, VisitMode mode);
1405   // Iterates over all strong roots in the heap.
1406   void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
1407   // Iterates over entries in the smi roots list.  Only interesting to the
1408   // serializer/deserializer, since GC does not care about smis.
1409   void IterateSmiRoots(ObjectVisitor* v);
1410   // Iterates over all the other roots in the heap.
1411   void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
1412
1413   // Iterate pointers to from semispace of new space found in memory interval
1414   // from start to end.
1415   void IterateAndMarkPointersToFromSpace(Address start,
1416                                          Address end,
1417                                          ObjectSlotCallback callback);
1418
1419   // Returns whether the object resides in new space.
1420   inline bool InNewSpace(Object* object);
1421   inline bool InNewSpace(Address address);
1422   inline bool InNewSpacePage(Address address);
1423   inline bool InFromSpace(Object* object);
1424   inline bool InToSpace(Object* object);
1425
1426   // Returns whether the object resides in old pointer space.
1427   inline bool InOldPointerSpace(Address address);
1428   inline bool InOldPointerSpace(Object* object);
1429
1430   // Returns whether the object resides in old data space.
1431   inline bool InOldDataSpace(Address address);
1432   inline bool InOldDataSpace(Object* object);
1433
1434   // Checks whether an address/object in the heap (including auxiliary
1435   // area and unused area).
1436   bool Contains(Address addr);
1437   bool Contains(HeapObject* value);
1438
1439   // Checks whether an address/object in a space.
1440   // Currently used by tests, serialization and heap verification only.
1441   bool InSpace(Address addr, AllocationSpace space);
1442   bool InSpace(HeapObject* value, AllocationSpace space);
1443
1444   // Finds out which space an object should get promoted to based on its type.
1445   inline OldSpace* TargetSpace(HeapObject* object);
1446   static inline AllocationSpace TargetSpaceId(InstanceType type);
1447
1448   // Checks whether the given object is allowed to be migrated from it's
1449   // current space into the given destination space. Used for debugging.
1450   inline bool AllowedToBeMigrated(HeapObject* object, AllocationSpace dest);
1451
1452   // Sets the stub_cache_ (only used when expanding the dictionary).
1453   void public_set_code_stubs(UnseededNumberDictionary* value) {
1454     roots_[kCodeStubsRootIndex] = value;
1455   }
1456
1457   // Support for computing object sizes for old objects during GCs. Returns
1458   // a function that is guaranteed to be safe for computing object sizes in
1459   // the current GC phase.
1460   HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
1461     return gc_safe_size_of_old_object_;
1462   }
1463
1464   // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
1465   void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
1466     roots_[kNonMonomorphicCacheRootIndex] = value;
1467   }
1468
1469   void public_set_empty_script(Script* script) {
1470     roots_[kEmptyScriptRootIndex] = script;
1471   }
1472
1473   void public_set_store_buffer_top(Address* top) {
1474     roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1475   }
1476
1477   void public_set_materialized_objects(FixedArray* objects) {
1478     roots_[kMaterializedObjectsRootIndex] = objects;
1479   }
1480
1481   // Generated code can embed this address to get access to the roots.
1482   Object** roots_array_start() { return roots_; }
1483
1484   Address* store_buffer_top_address() {
1485     return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1486   }
1487
1488   // Get address of native contexts list for serialization support.
1489   Object** native_contexts_list_address() {
1490     return &native_contexts_list_;
1491   }
1492
1493 #ifdef VERIFY_HEAP
1494   // Verify the heap is in its normal state before or after a GC.
1495   void Verify();
1496
1497
1498   bool weak_embedded_objects_verification_enabled() {
1499     return no_weak_object_verification_scope_depth_ == 0;
1500   }
1501 #endif
1502
1503 #ifdef DEBUG
1504   void Print();
1505   void PrintHandles();
1506
1507   void OldPointerSpaceCheckStoreBuffer();
1508   void MapSpaceCheckStoreBuffer();
1509   void LargeObjectSpaceCheckStoreBuffer();
1510
1511   // Report heap statistics.
1512   void ReportHeapStatistics(const char* title);
1513   void ReportCodeStatistics(const char* title);
1514 #endif
1515
1516   // Zapping is needed for verify heap, and always done in debug builds.
1517   static inline bool ShouldZapGarbage() {
1518 #ifdef DEBUG
1519     return true;
1520 #else
1521 #ifdef VERIFY_HEAP
1522     return FLAG_verify_heap;
1523 #else
1524     return false;
1525 #endif
1526 #endif
1527   }
1528
1529   // Print short heap statistics.
1530   void PrintShortHeapStatistics();
1531
1532   // Write barrier support for address[offset] = o.
1533   INLINE(void RecordWrite(Address address, int offset));
1534
1535   // Write barrier support for address[start : start + len[ = o.
1536   INLINE(void RecordWrites(Address address, int start, int len));
1537
1538   enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1539   inline HeapState gc_state() { return gc_state_; }
1540
1541   inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1542
1543 #ifdef DEBUG
1544   void set_allocation_timeout(int timeout) {
1545     allocation_timeout_ = timeout;
1546   }
1547
1548   void TracePathToObjectFrom(Object* target, Object* root);
1549   void TracePathToObject(Object* target);
1550   void TracePathToGlobal();
1551 #endif
1552
1553   // Callback function passed to Heap::Iterate etc.  Copies an object if
1554   // necessary, the object might be promoted to an old space.  The caller must
1555   // ensure the precondition that the object is (a) a heap object and (b) in
1556   // the heap's from space.
1557   static inline void ScavengePointer(HeapObject** p);
1558   static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1559
1560   enum ScratchpadSlotMode {
1561     IGNORE_SCRATCHPAD_SLOT,
1562     RECORD_SCRATCHPAD_SLOT
1563   };
1564
1565   // An object may have an AllocationSite associated with it through a trailing
1566   // AllocationMemento. Its feedback should be updated when objects are found
1567   // in the heap.
1568   static inline void UpdateAllocationSiteFeedback(
1569       HeapObject* object, ScratchpadSlotMode mode);
1570
1571   // Support for partial snapshots.  After calling this we have a linear
1572   // space to write objects in each space.
1573   void ReserveSpace(int *sizes, Address* addresses);
1574
1575   //
1576   // Support for the API.
1577   //
1578
1579   bool CreateApiObjects();
1580
1581   // Attempt to find the number in a small cache.  If we finds it, return
1582   // the string representation of the number.  Otherwise return undefined.
1583   Object* GetNumberStringCache(Object* number);
1584
1585   // Update the cache with a new number-string pair.
1586   void SetNumberStringCache(Object* number, String* str);
1587
1588   // Adjusts the amount of registered external memory.
1589   // Returns the adjusted value.
1590   inline int64_t AdjustAmountOfExternalAllocatedMemory(
1591       int64_t change_in_bytes);
1592
1593   // This is only needed for testing high promotion mode.
1594   void SetNewSpaceHighPromotionModeActive(bool mode) {
1595     new_space_high_promotion_mode_active_ = mode;
1596   }
1597
1598   // Returns the allocation mode (pre-tenuring) based on observed promotion
1599   // rates of previous collections.
1600   inline PretenureFlag GetPretenureMode() {
1601     return FLAG_pretenuring && new_space_high_promotion_mode_active_
1602         ? TENURED : NOT_TENURED;
1603   }
1604
1605   inline Address* NewSpaceHighPromotionModeActiveAddress() {
1606     return reinterpret_cast<Address*>(&new_space_high_promotion_mode_active_);
1607   }
1608
1609   inline intptr_t PromotedTotalSize() {
1610     int64_t total = PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1611     if (total > kMaxInt) return static_cast<intptr_t>(kMaxInt);
1612     if (total < 0) return 0;
1613     return static_cast<intptr_t>(total);
1614   }
1615
1616   inline intptr_t OldGenerationSpaceAvailable() {
1617     return old_generation_allocation_limit_ - PromotedTotalSize();
1618   }
1619
1620   inline intptr_t OldGenerationCapacityAvailable() {
1621     return max_old_generation_size_ - PromotedTotalSize();
1622   }
1623
1624   static const intptr_t kMinimumOldGenerationAllocationLimit =
1625       8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1626
1627   intptr_t OldGenerationAllocationLimit(intptr_t old_gen_size) {
1628     const int divisor = FLAG_stress_compaction ? 10 : 1;
1629     intptr_t limit =
1630         Max(old_gen_size + old_gen_size / divisor,
1631             kMinimumOldGenerationAllocationLimit);
1632     limit += new_space_.Capacity();
1633     intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1634     return Min(limit, halfway_to_the_max);
1635   }
1636
1637   // Indicates whether inline bump-pointer allocation has been disabled.
1638   bool inline_allocation_disabled() { return inline_allocation_disabled_; }
1639
1640   // Switch whether inline bump-pointer allocation should be used.
1641   void EnableInlineAllocation();
1642   void DisableInlineAllocation();
1643
1644   // Implements the corresponding V8 API function.
1645   bool IdleNotification(int hint);
1646
1647   // Declare all the root indices.  This defines the root list order.
1648   enum RootListIndex {
1649 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1650     STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1651 #undef ROOT_INDEX_DECLARATION
1652
1653 #define STRING_INDEX_DECLARATION(name, str) k##name##RootIndex,
1654     INTERNALIZED_STRING_LIST(STRING_INDEX_DECLARATION)
1655 #undef STRING_DECLARATION
1656
1657     // Utility type maps
1658 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1659     STRUCT_LIST(DECLARE_STRUCT_MAP)
1660 #undef DECLARE_STRUCT_MAP
1661
1662     kStringTableRootIndex,
1663
1664 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1665     SMI_ROOT_LIST(ROOT_INDEX_DECLARATION)
1666 #undef ROOT_INDEX_DECLARATION
1667
1668     kRootListLength,
1669     kStrongRootListLength = kStringTableRootIndex,
1670     kSmiRootsStart = kStringTableRootIndex + 1
1671   };
1672
1673   STATIC_CHECK(kUndefinedValueRootIndex == Internals::kUndefinedValueRootIndex);
1674   STATIC_CHECK(kNullValueRootIndex == Internals::kNullValueRootIndex);
1675   STATIC_CHECK(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1676   STATIC_CHECK(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1677   STATIC_CHECK(kempty_stringRootIndex == Internals::kEmptyStringRootIndex);
1678
1679   // Generated code can embed direct references to non-writable roots if
1680   // they are in new space.
1681   static bool RootCanBeWrittenAfterInitialization(RootListIndex root_index);
1682   // Generated code can treat direct references to this root as constant.
1683   bool RootCanBeTreatedAsConstant(RootListIndex root_index);
1684
1685   MUST_USE_RESULT MaybeObject* NumberToString(
1686       Object* number, bool check_number_string_cache = true);
1687   MUST_USE_RESULT MaybeObject* Uint32ToString(
1688       uint32_t value, bool check_number_string_cache = true);
1689
1690   Map* MapForFixedTypedArray(ExternalArrayType array_type);
1691   RootListIndex RootIndexForFixedTypedArray(
1692       ExternalArrayType array_type);
1693
1694   Map* MapForExternalArrayType(ExternalArrayType array_type);
1695   RootListIndex RootIndexForExternalArrayType(
1696       ExternalArrayType array_type);
1697
1698   RootListIndex RootIndexForEmptyExternalArray(ElementsKind kind);
1699   RootListIndex RootIndexForEmptyFixedTypedArray(ElementsKind kind);
1700   ExternalArray* EmptyExternalArrayForMap(Map* map);
1701   FixedTypedArrayBase* EmptyFixedTypedArrayForMap(Map* map);
1702
1703   void RecordStats(HeapStats* stats, bool take_snapshot = false);
1704
1705   // Copy block of memory from src to dst. Size of block should be aligned
1706   // by pointer size.
1707   static inline void CopyBlock(Address dst, Address src, int byte_size);
1708
1709   // Optimized version of memmove for blocks with pointer size aligned sizes and
1710   // pointer size aligned addresses.
1711   static inline void MoveBlock(Address dst, Address src, int byte_size);
1712
1713   // Check new space expansion criteria and expand semispaces if it was hit.
1714   void CheckNewSpaceExpansionCriteria();
1715
1716   inline void IncrementYoungSurvivorsCounter(int survived) {
1717     ASSERT(survived >= 0);
1718     young_survivors_after_last_gc_ = survived;
1719     survived_since_last_expansion_ += survived;
1720   }
1721
1722   inline bool NextGCIsLikelyToBeFull() {
1723     if (FLAG_gc_global) return true;
1724
1725     if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1726
1727     intptr_t adjusted_allocation_limit =
1728         old_generation_allocation_limit_ - new_space_.Capacity();
1729
1730     if (PromotedTotalSize() >= adjusted_allocation_limit) return true;
1731
1732     return false;
1733   }
1734
1735   void UpdateNewSpaceReferencesInExternalStringTable(
1736       ExternalStringTableUpdaterCallback updater_func);
1737
1738   void UpdateReferencesInExternalStringTable(
1739       ExternalStringTableUpdaterCallback updater_func);
1740
1741   void ProcessWeakReferences(WeakObjectRetainer* retainer);
1742
1743   void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1744
1745   // Helper function that governs the promotion policy from new space to
1746   // old.  If the object's old address lies below the new space's age
1747   // mark or if we've already filled the bottom 1/16th of the to space,
1748   // we try to promote this object.
1749   inline bool ShouldBePromoted(Address old_address, int object_size);
1750
1751   void ClearJSFunctionResultCaches();
1752
1753   void ClearNormalizedMapCaches();
1754
1755   GCTracer* tracer() { return tracer_; }
1756
1757   // Returns the size of objects residing in non new spaces.
1758   intptr_t PromotedSpaceSizeOfObjects();
1759
1760   double total_regexp_code_generated() { return total_regexp_code_generated_; }
1761   void IncreaseTotalRegexpCodeGenerated(int size) {
1762     total_regexp_code_generated_ += size;
1763   }
1764
1765   void IncrementCodeGeneratedBytes(bool is_crankshafted, int size) {
1766     if (is_crankshafted) {
1767       crankshaft_codegen_bytes_generated_ += size;
1768     } else {
1769       full_codegen_bytes_generated_ += size;
1770     }
1771   }
1772
1773   // Returns maximum GC pause.
1774   double get_max_gc_pause() { return max_gc_pause_; }
1775
1776   // Returns maximum size of objects alive after GC.
1777   intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1778
1779   // Returns minimal interval between two subsequent collections.
1780   double get_min_in_mutator() { return min_in_mutator_; }
1781
1782   // TODO(hpayer): remove, should be handled by GCTracer
1783   void AddMarkingTime(double marking_time) {
1784     marking_time_ += marking_time;
1785   }
1786
1787   double marking_time() const {
1788     return marking_time_;
1789   }
1790
1791   // TODO(hpayer): remove, should be handled by GCTracer
1792   void AddSweepingTime(double sweeping_time) {
1793     sweeping_time_ += sweeping_time;
1794   }
1795
1796   double sweeping_time() const {
1797     return sweeping_time_;
1798   }
1799
1800   MarkCompactCollector* mark_compact_collector() {
1801     return &mark_compact_collector_;
1802   }
1803
1804   StoreBuffer* store_buffer() {
1805     return &store_buffer_;
1806   }
1807
1808   Marking* marking() {
1809     return &marking_;
1810   }
1811
1812   IncrementalMarking* incremental_marking() {
1813     return &incremental_marking_;
1814   }
1815
1816   bool IsSweepingComplete() {
1817     return !mark_compact_collector()->IsConcurrentSweepingInProgress() &&
1818            old_data_space()->IsLazySweepingComplete() &&
1819            old_pointer_space()->IsLazySweepingComplete();
1820   }
1821
1822   bool AdvanceSweepers(int step_size);
1823
1824   bool EnsureSweepersProgressed(int step_size) {
1825     bool sweeping_complete = old_data_space()->EnsureSweeperProgress(step_size);
1826     sweeping_complete &= old_pointer_space()->EnsureSweeperProgress(step_size);
1827     return sweeping_complete;
1828   }
1829
1830   ExternalStringTable* external_string_table() {
1831     return &external_string_table_;
1832   }
1833
1834   // Returns the current sweep generation.
1835   int sweep_generation() {
1836     return sweep_generation_;
1837   }
1838
1839   inline Isolate* isolate();
1840
1841   void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1842   void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1843
1844   inline bool OldGenerationAllocationLimitReached();
1845
1846   inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1847     scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1848   }
1849
1850   void QueueMemoryChunkForFree(MemoryChunk* chunk);
1851   void FreeQueuedChunks();
1852
1853   int gc_count() const { return gc_count_; }
1854
1855   // Completely clear the Instanceof cache (to stop it keeping objects alive
1856   // around a GC).
1857   inline void CompletelyClearInstanceofCache();
1858
1859   // The roots that have an index less than this are always in old space.
1860   static const int kOldSpaceRoots = 0x20;
1861
1862   uint32_t HashSeed() {
1863     uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1864     ASSERT(FLAG_randomize_hashes || seed == 0);
1865     return seed;
1866   }
1867
1868   void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1869     ASSERT(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1870     set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1871   }
1872
1873   void SetConstructStubDeoptPCOffset(int pc_offset) {
1874     ASSERT(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1875     set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1876   }
1877
1878   void SetGetterStubDeoptPCOffset(int pc_offset) {
1879     ASSERT(getter_stub_deopt_pc_offset() == Smi::FromInt(0));
1880     set_getter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1881   }
1882
1883   void SetSetterStubDeoptPCOffset(int pc_offset) {
1884     ASSERT(setter_stub_deopt_pc_offset() == Smi::FromInt(0));
1885     set_setter_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1886   }
1887
1888   // For post mortem debugging.
1889   void RememberUnmappedPage(Address page, bool compacted);
1890
1891   // Global inline caching age: it is incremented on some GCs after context
1892   // disposal. We use it to flush inline caches.
1893   int global_ic_age() {
1894     return global_ic_age_;
1895   }
1896
1897   void AgeInlineCaches() {
1898     global_ic_age_ = (global_ic_age_ + 1) & SharedFunctionInfo::ICAgeBits::kMax;
1899   }
1900
1901   bool flush_monomorphic_ics() { return flush_monomorphic_ics_; }
1902
1903   int64_t amount_of_external_allocated_memory() {
1904     return amount_of_external_allocated_memory_;
1905   }
1906
1907   void DeoptMarkedAllocationSites();
1908
1909   // ObjectStats are kept in two arrays, counts and sizes. Related stats are
1910   // stored in a contiguous linear buffer. Stats groups are stored one after
1911   // another.
1912   enum {
1913     FIRST_CODE_KIND_SUB_TYPE = LAST_TYPE + 1,
1914     FIRST_FIXED_ARRAY_SUB_TYPE =
1915         FIRST_CODE_KIND_SUB_TYPE + Code::NUMBER_OF_KINDS,
1916     FIRST_CODE_AGE_SUB_TYPE =
1917         FIRST_FIXED_ARRAY_SUB_TYPE + LAST_FIXED_ARRAY_SUB_TYPE + 1,
1918     OBJECT_STATS_COUNT = FIRST_CODE_AGE_SUB_TYPE + Code::kCodeAgeCount + 1
1919   };
1920
1921   void RecordObjectStats(InstanceType type, size_t size) {
1922     ASSERT(type <= LAST_TYPE);
1923     object_counts_[type]++;
1924     object_sizes_[type] += size;
1925   }
1926
1927   void RecordCodeSubTypeStats(int code_sub_type, int code_age, size_t size) {
1928     int code_sub_type_index = FIRST_CODE_KIND_SUB_TYPE + code_sub_type;
1929     int code_age_index =
1930         FIRST_CODE_AGE_SUB_TYPE + code_age - Code::kFirstCodeAge;
1931     ASSERT(code_sub_type_index >= FIRST_CODE_KIND_SUB_TYPE &&
1932            code_sub_type_index < FIRST_CODE_AGE_SUB_TYPE);
1933     ASSERT(code_age_index >= FIRST_CODE_AGE_SUB_TYPE &&
1934            code_age_index < OBJECT_STATS_COUNT);
1935     object_counts_[code_sub_type_index]++;
1936     object_sizes_[code_sub_type_index] += size;
1937     object_counts_[code_age_index]++;
1938     object_sizes_[code_age_index] += size;
1939   }
1940
1941   void RecordFixedArraySubTypeStats(int array_sub_type, size_t size) {
1942     ASSERT(array_sub_type <= LAST_FIXED_ARRAY_SUB_TYPE);
1943     object_counts_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type]++;
1944     object_sizes_[FIRST_FIXED_ARRAY_SUB_TYPE + array_sub_type] += size;
1945   }
1946
1947   void CheckpointObjectStats();
1948
1949   // We don't use a LockGuard here since we want to lock the heap
1950   // only when FLAG_concurrent_recompilation is true.
1951   class RelocationLock {
1952    public:
1953     explicit RelocationLock(Heap* heap) : heap_(heap) {
1954       heap_->relocation_mutex_.Lock();
1955     }
1956
1957
1958     ~RelocationLock() {
1959       heap_->relocation_mutex_.Unlock();
1960     }
1961
1962    private:
1963     Heap* heap_;
1964   };
1965
1966   MaybeObject* AddWeakObjectToCodeDependency(Object* obj, DependentCode* dep);
1967
1968   DependentCode* LookupWeakObjectToCodeDependency(Object* obj);
1969
1970   void InitializeWeakObjectToCodeTable() {
1971     set_weak_object_to_code_table(undefined_value());
1972   }
1973
1974   void EnsureWeakObjectToCodeTable();
1975
1976   static void FatalProcessOutOfMemory(const char* location,
1977                                       bool take_snapshot = false);
1978
1979  private:
1980   Heap();
1981
1982   // This can be calculated directly from a pointer to the heap; however, it is
1983   // more expedient to get at the isolate directly from within Heap methods.
1984   Isolate* isolate_;
1985
1986   Object* roots_[kRootListLength];
1987
1988   intptr_t code_range_size_;
1989   int reserved_semispace_size_;
1990   int max_semispace_size_;
1991   int initial_semispace_size_;
1992   intptr_t max_old_generation_size_;
1993   intptr_t max_executable_size_;
1994   intptr_t maximum_committed_;
1995
1996   // For keeping track of how much data has survived
1997   // scavenge since last new space expansion.
1998   int survived_since_last_expansion_;
1999
2000   // For keeping track on when to flush RegExp code.
2001   int sweep_generation_;
2002
2003   int always_allocate_scope_depth_;
2004   int linear_allocation_scope_depth_;
2005
2006   // For keeping track of context disposals.
2007   int contexts_disposed_;
2008
2009   int global_ic_age_;
2010
2011   bool flush_monomorphic_ics_;
2012
2013   int scan_on_scavenge_pages_;
2014
2015   NewSpace new_space_;
2016   OldSpace* old_pointer_space_;
2017   OldSpace* old_data_space_;
2018   OldSpace* code_space_;
2019   MapSpace* map_space_;
2020   CellSpace* cell_space_;
2021   PropertyCellSpace* property_cell_space_;
2022   LargeObjectSpace* lo_space_;
2023   HeapState gc_state_;
2024   int gc_post_processing_depth_;
2025
2026   // Returns the amount of external memory registered since last global gc.
2027   int64_t PromotedExternalMemorySize();
2028
2029   unsigned int ms_count_;  // how many mark-sweep collections happened
2030   unsigned int gc_count_;  // how many gc happened
2031
2032   // For post mortem debugging.
2033   static const int kRememberedUnmappedPages = 128;
2034   int remembered_unmapped_pages_index_;
2035   Address remembered_unmapped_pages_[kRememberedUnmappedPages];
2036
2037   // Total length of the strings we failed to flatten since the last GC.
2038   int unflattened_strings_length_;
2039
2040 #define ROOT_ACCESSOR(type, name, camel_name)                                  \
2041   inline void set_##name(type* value) {                                        \
2042     /* The deserializer makes use of the fact that these common roots are */   \
2043     /* never in new space and never on a page that is being compacted.    */   \
2044     ASSERT(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value));  \
2045     roots_[k##camel_name##RootIndex] = value;                                  \
2046   }
2047   ROOT_LIST(ROOT_ACCESSOR)
2048 #undef ROOT_ACCESSOR
2049
2050 #ifdef DEBUG
2051   // If the --gc-interval flag is set to a positive value, this
2052   // variable holds the value indicating the number of allocations
2053   // remain until the next failure and garbage collection.
2054   int allocation_timeout_;
2055 #endif  // DEBUG
2056
2057   // Indicates that the new space should be kept small due to high promotion
2058   // rates caused by the mutator allocating a lot of long-lived objects.
2059   // TODO(hpayer): change to bool if no longer accessed from generated code
2060   intptr_t new_space_high_promotion_mode_active_;
2061
2062   // Limit that triggers a global GC on the next (normally caused) GC.  This
2063   // is checked when we have already decided to do a GC to help determine
2064   // which collector to invoke, before expanding a paged space in the old
2065   // generation and on every allocation in large object space.
2066   intptr_t old_generation_allocation_limit_;
2067
2068   // Used to adjust the limits that control the timing of the next GC.
2069   intptr_t size_of_old_gen_at_last_old_space_gc_;
2070
2071   // Limit on the amount of externally allocated memory allowed
2072   // between global GCs. If reached a global GC is forced.
2073   intptr_t external_allocation_limit_;
2074
2075   // The amount of external memory registered through the API kept alive
2076   // by global handles
2077   int64_t amount_of_external_allocated_memory_;
2078
2079   // Caches the amount of external memory registered at the last global gc.
2080   int64_t amount_of_external_allocated_memory_at_last_global_gc_;
2081
2082   // Indicates that an allocation has failed in the old generation since the
2083   // last GC.
2084   bool old_gen_exhausted_;
2085
2086   // Indicates that inline bump-pointer allocation has been globally disabled
2087   // for all spaces. This is used to disable allocations in generated code.
2088   bool inline_allocation_disabled_;
2089
2090   // Weak list heads, threaded through the objects.
2091   // List heads are initilized lazily and contain the undefined_value at start.
2092   Object* native_contexts_list_;
2093   Object* array_buffers_list_;
2094   Object* allocation_sites_list_;
2095
2096   // WeakHashTable that maps objects embedded in optimized code to dependent
2097   // code list. It is initilized lazily and contains the undefined_value at
2098   // start.
2099   Object* weak_object_to_code_table_;
2100
2101   StoreBufferRebuilder store_buffer_rebuilder_;
2102
2103   struct StringTypeTable {
2104     InstanceType type;
2105     int size;
2106     RootListIndex index;
2107   };
2108
2109   struct ConstantStringTable {
2110     const char* contents;
2111     RootListIndex index;
2112   };
2113
2114   struct StructTable {
2115     InstanceType type;
2116     int size;
2117     RootListIndex index;
2118   };
2119
2120   static const StringTypeTable string_type_table[];
2121   static const ConstantStringTable constant_string_table[];
2122   static const StructTable struct_table[];
2123
2124   // The special hidden string which is an empty string, but does not match
2125   // any string when looked up in properties.
2126   String* hidden_string_;
2127
2128   // GC callback function, called before and after mark-compact GC.
2129   // Allocations in the callback function are disallowed.
2130   struct GCPrologueCallbackPair {
2131     GCPrologueCallbackPair(v8::Isolate::GCPrologueCallback callback,
2132                            GCType gc_type,
2133                            bool pass_isolate)
2134         : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
2135     }
2136     bool operator==(const GCPrologueCallbackPair& pair) const {
2137       return pair.callback == callback;
2138     }
2139     v8::Isolate::GCPrologueCallback callback;
2140     GCType gc_type;
2141     // TODO(dcarney): remove variable
2142     bool pass_isolate_;
2143   };
2144   List<GCPrologueCallbackPair> gc_prologue_callbacks_;
2145
2146   struct GCEpilogueCallbackPair {
2147     GCEpilogueCallbackPair(v8::Isolate::GCPrologueCallback callback,
2148                            GCType gc_type,
2149                            bool pass_isolate)
2150         : callback(callback), gc_type(gc_type), pass_isolate_(pass_isolate) {
2151     }
2152     bool operator==(const GCEpilogueCallbackPair& pair) const {
2153       return pair.callback == callback;
2154     }
2155     v8::Isolate::GCPrologueCallback callback;
2156     GCType gc_type;
2157     // TODO(dcarney): remove variable
2158     bool pass_isolate_;
2159   };
2160   List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
2161
2162   // Support for computing object sizes during GC.
2163   HeapObjectCallback gc_safe_size_of_old_object_;
2164   static int GcSafeSizeOfOldObject(HeapObject* object);
2165
2166   // Update the GC state. Called from the mark-compact collector.
2167   void MarkMapPointersAsEncoded(bool encoded) {
2168     ASSERT(!encoded);
2169     gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
2170   }
2171
2172   // Code that should be run before and after each GC.  Includes some
2173   // reporting/verification activities when compiled with DEBUG set.
2174   void GarbageCollectionPrologue();
2175   void GarbageCollectionEpilogue();
2176
2177   // Pretenuring decisions are made based on feedback collected during new
2178   // space evacuation. Note that between feedback collection and calling this
2179   // method object in old space must not move.
2180   // Right now we only process pretenuring feedback in high promotion mode.
2181   void ProcessPretenuringFeedback();
2182
2183   // Checks whether a global GC is necessary
2184   GarbageCollector SelectGarbageCollector(AllocationSpace space,
2185                                           const char** reason);
2186
2187   // Make sure there is a filler value behind the top of the new space
2188   // so that the GC does not confuse some unintialized/stale memory
2189   // with the allocation memento of the object at the top
2190   void EnsureFillerObjectAtTop();
2191
2192   // Performs garbage collection operation.
2193   // Returns whether there is a chance that another major GC could
2194   // collect more garbage.
2195   bool CollectGarbage(
2196       GarbageCollector collector,
2197       const char* gc_reason,
2198       const char* collector_reason,
2199       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
2200
2201   // Performs garbage collection
2202   // Returns whether there is a chance another major GC could
2203   // collect more garbage.
2204   bool PerformGarbageCollection(
2205       GarbageCollector collector,
2206       GCTracer* tracer,
2207       const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
2208
2209   inline void UpdateOldSpaceLimits();
2210
2211   // Selects the proper allocation space depending on the given object
2212   // size, pretenuring decision, and preferred old-space.
2213   static AllocationSpace SelectSpace(int object_size,
2214                                      AllocationSpace preferred_old_space,
2215                                      PretenureFlag pretenure) {
2216     ASSERT(preferred_old_space == OLD_POINTER_SPACE ||
2217            preferred_old_space == OLD_DATA_SPACE);
2218     if (object_size > Page::kMaxRegularHeapObjectSize) return LO_SPACE;
2219     return (pretenure == TENURED) ? preferred_old_space : NEW_SPACE;
2220   }
2221
2222   // Allocate an uninitialized fixed array.
2223   MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(
2224       int length, PretenureFlag pretenure);
2225
2226   // Allocate an uninitialized fixed double array.
2227   MUST_USE_RESULT MaybeObject* AllocateRawFixedDoubleArray(
2228       int length, PretenureFlag pretenure);
2229
2230   // Allocate an initialized fixed array with the given filler value.
2231   MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithFiller(
2232       int length, PretenureFlag pretenure, Object* filler);
2233
2234   // Initializes a JSObject based on its map.
2235   void InitializeJSObjectFromMap(JSObject* obj,
2236                                  FixedArray* properties,
2237                                  Map* map);
2238   void InitializeAllocationMemento(AllocationMemento* memento,
2239                                    AllocationSite* allocation_site);
2240
2241   bool CreateInitialMaps();
2242   bool CreateInitialObjects();
2243
2244   // These five Create*EntryStub functions are here and forced to not be inlined
2245   // because of a gcc-4.4 bug that assigns wrong vtable entries.
2246   NO_INLINE(void CreateJSEntryStub());
2247   NO_INLINE(void CreateJSConstructEntryStub());
2248
2249   void CreateFixedStubs();
2250
2251   MUST_USE_RESULT MaybeObject* CreateOddball(const char* to_string,
2252                                              Object* to_number,
2253                                              byte kind);
2254
2255   // Allocate a JSArray with no elements
2256   MUST_USE_RESULT MaybeObject* AllocateJSArray(
2257       ElementsKind elements_kind,
2258       PretenureFlag pretenure = NOT_TENURED);
2259
2260   // Allocate empty fixed array.
2261   MUST_USE_RESULT MaybeObject* AllocateEmptyFixedArray();
2262
2263   // Allocate empty external array of given type.
2264   MUST_USE_RESULT MaybeObject* AllocateEmptyExternalArray(
2265       ExternalArrayType array_type);
2266
2267   // Allocate empty fixed typed array of given type.
2268   MUST_USE_RESULT MaybeObject* AllocateEmptyFixedTypedArray(
2269       ExternalArrayType array_type);
2270
2271   // Allocate empty fixed double array.
2272   MUST_USE_RESULT MaybeObject* AllocateEmptyFixedDoubleArray();
2273
2274   // Allocate empty constant pool array.
2275   MUST_USE_RESULT MaybeObject* AllocateEmptyConstantPoolArray();
2276
2277   // Allocate a tenured simple cell.
2278   MUST_USE_RESULT MaybeObject* AllocateCell(Object* value);
2279
2280   // Allocate a tenured JS global property cell initialized with the hole.
2281   MUST_USE_RESULT MaybeObject* AllocatePropertyCell();
2282
2283   // Allocate Box.
2284   MUST_USE_RESULT MaybeObject* AllocateBox(Object* value,
2285                                            PretenureFlag pretenure);
2286
2287   // Performs a minor collection in new generation.
2288   void Scavenge();
2289
2290   // Commits from space if it is uncommitted.
2291   void EnsureFromSpaceIsCommitted();
2292
2293   // Uncommit unused semi space.
2294   bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
2295
2296   // Fill in bogus values in from space
2297   void ZapFromSpace();
2298
2299   static String* UpdateNewSpaceReferenceInExternalStringTableEntry(
2300       Heap* heap,
2301       Object** pointer);
2302
2303   Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
2304   static void ScavengeStoreBufferCallback(Heap* heap,
2305                                           MemoryChunk* page,
2306                                           StoreBufferEvent event);
2307
2308   // Performs a major collection in the whole heap.
2309   void MarkCompact(GCTracer* tracer);
2310
2311   // Code to be run before and after mark-compact.
2312   void MarkCompactPrologue();
2313
2314   void ProcessNativeContexts(WeakObjectRetainer* retainer, bool record_slots);
2315   void ProcessArrayBuffers(WeakObjectRetainer* retainer, bool record_slots);
2316   void ProcessAllocationSites(WeakObjectRetainer* retainer, bool record_slots);
2317
2318   // Deopts all code that contains allocation instruction which are tenured or
2319   // not tenured. Moreover it clears the pretenuring allocation site statistics.
2320   void ResetAllAllocationSitesDependentCode(PretenureFlag flag);
2321
2322   // Evaluates local pretenuring for the old space and calls
2323   // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
2324   // the old space.
2325   void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
2326
2327   // Called on heap tear-down.
2328   void TearDownArrayBuffers();
2329
2330   // Record statistics before and after garbage collection.
2331   void ReportStatisticsBeforeGC();
2332   void ReportStatisticsAfterGC();
2333
2334   // Slow part of scavenge object.
2335   static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
2336
2337   // Initializes a function with a shared part and prototype.
2338   // Note: this code was factored out of AllocateFunction such that
2339   // other parts of the VM could use it. Specifically, a function that creates
2340   // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
2341   // Please note this does not perform a garbage collection.
2342   inline void InitializeFunction(
2343       JSFunction* function,
2344       SharedFunctionInfo* shared,
2345       Object* prototype);
2346
2347   // Total RegExp code ever generated
2348   double total_regexp_code_generated_;
2349
2350   GCTracer* tracer_;
2351
2352   // Allocates a small number to string cache.
2353   MUST_USE_RESULT MaybeObject* AllocateInitialNumberStringCache();
2354   // Creates and installs the full-sized number string cache.
2355   void AllocateFullSizeNumberStringCache();
2356   // Get the length of the number to string cache based on the max semispace
2357   // size.
2358   int FullSizeNumberStringCacheLength();
2359   // Flush the number to string cache.
2360   void FlushNumberStringCache();
2361
2362   // Allocates a fixed-size allocation sites scratchpad.
2363   MUST_USE_RESULT MaybeObject* AllocateAllocationSitesScratchpad();
2364
2365   // Sets used allocation sites entries to undefined.
2366   void FlushAllocationSitesScratchpad();
2367
2368   // Initializes the allocation sites scratchpad with undefined values.
2369   void InitializeAllocationSitesScratchpad();
2370
2371   // Adds an allocation site to the scratchpad if there is space left.
2372   void AddAllocationSiteToScratchpad(AllocationSite* site,
2373                                      ScratchpadSlotMode mode);
2374
2375   void UpdateSurvivalRateTrend(int start_new_space_size);
2376
2377   enum SurvivalRateTrend { INCREASING, STABLE, DECREASING, FLUCTUATING };
2378
2379   static const int kYoungSurvivalRateHighThreshold = 90;
2380   static const int kYoungSurvivalRateLowThreshold = 10;
2381   static const int kYoungSurvivalRateAllowedDeviation = 15;
2382
2383   static const int kOldSurvivalRateLowThreshold = 20;
2384
2385   int young_survivors_after_last_gc_;
2386   int high_survival_rate_period_length_;
2387   int low_survival_rate_period_length_;
2388   double survival_rate_;
2389   SurvivalRateTrend previous_survival_rate_trend_;
2390   SurvivalRateTrend survival_rate_trend_;
2391
2392   void set_survival_rate_trend(SurvivalRateTrend survival_rate_trend) {
2393     ASSERT(survival_rate_trend != FLUCTUATING);
2394     previous_survival_rate_trend_ = survival_rate_trend_;
2395     survival_rate_trend_ = survival_rate_trend;
2396   }
2397
2398   SurvivalRateTrend survival_rate_trend() {
2399     if (survival_rate_trend_ == STABLE) {
2400       return STABLE;
2401     } else if (previous_survival_rate_trend_ == STABLE) {
2402       return survival_rate_trend_;
2403     } else if (survival_rate_trend_ != previous_survival_rate_trend_) {
2404       return FLUCTUATING;
2405     } else {
2406       return survival_rate_trend_;
2407     }
2408   }
2409
2410   bool IsStableOrIncreasingSurvivalTrend() {
2411     switch (survival_rate_trend()) {
2412       case STABLE:
2413       case INCREASING:
2414         return true;
2415       default:
2416         return false;
2417     }
2418   }
2419
2420   bool IsStableOrDecreasingSurvivalTrend() {
2421     switch (survival_rate_trend()) {
2422       case STABLE:
2423       case DECREASING:
2424         return true;
2425       default:
2426         return false;
2427     }
2428   }
2429
2430   bool IsIncreasingSurvivalTrend() {
2431     return survival_rate_trend() == INCREASING;
2432   }
2433
2434   bool IsHighSurvivalRate() {
2435     return high_survival_rate_period_length_ > 0;
2436   }
2437
2438   bool IsLowSurvivalRate() {
2439     return low_survival_rate_period_length_ > 0;
2440   }
2441
2442   void SelectScavengingVisitorsTable();
2443
2444   void StartIdleRound() {
2445     mark_sweeps_since_idle_round_started_ = 0;
2446   }
2447
2448   void FinishIdleRound() {
2449     mark_sweeps_since_idle_round_started_ = kMaxMarkSweepsInIdleRound;
2450     scavenges_since_last_idle_round_ = 0;
2451   }
2452
2453   bool EnoughGarbageSinceLastIdleRound() {
2454     return (scavenges_since_last_idle_round_ >= kIdleScavengeThreshold);
2455   }
2456
2457   // Estimates how many milliseconds a Mark-Sweep would take to complete.
2458   // In idle notification handler we assume that this function will return:
2459   // - a number less than 10 for small heaps, which are less than 8Mb.
2460   // - a number greater than 10 for large heaps, which are greater than 32Mb.
2461   int TimeMarkSweepWouldTakeInMs() {
2462     // Rough estimate of how many megabytes of heap can be processed in 1 ms.
2463     static const int kMbPerMs = 2;
2464
2465     int heap_size_mb = static_cast<int>(SizeOfObjects() / MB);
2466     return heap_size_mb / kMbPerMs;
2467   }
2468
2469   // Returns true if no more GC work is left.
2470   bool IdleGlobalGC();
2471
2472   void AdvanceIdleIncrementalMarking(intptr_t step_size);
2473
2474   void ClearObjectStats(bool clear_last_time_stats = false);
2475
2476   void set_weak_object_to_code_table(Object* value) {
2477     ASSERT(!InNewSpace(value));
2478     weak_object_to_code_table_ = value;
2479   }
2480
2481   Object** weak_object_to_code_table_address() {
2482     return &weak_object_to_code_table_;
2483   }
2484
2485   static const int kInitialStringTableSize = 2048;
2486   static const int kInitialEvalCacheSize = 64;
2487   static const int kInitialNumberStringCacheSize = 256;
2488
2489   // Object counts and used memory by InstanceType
2490   size_t object_counts_[OBJECT_STATS_COUNT];
2491   size_t object_counts_last_time_[OBJECT_STATS_COUNT];
2492   size_t object_sizes_[OBJECT_STATS_COUNT];
2493   size_t object_sizes_last_time_[OBJECT_STATS_COUNT];
2494
2495   // Maximum GC pause.
2496   double max_gc_pause_;
2497
2498   // Total time spent in GC.
2499   double total_gc_time_ms_;
2500
2501   // Maximum size of objects alive after GC.
2502   intptr_t max_alive_after_gc_;
2503
2504   // Minimal interval between two subsequent collections.
2505   double min_in_mutator_;
2506
2507   // Size of objects alive after last GC.
2508   intptr_t alive_after_last_gc_;
2509
2510   double last_gc_end_timestamp_;
2511
2512   // Cumulative GC time spent in marking
2513   double marking_time_;
2514
2515   // Cumulative GC time spent in sweeping
2516   double sweeping_time_;
2517
2518   MarkCompactCollector mark_compact_collector_;
2519
2520   StoreBuffer store_buffer_;
2521
2522   Marking marking_;
2523
2524   IncrementalMarking incremental_marking_;
2525
2526   int number_idle_notifications_;
2527   unsigned int last_idle_notification_gc_count_;
2528   bool last_idle_notification_gc_count_init_;
2529
2530   int mark_sweeps_since_idle_round_started_;
2531   unsigned int gc_count_at_last_idle_gc_;
2532   int scavenges_since_last_idle_round_;
2533
2534   // These two counters are monotomically increasing and never reset.
2535   size_t full_codegen_bytes_generated_;
2536   size_t crankshaft_codegen_bytes_generated_;
2537
2538   // If the --deopt_every_n_garbage_collections flag is set to a positive value,
2539   // this variable holds the number of garbage collections since the last
2540   // deoptimization triggered by garbage collection.
2541   int gcs_since_last_deopt_;
2542
2543 #ifdef VERIFY_HEAP
2544   int no_weak_object_verification_scope_depth_;
2545 #endif
2546
2547   static const int kAllocationSiteScratchpadSize = 256;
2548   int allocation_sites_scratchpad_length_;
2549
2550   static const int kMaxMarkSweepsInIdleRound = 7;
2551   static const int kIdleScavengeThreshold = 5;
2552
2553   // Shared state read by the scavenge collector and set by ScavengeObject.
2554   PromotionQueue promotion_queue_;
2555
2556   // Flag is set when the heap has been configured.  The heap can be repeatedly
2557   // configured through the API until it is set up.
2558   bool configured_;
2559
2560   ExternalStringTable external_string_table_;
2561
2562   VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2563
2564   MemoryChunk* chunks_queued_for_free_;
2565
2566   Mutex relocation_mutex_;
2567
2568   int gc_callbacks_depth_;
2569
2570   friend class Factory;
2571   friend class GCTracer;
2572   friend class AlwaysAllocateScope;
2573   friend class Page;
2574   friend class Isolate;
2575   friend class MarkCompactCollector;
2576   friend class MarkCompactMarkingVisitor;
2577   friend class MapCompact;
2578 #ifdef VERIFY_HEAP
2579   friend class NoWeakObjectVerificationScope;
2580 #endif
2581   friend class GCCallbacksScope;
2582
2583   DISALLOW_COPY_AND_ASSIGN(Heap);
2584 };
2585
2586
2587 class HeapStats {
2588  public:
2589   static const int kStartMarker = 0xDECADE00;
2590   static const int kEndMarker = 0xDECADE01;
2591
2592   int* start_marker;                    //  0
2593   int* new_space_size;                  //  1
2594   int* new_space_capacity;              //  2
2595   intptr_t* old_pointer_space_size;          //  3
2596   intptr_t* old_pointer_space_capacity;      //  4
2597   intptr_t* old_data_space_size;             //  5
2598   intptr_t* old_data_space_capacity;         //  6
2599   intptr_t* code_space_size;                 //  7
2600   intptr_t* code_space_capacity;             //  8
2601   intptr_t* map_space_size;                  //  9
2602   intptr_t* map_space_capacity;              // 10
2603   intptr_t* cell_space_size;                 // 11
2604   intptr_t* cell_space_capacity;             // 12
2605   intptr_t* lo_space_size;                   // 13
2606   int* global_handle_count;             // 14
2607   int* weak_global_handle_count;        // 15
2608   int* pending_global_handle_count;     // 16
2609   int* near_death_global_handle_count;  // 17
2610   int* free_global_handle_count;        // 18
2611   intptr_t* memory_allocator_size;           // 19
2612   intptr_t* memory_allocator_capacity;       // 20
2613   int* objects_per_type;                // 21
2614   int* size_per_type;                   // 22
2615   int* os_error;                        // 23
2616   int* end_marker;                      // 24
2617   intptr_t* property_cell_space_size;   // 25
2618   intptr_t* property_cell_space_capacity;    // 26
2619 };
2620
2621
2622 class AlwaysAllocateScope {
2623  public:
2624   explicit inline AlwaysAllocateScope(Isolate* isolate);
2625   inline ~AlwaysAllocateScope();
2626
2627  private:
2628   // Implicitly disable artificial allocation failures.
2629   Heap* heap_;
2630   DisallowAllocationFailure daf_;
2631 };
2632
2633
2634 #ifdef VERIFY_HEAP
2635 class NoWeakObjectVerificationScope {
2636  public:
2637   inline NoWeakObjectVerificationScope();
2638   inline ~NoWeakObjectVerificationScope();
2639 };
2640 #endif
2641
2642
2643 class GCCallbacksScope {
2644  public:
2645   explicit inline GCCallbacksScope(Heap* heap);
2646   inline ~GCCallbacksScope();
2647
2648   inline bool CheckReenter();
2649
2650  private:
2651   Heap* heap_;
2652 };
2653
2654
2655 // Visitor class to verify interior pointers in spaces that do not contain
2656 // or care about intergenerational references. All heap object pointers have to
2657 // point into the heap to a location that has a map pointer at its first word.
2658 // Caveat: Heap::Contains is an approximation because it can return true for
2659 // objects in a heap space but above the allocation pointer.
2660 class VerifyPointersVisitor: public ObjectVisitor {
2661  public:
2662   inline void VisitPointers(Object** start, Object** end);
2663 };
2664
2665
2666 // Verify that all objects are Smis.
2667 class VerifySmisVisitor: public ObjectVisitor {
2668  public:
2669   inline void VisitPointers(Object** start, Object** end);
2670 };
2671
2672
2673 // Space iterator for iterating over all spaces of the heap.  Returns each space
2674 // in turn, and null when it is done.
2675 class AllSpaces BASE_EMBEDDED {
2676  public:
2677   explicit AllSpaces(Heap* heap) : heap_(heap), counter_(FIRST_SPACE) {}
2678   Space* next();
2679  private:
2680   Heap* heap_;
2681   int counter_;
2682 };
2683
2684
2685 // Space iterator for iterating over all old spaces of the heap: Old pointer
2686 // space, old data space and code space.  Returns each space in turn, and null
2687 // when it is done.
2688 class OldSpaces BASE_EMBEDDED {
2689  public:
2690   explicit OldSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2691   OldSpace* next();
2692  private:
2693   Heap* heap_;
2694   int counter_;
2695 };
2696
2697
2698 // Space iterator for iterating over all the paged spaces of the heap: Map
2699 // space, old pointer space, old data space, code space and cell space.  Returns
2700 // each space in turn, and null when it is done.
2701 class PagedSpaces BASE_EMBEDDED {
2702  public:
2703   explicit PagedSpaces(Heap* heap) : heap_(heap), counter_(OLD_POINTER_SPACE) {}
2704   PagedSpace* next();
2705  private:
2706   Heap* heap_;
2707   int counter_;
2708 };
2709
2710
2711 // Space iterator for iterating over all spaces of the heap.
2712 // For each space an object iterator is provided. The deallocation of the
2713 // returned object iterators is handled by the space iterator.
2714 class SpaceIterator : public Malloced {
2715  public:
2716   explicit SpaceIterator(Heap* heap);
2717   SpaceIterator(Heap* heap, HeapObjectCallback size_func);
2718   virtual ~SpaceIterator();
2719
2720   bool has_next();
2721   ObjectIterator* next();
2722
2723  private:
2724   ObjectIterator* CreateIterator();
2725
2726   Heap* heap_;
2727   int current_space_;  // from enum AllocationSpace.
2728   ObjectIterator* iterator_;  // object iterator for the current space.
2729   HeapObjectCallback size_func_;
2730 };
2731
2732
2733 // A HeapIterator provides iteration over the whole heap. It
2734 // aggregates the specific iterators for the different spaces as
2735 // these can only iterate over one space only.
2736 //
2737 // HeapIterator can skip free list nodes (that is, de-allocated heap
2738 // objects that still remain in the heap). As implementation of free
2739 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2740 // phases. Also, it is forbidden to interrupt iteration in this mode,
2741 // as this will leave heap objects marked (and thus, unusable).
2742 class HeapObjectsFilter;
2743
2744 class HeapIterator BASE_EMBEDDED {
2745  public:
2746   enum HeapObjectsFiltering {
2747     kNoFiltering,
2748     kFilterUnreachable
2749   };
2750
2751   explicit HeapIterator(Heap* heap);
2752   HeapIterator(Heap* heap, HeapObjectsFiltering filtering);
2753   ~HeapIterator();
2754
2755   HeapObject* next();
2756   void reset();
2757
2758  private:
2759   // Perform the initialization.
2760   void Init();
2761   // Perform all necessary shutdown (destruction) work.
2762   void Shutdown();
2763   HeapObject* NextObject();
2764
2765   Heap* heap_;
2766   HeapObjectsFiltering filtering_;
2767   HeapObjectsFilter* filter_;
2768   // Space iterator for iterating all the spaces.
2769   SpaceIterator* space_iterator_;
2770   // Object iterator for the space currently being iterated.
2771   ObjectIterator* object_iterator_;
2772 };
2773
2774
2775 // Cache for mapping (map, property name) into field offset.
2776 // Cleared at startup and prior to mark sweep collection.
2777 class KeyedLookupCache {
2778  public:
2779   // Lookup field offset for (map, name). If absent, -1 is returned.
2780   int Lookup(Map* map, Name* name);
2781
2782   // Update an element in the cache.
2783   void Update(Map* map, Name* name, int field_offset);
2784
2785   // Clear the cache.
2786   void Clear();
2787
2788   static const int kLength = 256;
2789   static const int kCapacityMask = kLength - 1;
2790   static const int kMapHashShift = 5;
2791   static const int kHashMask = -4;  // Zero the last two bits.
2792   static const int kEntriesPerBucket = 4;
2793   static const int kNotFound = -1;
2794
2795   // kEntriesPerBucket should be a power of 2.
2796   STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2797   STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2798
2799  private:
2800   KeyedLookupCache() {
2801     for (int i = 0; i < kLength; ++i) {
2802       keys_[i].map = NULL;
2803       keys_[i].name = NULL;
2804       field_offsets_[i] = kNotFound;
2805     }
2806   }
2807
2808   static inline int Hash(Map* map, Name* name);
2809
2810   // Get the address of the keys and field_offsets arrays.  Used in
2811   // generated code to perform cache lookups.
2812   Address keys_address() {
2813     return reinterpret_cast<Address>(&keys_);
2814   }
2815
2816   Address field_offsets_address() {
2817     return reinterpret_cast<Address>(&field_offsets_);
2818   }
2819
2820   struct Key {
2821     Map* map;
2822     Name* name;
2823   };
2824
2825   Key keys_[kLength];
2826   int field_offsets_[kLength];
2827
2828   friend class ExternalReference;
2829   friend class Isolate;
2830   DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2831 };
2832
2833
2834 // Cache for mapping (map, property name) into descriptor index.
2835 // The cache contains both positive and negative results.
2836 // Descriptor index equals kNotFound means the property is absent.
2837 // Cleared at startup and prior to any gc.
2838 class DescriptorLookupCache {
2839  public:
2840   // Lookup descriptor index for (map, name).
2841   // If absent, kAbsent is returned.
2842   int Lookup(Map* source, Name* name) {
2843     if (!name->IsUniqueName()) return kAbsent;
2844     int index = Hash(source, name);
2845     Key& key = keys_[index];
2846     if ((key.source == source) && (key.name == name)) return results_[index];
2847     return kAbsent;
2848   }
2849
2850   // Update an element in the cache.
2851   void Update(Map* source, Name* name, int result) {
2852     ASSERT(result != kAbsent);
2853     if (name->IsUniqueName()) {
2854       int index = Hash(source, name);
2855       Key& key = keys_[index];
2856       key.source = source;
2857       key.name = name;
2858       results_[index] = result;
2859     }
2860   }
2861
2862   // Clear the cache.
2863   void Clear();
2864
2865   static const int kAbsent = -2;
2866
2867  private:
2868   DescriptorLookupCache() {
2869     for (int i = 0; i < kLength; ++i) {
2870       keys_[i].source = NULL;
2871       keys_[i].name = NULL;
2872       results_[i] = kAbsent;
2873     }
2874   }
2875
2876   static int Hash(Object* source, Name* name) {
2877     // Uses only lower 32 bits if pointers are larger.
2878     uint32_t source_hash =
2879         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(source))
2880             >> kPointerSizeLog2;
2881     uint32_t name_hash =
2882         static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name))
2883             >> kPointerSizeLog2;
2884     return (source_hash ^ name_hash) % kLength;
2885   }
2886
2887   static const int kLength = 64;
2888   struct Key {
2889     Map* source;
2890     Name* name;
2891   };
2892
2893   Key keys_[kLength];
2894   int results_[kLength];
2895
2896   friend class Isolate;
2897   DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2898 };
2899
2900
2901 // GCTracer collects and prints ONE line after each garbage collector
2902 // invocation IFF --trace_gc is used.
2903
2904 class GCTracer BASE_EMBEDDED {
2905  public:
2906   class Scope BASE_EMBEDDED {
2907    public:
2908     enum ScopeId {
2909       EXTERNAL,
2910       MC_MARK,
2911       MC_SWEEP,
2912       MC_SWEEP_NEWSPACE,
2913       MC_SWEEP_OLDSPACE,
2914       MC_EVACUATE_PAGES,
2915       MC_UPDATE_NEW_TO_NEW_POINTERS,
2916       MC_UPDATE_ROOT_TO_NEW_POINTERS,
2917       MC_UPDATE_OLD_TO_NEW_POINTERS,
2918       MC_UPDATE_POINTERS_TO_EVACUATED,
2919       MC_UPDATE_POINTERS_BETWEEN_EVACUATED,
2920       MC_UPDATE_MISC_POINTERS,
2921       MC_WEAKCOLLECTION_PROCESS,
2922       MC_WEAKCOLLECTION_CLEAR,
2923       MC_FLUSH_CODE,
2924       kNumberOfScopes
2925     };
2926
2927     Scope(GCTracer* tracer, ScopeId scope)
2928         : tracer_(tracer),
2929         scope_(scope) {
2930       start_time_ = OS::TimeCurrentMillis();
2931     }
2932
2933     ~Scope() {
2934       ASSERT(scope_ < kNumberOfScopes);  // scope_ is unsigned.
2935       tracer_->scopes_[scope_] += OS::TimeCurrentMillis() - start_time_;
2936     }
2937
2938    private:
2939     GCTracer* tracer_;
2940     ScopeId scope_;
2941     double start_time_;
2942   };
2943
2944   explicit GCTracer(Heap* heap,
2945                     const char* gc_reason,
2946                     const char* collector_reason);
2947   ~GCTracer();
2948
2949   // Sets the collector.
2950   void set_collector(GarbageCollector collector) { collector_ = collector; }
2951
2952   // Sets the GC count.
2953   void set_gc_count(unsigned int count) { gc_count_ = count; }
2954
2955   // Sets the full GC count.
2956   void set_full_gc_count(int count) { full_gc_count_ = count; }
2957
2958   void increment_promoted_objects_size(int object_size) {
2959     promoted_objects_size_ += object_size;
2960   }
2961
2962   void increment_nodes_died_in_new_space() {
2963     nodes_died_in_new_space_++;
2964   }
2965
2966   void increment_nodes_copied_in_new_space() {
2967     nodes_copied_in_new_space_++;
2968   }
2969
2970   void increment_nodes_promoted() {
2971     nodes_promoted_++;
2972   }
2973
2974  private:
2975   // Returns a string matching the collector.
2976   const char* CollectorString();
2977
2978   // Returns size of object in heap (in MB).
2979   inline double SizeOfHeapObjects();
2980
2981   // Timestamp set in the constructor.
2982   double start_time_;
2983
2984   // Size of objects in heap set in constructor.
2985   intptr_t start_object_size_;
2986
2987   // Size of memory allocated from OS set in constructor.
2988   intptr_t start_memory_size_;
2989
2990   // Type of collector.
2991   GarbageCollector collector_;
2992
2993   // A count (including this one, e.g. the first collection is 1) of the
2994   // number of garbage collections.
2995   unsigned int gc_count_;
2996
2997   // A count (including this one) of the number of full garbage collections.
2998   int full_gc_count_;
2999
3000   // Amounts of time spent in different scopes during GC.
3001   double scopes_[Scope::kNumberOfScopes];
3002
3003   // Total amount of space either wasted or contained in one of free lists
3004   // before the current GC.
3005   intptr_t in_free_list_or_wasted_before_gc_;
3006
3007   // Difference between space used in the heap at the beginning of the current
3008   // collection and the end of the previous collection.
3009   intptr_t allocated_since_last_gc_;
3010
3011   // Amount of time spent in mutator that is time elapsed between end of the
3012   // previous collection and the beginning of the current one.
3013   double spent_in_mutator_;
3014
3015   // Size of objects promoted during the current collection.
3016   intptr_t promoted_objects_size_;
3017
3018   // Number of died nodes in the new space.
3019   int nodes_died_in_new_space_;
3020
3021   // Number of copied nodes to the new space.
3022   int nodes_copied_in_new_space_;
3023
3024   // Number of promoted nodes to the old space.
3025   int nodes_promoted_;
3026
3027   // Incremental marking steps counters.
3028   int steps_count_;
3029   double steps_took_;
3030   double longest_step_;
3031   int steps_count_since_last_gc_;
3032   double steps_took_since_last_gc_;
3033
3034   Heap* heap_;
3035
3036   const char* gc_reason_;
3037   const char* collector_reason_;
3038 };
3039
3040
3041 class RegExpResultsCache {
3042  public:
3043   enum ResultsCacheType { REGEXP_MULTIPLE_INDICES, STRING_SPLIT_SUBSTRINGS };
3044
3045   // Attempt to retrieve a cached result.  On failure, 0 is returned as a Smi.
3046   // On success, the returned result is guaranteed to be a COW-array.
3047   static Object* Lookup(Heap* heap,
3048                         String* key_string,
3049                         Object* key_pattern,
3050                         ResultsCacheType type);
3051   // Attempt to add value_array to the cache specified by type.  On success,
3052   // value_array is turned into a COW-array.
3053   static void Enter(Heap* heap,
3054                     String* key_string,
3055                     Object* key_pattern,
3056                     FixedArray* value_array,
3057                     ResultsCacheType type);
3058   static void Clear(FixedArray* cache);
3059   static const int kRegExpResultsCacheSize = 0x100;
3060
3061  private:
3062   static const int kArrayEntriesPerCacheEntry = 4;
3063   static const int kStringOffset = 0;
3064   static const int kPatternOffset = 1;
3065   static const int kArrayOffset = 2;
3066 };
3067
3068
3069 // Abstract base class for checking whether a weak object should be retained.
3070 class WeakObjectRetainer {
3071  public:
3072   virtual ~WeakObjectRetainer() {}
3073
3074   // Return whether this object should be retained. If NULL is returned the
3075   // object has no references. Otherwise the address of the retained object
3076   // should be returned as in some GC situations the object has been moved.
3077   virtual Object* RetainAs(Object* object) = 0;
3078 };
3079
3080
3081 // Intrusive object marking uses least significant bit of
3082 // heap object's map word to mark objects.
3083 // Normally all map words have least significant bit set
3084 // because they contain tagged map pointer.
3085 // If the bit is not set object is marked.
3086 // All objects should be unmarked before resuming
3087 // JavaScript execution.
3088 class IntrusiveMarking {
3089  public:
3090   static bool IsMarked(HeapObject* object) {
3091     return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
3092   }
3093
3094   static void ClearMark(HeapObject* object) {
3095     uintptr_t map_word = object->map_word().ToRawValue();
3096     object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
3097     ASSERT(!IsMarked(object));
3098   }
3099
3100   static void SetMark(HeapObject* object) {
3101     uintptr_t map_word = object->map_word().ToRawValue();
3102     object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
3103     ASSERT(IsMarked(object));
3104   }
3105
3106   static Map* MapOfMarkedObject(HeapObject* object) {
3107     uintptr_t map_word = object->map_word().ToRawValue();
3108     return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
3109   }
3110
3111   static int SizeOfMarkedObject(HeapObject* object) {
3112     return object->SizeFromMap(MapOfMarkedObject(object));
3113   }
3114
3115  private:
3116   static const uintptr_t kNotMarkedBit = 0x1;
3117   STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0);
3118 };
3119
3120
3121 #ifdef DEBUG
3122 // Helper class for tracing paths to a search target Object from all roots.
3123 // The TracePathFrom() method can be used to trace paths from a specific
3124 // object to the search target object.
3125 class PathTracer : public ObjectVisitor {
3126  public:
3127   enum WhatToFind {
3128     FIND_ALL,   // Will find all matches.
3129     FIND_FIRST  // Will stop the search after first match.
3130   };
3131
3132   // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
3133   // after the first match.  If FIND_ALL is specified, then tracing will be
3134   // done for all matches.
3135   PathTracer(Object* search_target,
3136              WhatToFind what_to_find,
3137              VisitMode visit_mode)
3138       : search_target_(search_target),
3139         found_target_(false),
3140         found_target_in_trace_(false),
3141         what_to_find_(what_to_find),
3142         visit_mode_(visit_mode),
3143         object_stack_(20),
3144         no_allocation() {}
3145
3146   virtual void VisitPointers(Object** start, Object** end);
3147
3148   void Reset();
3149   void TracePathFrom(Object** root);
3150
3151   bool found() const { return found_target_; }
3152
3153   static Object* const kAnyGlobalObject;
3154
3155  protected:
3156   class MarkVisitor;
3157   class UnmarkVisitor;
3158
3159   void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
3160   void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
3161   virtual void ProcessResults();
3162
3163   // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3164   static const int kMarkTag = 2;
3165
3166   Object* search_target_;
3167   bool found_target_;
3168   bool found_target_in_trace_;
3169   WhatToFind what_to_find_;
3170   VisitMode visit_mode_;
3171   List<Object*> object_stack_;
3172
3173   DisallowHeapAllocation no_allocation;  // i.e. no gc allowed.
3174
3175  private:
3176   DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
3177 };
3178 #endif  // DEBUG
3179
3180 } }  // namespace v8::internal
3181
3182 #endif  // V8_HEAP_H_