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