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
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.
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.
33 #include "allocation.h"
35 #include "incremental-marking.h"
37 #include "mark-compact.h"
38 #include "objects-visiting.h"
40 #include "splay-tree-inl.h"
41 #include "store-buffer.h"
42 #include "v8-counters.h"
43 #include "v8globals.h"
48 // Defines all the roots in Heap.
49 #define STRONG_ROOT_LIST(V) \
50 V(Map, byte_array_map, ByteArrayMap) \
51 V(Map, free_space_map, FreeSpaceMap) \
52 V(Map, one_pointer_filler_map, OnePointerFillerMap) \
53 V(Map, two_pointer_filler_map, TwoPointerFillerMap) \
54 /* Cluster the most popular ones in a few cache lines here at the top. */ \
55 V(Smi, store_buffer_top, StoreBufferTop) \
56 V(Oddball, undefined_value, UndefinedValue) \
57 V(Oddball, the_hole_value, TheHoleValue) \
58 V(Oddball, null_value, NullValue) \
59 V(Oddball, true_value, TrueValue) \
60 V(Oddball, false_value, FalseValue) \
61 V(Map, global_property_cell_map, GlobalPropertyCellMap) \
62 V(Map, shared_function_info_map, SharedFunctionInfoMap) \
63 V(Map, meta_map, MetaMap) \
64 V(Map, ascii_symbol_map, AsciiSymbolMap) \
65 V(Map, ascii_string_map, AsciiStringMap) \
66 V(Map, heap_number_map, HeapNumberMap) \
67 V(Map, global_context_map, GlobalContextMap) \
68 V(Map, fixed_array_map, FixedArrayMap) \
69 V(Map, code_map, CodeMap) \
70 V(Map, scope_info_map, ScopeInfoMap) \
71 V(Map, fixed_cow_array_map, FixedCOWArrayMap) \
72 V(Map, fixed_double_array_map, FixedDoubleArrayMap) \
73 V(Object, no_interceptor_result_sentinel, NoInterceptorResultSentinel) \
74 V(Map, hash_table_map, HashTableMap) \
75 V(FixedArray, empty_fixed_array, EmptyFixedArray) \
76 V(ByteArray, empty_byte_array, EmptyByteArray) \
77 V(String, empty_string, EmptyString) \
78 V(DescriptorArray, empty_descriptor_array, EmptyDescriptorArray) \
79 V(Smi, stack_limit, StackLimit) \
80 V(Oddball, arguments_marker, ArgumentsMarker) \
81 /* The first 32 roots above this line should be boring from a GC point of */ \
82 /* view. This means they are never in new space and never on a page that */ \
83 /* is being compacted. */ \
84 V(FixedArray, number_string_cache, NumberStringCache) \
85 V(Object, instanceof_cache_function, InstanceofCacheFunction) \
86 V(Object, instanceof_cache_map, InstanceofCacheMap) \
87 V(Object, instanceof_cache_answer, InstanceofCacheAnswer) \
88 V(FixedArray, single_character_string_cache, SingleCharacterStringCache) \
89 V(FixedArray, string_split_cache, StringSplitCache) \
90 V(Object, termination_exception, TerminationException) \
91 V(Smi, hash_seed, HashSeed) \
92 V(Map, string_map, StringMap) \
93 V(Map, symbol_map, SymbolMap) \
94 V(Map, cons_string_map, ConsStringMap) \
95 V(Map, cons_ascii_string_map, ConsAsciiStringMap) \
96 V(Map, sliced_string_map, SlicedStringMap) \
97 V(Map, sliced_ascii_string_map, SlicedAsciiStringMap) \
98 V(Map, cons_symbol_map, ConsSymbolMap) \
99 V(Map, cons_ascii_symbol_map, ConsAsciiSymbolMap) \
100 V(Map, external_symbol_map, ExternalSymbolMap) \
101 V(Map, external_symbol_with_ascii_data_map, ExternalSymbolWithAsciiDataMap) \
102 V(Map, external_ascii_symbol_map, ExternalAsciiSymbolMap) \
103 V(Map, external_string_map, ExternalStringMap) \
104 V(Map, external_string_with_ascii_data_map, ExternalStringWithAsciiDataMap) \
105 V(Map, external_ascii_string_map, ExternalAsciiStringMap) \
106 V(Map, short_external_symbol_map, ShortExternalSymbolMap) \
108 short_external_symbol_with_ascii_data_map, \
109 ShortExternalSymbolWithAsciiDataMap) \
110 V(Map, short_external_ascii_symbol_map, ShortExternalAsciiSymbolMap) \
111 V(Map, short_external_string_map, ShortExternalStringMap) \
113 short_external_string_with_ascii_data_map, \
114 ShortExternalStringWithAsciiDataMap) \
115 V(Map, short_external_ascii_string_map, ShortExternalAsciiStringMap) \
116 V(Map, undetectable_string_map, UndetectableStringMap) \
117 V(Map, undetectable_ascii_string_map, UndetectableAsciiStringMap) \
118 V(Map, external_pixel_array_map, ExternalPixelArrayMap) \
119 V(Map, external_byte_array_map, ExternalByteArrayMap) \
120 V(Map, external_unsigned_byte_array_map, ExternalUnsignedByteArrayMap) \
121 V(Map, external_short_array_map, ExternalShortArrayMap) \
122 V(Map, external_unsigned_short_array_map, ExternalUnsignedShortArrayMap) \
123 V(Map, external_int_array_map, ExternalIntArrayMap) \
124 V(Map, external_unsigned_int_array_map, ExternalUnsignedIntArrayMap) \
125 V(Map, external_float_array_map, ExternalFloatArrayMap) \
126 V(Map, external_double_array_map, ExternalDoubleArrayMap) \
127 V(Map, non_strict_arguments_elements_map, NonStrictArgumentsElementsMap) \
128 V(Map, function_context_map, FunctionContextMap) \
129 V(Map, catch_context_map, CatchContextMap) \
130 V(Map, with_context_map, WithContextMap) \
131 V(Map, block_context_map, BlockContextMap) \
132 V(Map, module_context_map, ModuleContextMap) \
133 V(Map, oddball_map, OddballMap) \
134 V(Map, message_object_map, JSMessageObjectMap) \
135 V(Map, foreign_map, ForeignMap) \
136 V(HeapNumber, nan_value, NanValue) \
137 V(HeapNumber, infinity_value, InfinityValue) \
138 V(HeapNumber, minus_zero_value, MinusZeroValue) \
139 V(Map, neander_map, NeanderMap) \
140 V(JSObject, message_listeners, MessageListeners) \
141 V(Foreign, prototype_accessors, PrototypeAccessors) \
142 V(UnseededNumberDictionary, code_stubs, CodeStubs) \
143 V(UnseededNumberDictionary, non_monomorphic_cache, NonMonomorphicCache) \
144 V(PolymorphicCodeCache, polymorphic_code_cache, PolymorphicCodeCache) \
145 V(Code, js_entry_code, JsEntryCode) \
146 V(Code, js_construct_entry_code, JsConstructEntryCode) \
147 V(FixedArray, natives_source_cache, NativesSourceCache) \
148 V(Object, last_script_id, LastScriptId) \
149 V(Script, empty_script, EmptyScript) \
150 V(Smi, real_stack_limit, RealStackLimit) \
151 V(StringDictionary, intrinsic_function_names, IntrinsicFunctionNames) \
152 V(Smi, arguments_adaptor_deopt_pc_offset, ArgumentsAdaptorDeoptPCOffset) \
153 V(Smi, construct_stub_deopt_pc_offset, ConstructStubDeoptPCOffset)
155 #define ROOT_LIST(V) \
156 STRONG_ROOT_LIST(V) \
157 V(SymbolTable, symbol_table, SymbolTable)
159 #define SYMBOL_LIST(V) \
160 V(Array_symbol, "Array") \
161 V(Object_symbol, "Object") \
162 V(Proto_symbol, "__proto__") \
163 V(StringImpl_symbol, "StringImpl") \
164 V(arguments_symbol, "arguments") \
165 V(Arguments_symbol, "Arguments") \
166 V(call_symbol, "call") \
167 V(apply_symbol, "apply") \
168 V(caller_symbol, "caller") \
169 V(boolean_symbol, "boolean") \
170 V(Boolean_symbol, "Boolean") \
171 V(callee_symbol, "callee") \
172 V(constructor_symbol, "constructor") \
173 V(code_symbol, ".code") \
174 V(result_symbol, ".result") \
175 V(catch_var_symbol, ".catch-var") \
176 V(empty_symbol, "") \
177 V(eval_symbol, "eval") \
178 V(function_symbol, "function") \
179 V(length_symbol, "length") \
180 V(module_symbol, "module") \
181 V(name_symbol, "name") \
182 V(native_symbol, "native") \
183 V(null_symbol, "null") \
184 V(number_symbol, "number") \
185 V(Number_symbol, "Number") \
186 V(nan_symbol, "NaN") \
187 V(RegExp_symbol, "RegExp") \
188 V(source_symbol, "source") \
189 V(global_symbol, "global") \
190 V(ignore_case_symbol, "ignoreCase") \
191 V(multiline_symbol, "multiline") \
192 V(input_symbol, "input") \
193 V(index_symbol, "index") \
194 V(last_index_symbol, "lastIndex") \
195 V(object_symbol, "object") \
196 V(prototype_symbol, "prototype") \
197 V(string_symbol, "string") \
198 V(String_symbol, "String") \
199 V(Date_symbol, "Date") \
200 V(this_symbol, "this") \
201 V(to_string_symbol, "toString") \
202 V(char_at_symbol, "CharAt") \
203 V(undefined_symbol, "undefined") \
204 V(value_of_symbol, "valueOf") \
205 V(InitializeVarGlobal_symbol, "InitializeVarGlobal") \
206 V(InitializeConstGlobal_symbol, "InitializeConstGlobal") \
207 V(KeyedLoadElementMonomorphic_symbol, \
208 "KeyedLoadElementMonomorphic") \
209 V(KeyedStoreElementMonomorphic_symbol, \
210 "KeyedStoreElementMonomorphic") \
211 V(KeyedStoreAndGrowElementMonomorphic_symbol, \
212 "KeyedStoreAndGrowElementMonomorphic") \
213 V(stack_overflow_symbol, "kStackOverflowBoilerplate") \
214 V(illegal_access_symbol, "illegal access") \
215 V(out_of_memory_symbol, "out-of-memory") \
216 V(illegal_execution_state_symbol, "illegal execution state") \
217 V(get_symbol, "get") \
218 V(set_symbol, "set") \
219 V(function_class_symbol, "Function") \
220 V(illegal_argument_symbol, "illegal argument") \
221 V(MakeReferenceError_symbol, "MakeReferenceError") \
222 V(MakeSyntaxError_symbol, "MakeSyntaxError") \
223 V(MakeTypeError_symbol, "MakeTypeError") \
224 V(invalid_lhs_in_assignment_symbol, "invalid_lhs_in_assignment") \
225 V(invalid_lhs_in_for_in_symbol, "invalid_lhs_in_for_in") \
226 V(invalid_lhs_in_postfix_op_symbol, "invalid_lhs_in_postfix_op") \
227 V(invalid_lhs_in_prefix_op_symbol, "invalid_lhs_in_prefix_op") \
228 V(illegal_return_symbol, "illegal_return") \
229 V(illegal_break_symbol, "illegal_break") \
230 V(illegal_continue_symbol, "illegal_continue") \
231 V(unknown_label_symbol, "unknown_label") \
232 V(redeclaration_symbol, "redeclaration") \
233 V(failure_symbol, "<failure>") \
234 V(space_symbol, " ") \
235 V(exec_symbol, "exec") \
236 V(zero_symbol, "0") \
237 V(global_eval_symbol, "GlobalEval") \
238 V(identity_hash_symbol, "v8::IdentityHash") \
239 V(closure_symbol, "(closure)") \
240 V(use_strict, "use strict") \
242 V(anonymous_function_symbol, "(anonymous function)") \
243 V(compare_ic_symbol, ".compare_ic") \
244 V(infinity_symbol, "Infinity") \
245 V(minus_infinity_symbol, "-Infinity") \
246 V(hidden_stack_trace_symbol, "v8::hidden_stack_trace") \
247 V(query_colon_symbol, "(?:)")
249 // Forward declarations.
253 class WeakObjectRetainer;
256 typedef HeapObject* (*ExternalStringTableUpdaterCallback)(Heap* heap,
259 class StoreBufferRebuilder {
261 explicit StoreBufferRebuilder(StoreBuffer* store_buffer)
262 : store_buffer_(store_buffer) {
265 void Callback(MemoryChunk* page, StoreBufferEvent event);
268 StoreBuffer* store_buffer_;
270 // We record in this variable how full the store buffer was when we started
271 // iterating over the current page, finding pointers to new space. If the
272 // store buffer overflows again we can exempt the page from the store buffer
273 // by rewinding to this point instead of having to search the store buffer.
274 Object*** start_of_current_page_;
275 // The current page we are scanning in the store buffer iterator.
276 MemoryChunk* current_page_;
281 // The all static Heap captures the interface to the global object heap.
282 // All JavaScript contexts by this process share the same object heap.
285 class HeapDebugUtils;
289 // A queue of objects promoted during scavenge. Each object is accompanied
290 // by it's size to avoid dereferencing a map pointer for scanning.
291 class PromotionQueue {
293 explicit PromotionQueue(Heap* heap)
304 delete emergency_stack_;
305 emergency_stack_ = NULL;
308 inline void ActivateGuardIfOnTheSamePage();
310 Page* GetHeadPage() {
311 return Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
314 void SetNewLimit(Address limit) {
319 ASSERT(GetHeadPage() == Page::FromAllocationTop(limit));
320 limit_ = reinterpret_cast<intptr_t*>(limit);
322 if (limit_ <= rear_) {
330 return (front_ == rear_) &&
331 (emergency_stack_ == NULL || emergency_stack_->length() == 0);
334 inline void insert(HeapObject* target, int size);
336 void remove(HeapObject** target, int* size) {
338 if (front_ == rear_) {
339 Entry e = emergency_stack_->RemoveLast();
345 if (NewSpacePage::IsAtStart(reinterpret_cast<Address>(front_))) {
346 NewSpacePage* front_page =
347 NewSpacePage::FromAddress(reinterpret_cast<Address>(front_));
348 ASSERT(!front_page->prev_page()->is_anchor());
350 reinterpret_cast<intptr_t*>(front_page->prev_page()->area_end());
352 *target = reinterpret_cast<HeapObject*>(*(--front_));
353 *size = static_cast<int>(*(--front_));
354 // Assert no underflow.
355 SemiSpace::AssertValidRange(reinterpret_cast<Address>(rear_),
356 reinterpret_cast<Address>(front_));
360 // The front of the queue is higher in the memory page chain than the rear.
367 static const int kEntrySizeInWords = 2;
370 Entry(HeapObject* obj, int size) : obj_(obj), size_(size) { }
375 List<Entry>* emergency_stack_;
379 void RelocateQueueHead();
381 DISALLOW_COPY_AND_ASSIGN(PromotionQueue);
385 typedef void (*ScavengingCallback)(Map* map,
390 // External strings table is a place where all external strings are
391 // registered. We need to keep track of such strings to properly
393 // The ExternalStringTable can contain both strings and objects with
394 // external resources. It was not renamed to make the patch simpler.
395 class ExternalStringTable {
397 // Registers an external string.
398 inline void AddString(String* string);
399 // Registers an external object.
400 inline void AddObject(HeapObject* string);
402 inline void Iterate(ObjectVisitor* v);
404 // Restores internal invariant and gets rid of collected strings.
405 // Must be called after each Iterate() that modified the strings.
408 // Destroys all allocated memory.
412 ExternalStringTable() { }
416 inline void Verify();
418 inline void AddOldObject(HeapObject* string);
420 // Notifies the table that only a prefix of the new list is valid.
421 inline void ShrinkNewObjects(int position);
423 // To speed up scavenge collections new space string are kept
424 // separate from old space strings.
425 List<Object*> new_space_strings_;
426 List<Object*> old_space_strings_;
430 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
434 enum ArrayStorageAllocationMode {
435 DONT_INITIALIZE_ARRAY_ELEMENTS,
436 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
441 // Configure heap size before setup. Return false if the heap has been
443 bool ConfigureHeap(int max_semispace_size,
444 intptr_t max_old_gen_size,
445 intptr_t max_executable_size);
446 bool ConfigureHeapDefault();
448 // Initializes the global object heap. If create_heap_objects is true,
449 // also creates the basic non-mutable objects.
450 // Returns whether it succeeded.
451 bool SetUp(bool create_heap_objects);
453 // Destroys all memory allocated by the heap.
456 // Set the stack limit in the roots_ array. Some architectures generate
457 // code that looks here, because it is faster than loading from the static
458 // jslimit_/real_jslimit_ variable in the StackGuard.
459 void SetStackLimits();
461 // Returns whether SetUp has been called.
464 // Returns the maximum amount of memory reserved for the heap. For
465 // the young generation, we reserve 4 times the amount needed for a
466 // semi space. The young generation consists of two semi spaces and
467 // we reserve twice the amount needed for those in order to ensure
468 // that new space can be aligned to its size.
469 intptr_t MaxReserved() {
470 return 4 * reserved_semispace_size_ + max_old_generation_size_;
472 int MaxSemiSpaceSize() { return max_semispace_size_; }
473 int ReservedSemiSpaceSize() { return reserved_semispace_size_; }
474 int InitialSemiSpaceSize() { return initial_semispace_size_; }
475 intptr_t MaxOldGenerationSize() { return max_old_generation_size_; }
476 intptr_t MaxExecutableSize() { return max_executable_size_; }
478 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
479 // more spaces are needed until it reaches the limit.
482 // Returns the amount of memory currently committed for the heap.
483 intptr_t CommittedMemory();
485 // Returns the amount of executable memory currently committed for the heap.
486 intptr_t CommittedMemoryExecutable();
488 // Returns the available bytes in space w/o growing.
489 // Heap doesn't guarantee that it can allocate an object that requires
490 // all available bytes. Check MaxHeapObjectSize() instead.
491 intptr_t Available();
493 // Returns of size of all objects residing in the heap.
494 intptr_t SizeOfObjects();
496 // Return the starting address and a mask for the new space. And-masking an
497 // address with the mask will result in the start address of the new space
498 // for all addresses in either semispace.
499 Address NewSpaceStart() { return new_space_.start(); }
500 uintptr_t NewSpaceMask() { return new_space_.mask(); }
501 Address NewSpaceTop() { return new_space_.top(); }
503 NewSpace* new_space() { return &new_space_; }
504 OldSpace* old_pointer_space() { return old_pointer_space_; }
505 OldSpace* old_data_space() { return old_data_space_; }
506 OldSpace* code_space() { return code_space_; }
507 MapSpace* map_space() { return map_space_; }
508 CellSpace* cell_space() { return cell_space_; }
509 LargeObjectSpace* lo_space() { return lo_space_; }
511 bool always_allocate() { return always_allocate_scope_depth_ != 0; }
512 Address always_allocate_scope_depth_address() {
513 return reinterpret_cast<Address>(&always_allocate_scope_depth_);
515 bool linear_allocation() {
516 return linear_allocation_scope_depth_ != 0;
519 Address* NewSpaceAllocationTopAddress() {
520 return new_space_.allocation_top_address();
522 Address* NewSpaceAllocationLimitAddress() {
523 return new_space_.allocation_limit_address();
526 // Uncommit unused semi space.
527 bool UncommitFromSpace() { return new_space_.UncommitFromSpace(); }
529 // Allocates and initializes a new JavaScript object based on a
531 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
533 // Please note this does not perform a garbage collection.
534 MUST_USE_RESULT MaybeObject* AllocateJSObject(
535 JSFunction* constructor, PretenureFlag pretenure = NOT_TENURED);
537 MUST_USE_RESULT MaybeObject* AllocateJSModule();
539 // Allocate a JSArray with no elements
540 MUST_USE_RESULT MaybeObject* AllocateEmptyJSArray(
541 ElementsKind elements_kind,
542 PretenureFlag pretenure = NOT_TENURED) {
543 return AllocateJSArrayAndStorage(elements_kind, 0, 0,
544 DONT_INITIALIZE_ARRAY_ELEMENTS,
548 // Allocate a JSArray with a specified length but elements that are left
550 MUST_USE_RESULT MaybeObject* AllocateJSArrayAndStorage(
551 ElementsKind elements_kind,
554 ArrayStorageAllocationMode mode = DONT_INITIALIZE_ARRAY_ELEMENTS,
555 PretenureFlag pretenure = NOT_TENURED);
557 // Allocate a JSArray with no elements
558 MUST_USE_RESULT MaybeObject* AllocateJSArrayWithElements(
559 FixedArrayBase* array_base,
560 ElementsKind elements_kind,
561 PretenureFlag pretenure = NOT_TENURED);
563 // Allocates and initializes a new global object based on a constructor.
564 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
566 // Please note this does not perform a garbage collection.
567 MUST_USE_RESULT MaybeObject* AllocateGlobalObject(JSFunction* constructor);
569 // Returns a deep copy of the JavaScript object.
570 // Properties and elements are copied too.
571 // Returns failure if allocation failed.
572 MUST_USE_RESULT MaybeObject* CopyJSObject(JSObject* source);
574 // Allocates the function prototype.
575 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
577 // Please note this does not perform a garbage collection.
578 MUST_USE_RESULT MaybeObject* AllocateFunctionPrototype(JSFunction* function);
580 // Allocates a Harmony proxy or function proxy.
581 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
583 // Please note this does not perform a garbage collection.
584 MUST_USE_RESULT MaybeObject* AllocateJSProxy(Object* handler,
587 MUST_USE_RESULT MaybeObject* AllocateJSFunctionProxy(Object* handler,
589 Object* construct_trap,
592 // Reinitialize a JSReceiver into an (empty) JS object of respective type and
593 // size, but keeping the original prototype. The receiver must have at least
594 // the size of the new object. The object is reinitialized and behaves as an
595 // object that has been freshly allocated.
596 // Returns failure if an error occured, otherwise object.
597 MUST_USE_RESULT MaybeObject* ReinitializeJSReceiver(JSReceiver* object,
601 // Reinitialize an JSGlobalProxy based on a constructor. The object
602 // must have the same size as objects allocated using the
603 // constructor. The object is reinitialized and behaves as an
604 // object that has been freshly allocated using the constructor.
605 MUST_USE_RESULT MaybeObject* ReinitializeJSGlobalProxy(
606 JSFunction* constructor, JSGlobalProxy* global);
608 // Allocates and initializes a new JavaScript object based on a map.
609 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
611 // Please note this does not perform a garbage collection.
612 MUST_USE_RESULT MaybeObject* AllocateJSObjectFromMap(
613 Map* map, PretenureFlag pretenure = NOT_TENURED);
615 // Allocates a heap object based on the map.
616 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
618 // Please note this function does not perform a garbage collection.
619 MUST_USE_RESULT MaybeObject* Allocate(Map* map, AllocationSpace space);
621 // Allocates a JS Map in the heap.
622 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
624 // Please note this function does not perform a garbage collection.
625 MUST_USE_RESULT MaybeObject* AllocateMap(
626 InstanceType instance_type,
628 ElementsKind elements_kind = FAST_ELEMENTS);
630 // Allocates a partial map for bootstrapping.
631 MUST_USE_RESULT MaybeObject* AllocatePartialMap(InstanceType instance_type,
634 // Allocate a map for the specified function
635 MUST_USE_RESULT MaybeObject* AllocateInitialMap(JSFunction* fun);
637 // Allocates an empty code cache.
638 MUST_USE_RESULT MaybeObject* AllocateCodeCache();
640 // Allocates a serialized scope info.
641 MUST_USE_RESULT MaybeObject* AllocateScopeInfo(int length);
643 // Allocates an empty PolymorphicCodeCache.
644 MUST_USE_RESULT MaybeObject* AllocatePolymorphicCodeCache();
646 // Allocates a pre-tenured empty AccessorPair.
647 MUST_USE_RESULT MaybeObject* AllocateAccessorPair();
649 // Allocates an empty TypeFeedbackInfo.
650 MUST_USE_RESULT MaybeObject* AllocateTypeFeedbackInfo();
652 // Allocates an AliasedArgumentsEntry.
653 MUST_USE_RESULT MaybeObject* AllocateAliasedArgumentsEntry(int slot);
655 // Clear the Instanceof cache (used when a prototype changes).
656 inline void ClearInstanceofCache();
658 // Allocates and fully initializes a String. There are two String
659 // encodings: ASCII and two byte. One should choose between the three string
660 // allocation functions based on the encoding of the string buffer used to
661 // initialized the string.
662 // - ...FromAscii initializes the string from a buffer that is ASCII
663 // encoded (it does not check that the buffer is ASCII encoded) and the
664 // result will be ASCII encoded.
665 // - ...FromUTF8 initializes the string from a buffer that is UTF-8
666 // encoded. If the characters are all single-byte characters, the
667 // result will be ASCII encoded, otherwise it will converted to two
669 // - ...FromTwoByte initializes the string from a buffer that is two-byte
670 // encoded. If the characters are all single-byte characters, the
671 // result will be converted to ASCII, otherwise it will be left as
673 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
675 // Please note this does not perform a garbage collection.
676 MUST_USE_RESULT MaybeObject* AllocateStringFromAscii(
677 Vector<const char> str,
678 PretenureFlag pretenure = NOT_TENURED);
679 MUST_USE_RESULT inline MaybeObject* AllocateStringFromUtf8(
680 Vector<const char> str,
681 PretenureFlag pretenure = NOT_TENURED);
682 MUST_USE_RESULT MaybeObject* AllocateStringFromUtf8Slow(
683 Vector<const char> str,
684 PretenureFlag pretenure = NOT_TENURED);
685 MUST_USE_RESULT MaybeObject* AllocateStringFromTwoByte(
686 Vector<const uc16> str,
687 PretenureFlag pretenure = NOT_TENURED);
689 // Allocates a symbol in old space based on the character stream.
690 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
692 // Please note this function does not perform a garbage collection.
693 MUST_USE_RESULT inline MaybeObject* AllocateSymbol(Vector<const char> str,
695 uint32_t hash_field);
697 MUST_USE_RESULT inline MaybeObject* AllocateAsciiSymbol(
698 Vector<const char> str,
699 uint32_t hash_field);
701 MUST_USE_RESULT inline MaybeObject* AllocateTwoByteSymbol(
702 Vector<const uc16> str,
703 uint32_t hash_field);
705 MUST_USE_RESULT MaybeObject* AllocateInternalSymbol(
706 unibrow::CharacterStream* buffer, int chars, uint32_t hash_field);
708 MUST_USE_RESULT MaybeObject* AllocateExternalSymbol(
709 Vector<const char> str,
712 // Allocates and partially initializes a String. There are two String
713 // encodings: ASCII and two byte. These functions allocate a string of the
714 // given length and set its map and length fields. The characters of the
715 // string are uninitialized.
716 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
718 // Please note this does not perform a garbage collection.
719 MUST_USE_RESULT MaybeObject* AllocateRawAsciiString(
721 PretenureFlag pretenure = NOT_TENURED);
722 MUST_USE_RESULT MaybeObject* AllocateRawTwoByteString(
724 PretenureFlag pretenure = NOT_TENURED);
726 // Computes a single character string where the character has code.
727 // A cache is used for ASCII codes.
728 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
729 // failed. Please note this does not perform a garbage collection.
730 MUST_USE_RESULT MaybeObject* LookupSingleCharacterStringFromCode(
733 // Allocate a byte array of the specified length
734 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
736 // Please note this does not perform a garbage collection.
737 MUST_USE_RESULT MaybeObject* AllocateByteArray(int length,
738 PretenureFlag pretenure);
740 // Allocate a non-tenured byte array of the specified length
741 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
743 // Please note this does not perform a garbage collection.
744 MUST_USE_RESULT MaybeObject* AllocateByteArray(int length);
746 // Allocates an external array of the specified length and type.
747 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
749 // Please note this does not perform a garbage collection.
750 MUST_USE_RESULT MaybeObject* AllocateExternalArray(
752 ExternalArrayType array_type,
753 void* external_pointer,
754 PretenureFlag pretenure);
756 // Allocate a tenured JS global property cell.
757 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
759 // Please note this does not perform a garbage collection.
760 MUST_USE_RESULT MaybeObject* AllocateJSGlobalPropertyCell(Object* value);
762 // Allocates a fixed array initialized with undefined values
763 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
765 // Please note this does not perform a garbage collection.
766 MUST_USE_RESULT MaybeObject* AllocateFixedArray(int length,
767 PretenureFlag pretenure);
768 // Allocates a fixed array initialized with undefined values
769 MUST_USE_RESULT MaybeObject* AllocateFixedArray(int length);
771 // Allocates an uninitialized fixed array. It must be filled by the caller.
773 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
775 // Please note this does not perform a garbage collection.
776 MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedArray(int length);
778 // Make a copy of src and return it. Returns
779 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
780 MUST_USE_RESULT inline MaybeObject* CopyFixedArray(FixedArray* src);
782 // Make a copy of src, set the map, and return the copy. Returns
783 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
784 MUST_USE_RESULT MaybeObject* CopyFixedArrayWithMap(FixedArray* src, Map* map);
786 // Make a copy of src and return it. Returns
787 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
788 MUST_USE_RESULT inline MaybeObject* CopyFixedDoubleArray(
789 FixedDoubleArray* src);
791 // Make a copy of src, set the map, and return the copy. Returns
792 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
793 MUST_USE_RESULT MaybeObject* CopyFixedDoubleArrayWithMap(
794 FixedDoubleArray* src, Map* map);
796 // Allocates a fixed array initialized with the hole values.
797 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
799 // Please note this does not perform a garbage collection.
800 MUST_USE_RESULT MaybeObject* AllocateFixedArrayWithHoles(
802 PretenureFlag pretenure = NOT_TENURED);
804 MUST_USE_RESULT MaybeObject* AllocateRawFixedDoubleArray(
806 PretenureFlag pretenure);
808 // Allocates a fixed double array with uninitialized values. Returns
809 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
810 // Please note this does not perform a garbage collection.
811 MUST_USE_RESULT MaybeObject* AllocateUninitializedFixedDoubleArray(
813 PretenureFlag pretenure = NOT_TENURED);
815 // Allocates a fixed double array with hole values. Returns
816 // Failure::RetryAfterGC(requested_bytes, space) if the allocation failed.
817 // Please note this does not perform a garbage collection.
818 MUST_USE_RESULT MaybeObject* AllocateFixedDoubleArrayWithHoles(
820 PretenureFlag pretenure = NOT_TENURED);
822 // AllocateHashTable is identical to AllocateFixedArray except
823 // that the resulting object has hash_table_map as map.
824 MUST_USE_RESULT MaybeObject* AllocateHashTable(
825 int length, PretenureFlag pretenure = NOT_TENURED);
827 // Allocate a global (but otherwise uninitialized) context.
828 MUST_USE_RESULT MaybeObject* AllocateGlobalContext();
830 // Allocate a module context.
831 MUST_USE_RESULT MaybeObject* AllocateModuleContext(Context* previous,
832 ScopeInfo* scope_info);
834 // Allocate a function context.
835 MUST_USE_RESULT MaybeObject* AllocateFunctionContext(int length,
836 JSFunction* function);
838 // Allocate a catch context.
839 MUST_USE_RESULT MaybeObject* AllocateCatchContext(JSFunction* function,
842 Object* thrown_object);
843 // Allocate a 'with' context.
844 MUST_USE_RESULT MaybeObject* AllocateWithContext(JSFunction* function,
846 JSObject* extension);
848 // Allocate a block context.
849 MUST_USE_RESULT MaybeObject* AllocateBlockContext(JSFunction* function,
853 // Allocates a new utility object in the old generation.
854 MUST_USE_RESULT MaybeObject* AllocateStruct(InstanceType type);
856 // Allocates a function initialized with a shared part.
857 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
859 // Please note this does not perform a garbage collection.
860 MUST_USE_RESULT MaybeObject* AllocateFunction(
862 SharedFunctionInfo* shared,
864 PretenureFlag pretenure = TENURED);
866 // Arguments object size.
867 static const int kArgumentsObjectSize =
868 JSObject::kHeaderSize + 2 * kPointerSize;
869 // Strict mode arguments has no callee so it is smaller.
870 static const int kArgumentsObjectSizeStrict =
871 JSObject::kHeaderSize + 1 * kPointerSize;
872 // Indicies for direct access into argument objects.
873 static const int kArgumentsLengthIndex = 0;
874 // callee is only valid in non-strict mode.
875 static const int kArgumentsCalleeIndex = 1;
877 // Allocates an arguments object - optionally with an elements array.
878 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
880 // Please note this does not perform a garbage collection.
881 MUST_USE_RESULT MaybeObject* AllocateArgumentsObject(
882 Object* callee, int length);
884 // Same as NewNumberFromDouble, but may return a preallocated/immutable
885 // number object (e.g., minus_zero_value_, nan_value_)
886 MUST_USE_RESULT MaybeObject* NumberFromDouble(
887 double value, PretenureFlag pretenure = NOT_TENURED);
889 // Allocated a HeapNumber from value.
890 MUST_USE_RESULT MaybeObject* AllocateHeapNumber(
892 PretenureFlag pretenure);
893 // pretenure = NOT_TENURED
894 MUST_USE_RESULT MaybeObject* AllocateHeapNumber(double value);
896 // Converts an int into either a Smi or a HeapNumber object.
897 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
899 // Please note this does not perform a garbage collection.
900 MUST_USE_RESULT inline MaybeObject* NumberFromInt32(
901 int32_t value, PretenureFlag pretenure = NOT_TENURED);
903 // Converts an int into either a Smi or a HeapNumber object.
904 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
906 // Please note this does not perform a garbage collection.
907 MUST_USE_RESULT inline MaybeObject* NumberFromUint32(
908 uint32_t value, PretenureFlag pretenure = NOT_TENURED);
910 // Allocates a new foreign object.
911 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
913 // Please note this does not perform a garbage collection.
914 MUST_USE_RESULT MaybeObject* AllocateForeign(
915 Address address, PretenureFlag pretenure = NOT_TENURED);
917 // Allocates a new SharedFunctionInfo object.
918 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
920 // Please note this does not perform a garbage collection.
921 MUST_USE_RESULT MaybeObject* AllocateSharedFunctionInfo(Object* name);
923 // Allocates a new JSMessageObject object.
924 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
926 // Please note that this does not perform a garbage collection.
927 MUST_USE_RESULT MaybeObject* AllocateJSMessageObject(
934 Object* stack_frames);
936 // Allocates a new cons string object.
937 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
939 // Please note this does not perform a garbage collection.
940 MUST_USE_RESULT MaybeObject* AllocateConsString(String* first,
943 // Allocates a new sub string object which is a substring of an underlying
944 // string buffer stretching from the index start (inclusive) to the index
946 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
948 // Please note this does not perform a garbage collection.
949 MUST_USE_RESULT MaybeObject* AllocateSubString(
953 PretenureFlag pretenure = NOT_TENURED);
955 // Allocate a new external string object, which is backed by a string
956 // resource that resides outside the V8 heap.
957 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
959 // Please note this does not perform a garbage collection.
960 MUST_USE_RESULT MaybeObject* AllocateExternalStringFromAscii(
961 const ExternalAsciiString::Resource* resource);
962 MUST_USE_RESULT MaybeObject* AllocateExternalStringFromTwoByte(
963 const ExternalTwoByteString::Resource* resource);
965 // Finalizes an external string by deleting the associated external
966 // data and clearing the resource pointer.
967 inline void FinalizeExternalString(HeapObject* string);
969 // Allocates an uninitialized object. The memory is non-executable if the
970 // hardware and OS allow.
971 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
973 // Please note this function does not perform a garbage collection.
974 MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes,
975 AllocationSpace space,
976 AllocationSpace retry_space);
978 // Initialize a filler object to keep the ability to iterate over the heap
979 // when shortening objects.
980 void CreateFillerObjectAt(Address addr, int size);
982 // Makes a new native code object
983 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
984 // failed. On success, the pointer to the Code object is stored in the
985 // self_reference. This allows generated code to reference its own Code
986 // object by containing this pointer.
987 // Please note this function does not perform a garbage collection.
988 MUST_USE_RESULT MaybeObject* CreateCode(const CodeDesc& desc,
990 Handle<Object> self_reference,
991 bool immovable = false);
993 MUST_USE_RESULT MaybeObject* CopyCode(Code* code);
995 // Copy the code and scope info part of the code object, but insert
996 // the provided data as the relocation information.
997 MUST_USE_RESULT MaybeObject* CopyCode(Code* code, Vector<byte> reloc_info);
999 // Finds the symbol for string in the symbol table.
1000 // If not found, a new symbol is added to the table and returned.
1001 // Returns Failure::RetryAfterGC(requested_bytes, space) if allocation
1003 // Please note this function does not perform a garbage collection.
1004 MUST_USE_RESULT MaybeObject* LookupSymbol(Vector<const char> str);
1005 MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Vector<const char> str);
1006 MUST_USE_RESULT MaybeObject* LookupTwoByteSymbol(Vector<const uc16> str);
1007 MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(const char* str) {
1008 return LookupSymbol(CStrVector(str));
1010 MUST_USE_RESULT MaybeObject* LookupSymbol(String* str);
1011 MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Handle<SeqAsciiString> string,
1015 bool LookupSymbolIfExists(String* str, String** symbol);
1016 bool LookupTwoCharsSymbolIfExists(String* str, String** symbol);
1018 // Compute the matching symbol map for a string if possible.
1019 // NULL is returned if string is in new space or not flattened.
1020 Map* SymbolMapForString(String* str);
1022 // Tries to flatten a string before compare operation.
1024 // Returns a failure in case it was decided that flattening was
1025 // necessary and failed. Note, if flattening is not necessary the
1026 // string might stay non-flat even when not a failure is returned.
1028 // Please note this function does not perform a garbage collection.
1029 MUST_USE_RESULT inline MaybeObject* PrepareForCompare(String* str);
1031 // Converts the given boolean condition to JavaScript boolean value.
1032 inline Object* ToBoolean(bool condition);
1034 // Code that should be run before and after each GC. Includes some
1035 // reporting/verification activities when compiled with DEBUG set.
1036 void GarbageCollectionPrologue();
1037 void GarbageCollectionEpilogue();
1039 // Performs garbage collection operation.
1040 // Returns whether there is a chance that another major GC could
1041 // collect more garbage.
1042 bool CollectGarbage(AllocationSpace space,
1043 GarbageCollector collector,
1044 const char* gc_reason,
1045 const char* collector_reason);
1047 // Performs garbage collection operation.
1048 // Returns whether there is a chance that another major GC could
1049 // collect more garbage.
1050 inline bool CollectGarbage(AllocationSpace space,
1051 const char* gc_reason = NULL);
1053 static const int kNoGCFlags = 0;
1054 static const int kSweepPreciselyMask = 1;
1055 static const int kReduceMemoryFootprintMask = 2;
1056 static const int kAbortIncrementalMarkingMask = 4;
1058 // Making the heap iterable requires us to sweep precisely and abort any
1059 // incremental marking as well.
1060 static const int kMakeHeapIterableMask =
1061 kSweepPreciselyMask | kAbortIncrementalMarkingMask;
1063 // Performs a full garbage collection. If (flags & kMakeHeapIterableMask) is
1064 // non-zero, then the slower precise sweeper is used, which leaves the heap
1065 // in a state where we can iterate over the heap visiting all objects.
1066 void CollectAllGarbage(int flags, const char* gc_reason = NULL);
1068 // Last hope GC, should try to squeeze as much as possible.
1069 void CollectAllAvailableGarbage(const char* gc_reason = NULL);
1071 // Check whether the heap is currently iterable.
1072 bool IsHeapIterable();
1074 // Ensure that we have swept all spaces in such a way that we can iterate
1075 // over all objects. May cause a GC.
1076 void EnsureHeapIsIterable();
1078 // Notify the heap that a context has been disposed.
1079 int NotifyContextDisposed() { return ++contexts_disposed_; }
1081 // Utility to invoke the scavenger. This is needed in test code to
1082 // ensure correct callback for weak global handles.
1083 void PerformScavenge();
1085 inline void increment_scan_on_scavenge_pages() {
1086 scan_on_scavenge_pages_++;
1087 if (FLAG_gc_verbose) {
1088 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1092 inline void decrement_scan_on_scavenge_pages() {
1093 scan_on_scavenge_pages_--;
1094 if (FLAG_gc_verbose) {
1095 PrintF("Scan-on-scavenge pages: %d\n", scan_on_scavenge_pages_);
1099 PromotionQueue* promotion_queue() { return &promotion_queue_; }
1102 // Utility used with flag gc-greedy.
1103 void GarbageCollectionGreedyCheck();
1106 void AddGCPrologueCallback(
1107 GCEpilogueCallback callback, GCType gc_type_filter);
1108 void RemoveGCPrologueCallback(GCEpilogueCallback callback);
1110 void AddGCEpilogueCallback(
1111 GCEpilogueCallback callback, GCType gc_type_filter);
1112 void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
1114 void SetGlobalGCPrologueCallback(GCCallback callback) {
1115 ASSERT((callback == NULL) ^ (global_gc_prologue_callback_ == NULL));
1116 global_gc_prologue_callback_ = callback;
1118 void SetGlobalGCEpilogueCallback(GCCallback callback) {
1119 ASSERT((callback == NULL) ^ (global_gc_epilogue_callback_ == NULL));
1120 global_gc_epilogue_callback_ = callback;
1123 // Heap root getters. We have versions with and without type::cast() here.
1124 // You can't use type::cast during GC because the assert fails.
1125 // TODO(1490): Try removing the unchecked accessors, now that GC marking does
1126 // not corrupt the map.
1127 #define ROOT_ACCESSOR(type, name, camel_name) \
1129 return type::cast(roots_[k##camel_name##RootIndex]); \
1131 type* raw_unchecked_##name() { \
1132 return reinterpret_cast<type*>(roots_[k##camel_name##RootIndex]); \
1134 ROOT_LIST(ROOT_ACCESSOR)
1135 #undef ROOT_ACCESSOR
1137 // Utility type maps
1138 #define STRUCT_MAP_ACCESSOR(NAME, Name, name) \
1139 Map* name##_map() { \
1140 return Map::cast(roots_[k##Name##MapRootIndex]); \
1142 STRUCT_LIST(STRUCT_MAP_ACCESSOR)
1143 #undef STRUCT_MAP_ACCESSOR
1145 #define SYMBOL_ACCESSOR(name, str) String* name() { \
1146 return String::cast(roots_[k##name##RootIndex]); \
1148 SYMBOL_LIST(SYMBOL_ACCESSOR)
1149 #undef SYMBOL_ACCESSOR
1151 // The hidden_symbol is special because it is the empty string, but does
1152 // not match the empty string.
1153 String* hidden_symbol() { return hidden_symbol_; }
1155 void set_global_contexts_list(Object* object) {
1156 global_contexts_list_ = object;
1158 Object* global_contexts_list() { return global_contexts_list_; }
1160 // Number of mark-sweeps.
1161 int ms_count() { return ms_count_; }
1163 // Iterates over all roots in the heap.
1164 void IterateRoots(ObjectVisitor* v, VisitMode mode);
1165 // Iterates over all strong roots in the heap.
1166 void IterateStrongRoots(ObjectVisitor* v, VisitMode mode);
1167 // Iterates over all the other roots in the heap.
1168 void IterateWeakRoots(ObjectVisitor* v, VisitMode mode);
1170 // Iterate pointers to from semispace of new space found in memory interval
1171 // from start to end.
1172 void IterateAndMarkPointersToFromSpace(Address start,
1174 ObjectSlotCallback callback);
1176 // Returns whether the object resides in new space.
1177 inline bool InNewSpace(Object* object);
1178 inline bool InNewSpace(Address addr);
1179 inline bool InNewSpacePage(Address addr);
1180 inline bool InFromSpace(Object* object);
1181 inline bool InToSpace(Object* object);
1183 // Checks whether an address/object in the heap (including auxiliary
1184 // area and unused area).
1185 bool Contains(Address addr);
1186 bool Contains(HeapObject* value);
1188 // Checks whether an address/object in a space.
1189 // Currently used by tests, serialization and heap verification only.
1190 bool InSpace(Address addr, AllocationSpace space);
1191 bool InSpace(HeapObject* value, AllocationSpace space);
1193 // Finds out which space an object should get promoted to based on its type.
1194 inline OldSpace* TargetSpace(HeapObject* object);
1195 inline AllocationSpace TargetSpaceId(InstanceType type);
1197 // Sets the stub_cache_ (only used when expanding the dictionary).
1198 void public_set_code_stubs(UnseededNumberDictionary* value) {
1199 roots_[kCodeStubsRootIndex] = value;
1202 // Support for computing object sizes for old objects during GCs. Returns
1203 // a function that is guaranteed to be safe for computing object sizes in
1204 // the current GC phase.
1205 HeapObjectCallback GcSafeSizeOfOldObjectFunction() {
1206 return gc_safe_size_of_old_object_;
1209 // Sets the non_monomorphic_cache_ (only used when expanding the dictionary).
1210 void public_set_non_monomorphic_cache(UnseededNumberDictionary* value) {
1211 roots_[kNonMonomorphicCacheRootIndex] = value;
1214 void public_set_empty_script(Script* script) {
1215 roots_[kEmptyScriptRootIndex] = script;
1218 void public_set_store_buffer_top(Address* top) {
1219 roots_[kStoreBufferTopRootIndex] = reinterpret_cast<Smi*>(top);
1222 // Update the next script id.
1223 inline void SetLastScriptId(Object* last_script_id);
1225 // Generated code can embed this address to get access to the roots.
1226 Object** roots_array_start() { return roots_; }
1228 Address* store_buffer_top_address() {
1229 return reinterpret_cast<Address*>(&roots_[kStoreBufferTopRootIndex]);
1232 // Get address of global contexts list for serialization support.
1233 Object** global_contexts_list_address() {
1234 return &global_contexts_list_;
1239 void PrintHandles();
1241 // Verify the heap is in its normal state before or after a GC.
1244 // Verify that AccessorPairs are not shared, i.e. make sure that they have
1245 // exactly one pointer to them.
1246 void VerifyNoAccessorPairSharing();
1248 void OldPointerSpaceCheckStoreBuffer();
1249 void MapSpaceCheckStoreBuffer();
1250 void LargeObjectSpaceCheckStoreBuffer();
1252 // Report heap statistics.
1253 void ReportHeapStatistics(const char* title);
1254 void ReportCodeStatistics(const char* title);
1256 // Fill in bogus values in from space
1257 void ZapFromSpace();
1260 // Print short heap statistics.
1261 void PrintShortHeapStatistics();
1263 // Makes a new symbol object
1264 // Returns Failure::RetryAfterGC(requested_bytes, space) if the allocation
1266 // Please note this function does not perform a garbage collection.
1267 MUST_USE_RESULT MaybeObject* CreateSymbol(
1268 const char* str, int length, int hash);
1269 MUST_USE_RESULT MaybeObject* CreateSymbol(String* str);
1271 // Write barrier support for address[offset] = o.
1272 inline void RecordWrite(Address address, int offset);
1274 // Write barrier support for address[start : start + len[ = o.
1275 inline void RecordWrites(Address address, int start, int len);
1277 // Given an address occupied by a live code object, return that object.
1278 Object* FindCodeObject(Address a);
1280 // Invoke Shrink on shrinkable spaces.
1283 enum HeapState { NOT_IN_GC, SCAVENGE, MARK_COMPACT };
1284 inline HeapState gc_state() { return gc_state_; }
1286 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
1289 bool IsAllocationAllowed() { return allocation_allowed_; }
1290 inline bool allow_allocation(bool enable);
1292 bool disallow_allocation_failure() {
1293 return disallow_allocation_failure_;
1296 void TracePathToObject(Object* target);
1297 void TracePathToGlobal();
1300 // Callback function passed to Heap::Iterate etc. Copies an object if
1301 // necessary, the object might be promoted to an old space. The caller must
1302 // ensure the precondition that the object is (a) a heap object and (b) in
1303 // the heap's from space.
1304 static inline void ScavengePointer(HeapObject** p);
1305 static inline void ScavengeObject(HeapObject** p, HeapObject* object);
1307 // Commits from space if it is uncommitted.
1308 void EnsureFromSpaceIsCommitted();
1310 // Support for partial snapshots. After calling this we can allocate a
1311 // certain number of bytes using only linear allocation (with a
1312 // LinearAllocationScope and an AlwaysAllocateScope) without using freelists
1313 // or causing a GC. It returns true of space was reserved or false if a GC is
1314 // needed. For paged spaces the space requested must include the space wasted
1315 // at the end of each page when allocating linearly.
1318 int pointer_space_size,
1319 int data_space_size,
1320 int code_space_size,
1322 int cell_space_size,
1323 int large_object_size);
1326 // Support for the API.
1329 bool CreateApiObjects();
1331 // Attempt to find the number in a small cache. If we finds it, return
1332 // the string representation of the number. Otherwise return undefined.
1333 Object* GetNumberStringCache(Object* number);
1335 // Update the cache with a new number-string pair.
1336 void SetNumberStringCache(Object* number, String* str);
1338 // Adjusts the amount of registered external memory.
1339 // Returns the adjusted value.
1340 inline intptr_t AdjustAmountOfExternalAllocatedMemory(
1341 intptr_t change_in_bytes);
1343 // Allocate uninitialized fixed array.
1344 MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(int length);
1345 MUST_USE_RESULT MaybeObject* AllocateRawFixedArray(int length,
1346 PretenureFlag pretenure);
1348 inline intptr_t PromotedTotalSize() {
1349 return PromotedSpaceSizeOfObjects() + PromotedExternalMemorySize();
1352 // True if we have reached the allocation limit in the old generation that
1353 // should force the next GC (caused normally) to be a full one.
1354 inline bool OldGenerationPromotionLimitReached() {
1355 return PromotedTotalSize() > old_gen_promotion_limit_;
1358 inline intptr_t OldGenerationSpaceAvailable() {
1359 return old_gen_allocation_limit_ - PromotedTotalSize();
1362 inline intptr_t OldGenerationCapacityAvailable() {
1363 return max_old_generation_size_ - PromotedTotalSize();
1366 static const intptr_t kMinimumPromotionLimit = 5 * Page::kPageSize;
1367 static const intptr_t kMinimumAllocationLimit =
1368 8 * (Page::kPageSize > MB ? Page::kPageSize : MB);
1370 intptr_t OldGenPromotionLimit(intptr_t old_gen_size) {
1371 const int divisor = FLAG_stress_compaction ? 10 : 3;
1373 Max(old_gen_size + old_gen_size / divisor, kMinimumPromotionLimit);
1374 limit += new_space_.Capacity();
1375 limit *= old_gen_limit_factor_;
1376 intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1377 return Min(limit, halfway_to_the_max);
1380 intptr_t OldGenAllocationLimit(intptr_t old_gen_size) {
1381 const int divisor = FLAG_stress_compaction ? 8 : 2;
1383 Max(old_gen_size + old_gen_size / divisor, kMinimumAllocationLimit);
1384 limit += new_space_.Capacity();
1385 limit *= old_gen_limit_factor_;
1386 intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
1387 return Min(limit, halfway_to_the_max);
1390 // Implements the corresponding V8 API function.
1391 bool IdleNotification(int hint);
1393 // Declare all the root indices.
1394 enum RootListIndex {
1395 #define ROOT_INDEX_DECLARATION(type, name, camel_name) k##camel_name##RootIndex,
1396 STRONG_ROOT_LIST(ROOT_INDEX_DECLARATION)
1397 #undef ROOT_INDEX_DECLARATION
1399 // Utility type maps
1400 #define DECLARE_STRUCT_MAP(NAME, Name, name) k##Name##MapRootIndex,
1401 STRUCT_LIST(DECLARE_STRUCT_MAP)
1402 #undef DECLARE_STRUCT_MAP
1404 #define SYMBOL_INDEX_DECLARATION(name, str) k##name##RootIndex,
1405 SYMBOL_LIST(SYMBOL_INDEX_DECLARATION)
1406 #undef SYMBOL_DECLARATION
1408 kSymbolTableRootIndex,
1409 kStrongRootListLength = kSymbolTableRootIndex,
1413 STATIC_CHECK(kUndefinedValueRootIndex == Internals::kUndefinedValueRootIndex);
1414 STATIC_CHECK(kNullValueRootIndex == Internals::kNullValueRootIndex);
1415 STATIC_CHECK(kTrueValueRootIndex == Internals::kTrueValueRootIndex);
1416 STATIC_CHECK(kFalseValueRootIndex == Internals::kFalseValueRootIndex);
1417 STATIC_CHECK(kempty_symbolRootIndex == Internals::kEmptySymbolRootIndex);
1419 MUST_USE_RESULT MaybeObject* NumberToString(
1420 Object* number, bool check_number_string_cache = true);
1421 MUST_USE_RESULT MaybeObject* Uint32ToString(
1422 uint32_t value, bool check_number_string_cache = true);
1424 Map* MapForExternalArrayType(ExternalArrayType array_type);
1425 RootListIndex RootIndexForExternalArrayType(
1426 ExternalArrayType array_type);
1428 void RecordStats(HeapStats* stats, bool take_snapshot = false);
1430 // Copy block of memory from src to dst. Size of block should be aligned
1432 static inline void CopyBlock(Address dst, Address src, int byte_size);
1434 // Optimized version of memmove for blocks with pointer size aligned sizes and
1435 // pointer size aligned addresses.
1436 static inline void MoveBlock(Address dst, Address src, int byte_size);
1438 // Check new space expansion criteria and expand semispaces if it was hit.
1439 void CheckNewSpaceExpansionCriteria();
1441 inline void IncrementYoungSurvivorsCounter(int survived) {
1442 ASSERT(survived >= 0);
1443 young_survivors_after_last_gc_ = survived;
1444 survived_since_last_expansion_ += survived;
1447 inline bool NextGCIsLikelyToBeFull() {
1448 if (FLAG_gc_global) return true;
1450 if (FLAG_stress_compaction && (gc_count_ & 1) != 0) return true;
1452 intptr_t total_promoted = PromotedTotalSize();
1454 intptr_t adjusted_promotion_limit =
1455 old_gen_promotion_limit_ - new_space_.Capacity();
1457 if (total_promoted >= adjusted_promotion_limit) return true;
1459 intptr_t adjusted_allocation_limit =
1460 old_gen_allocation_limit_ - new_space_.Capacity() / 5;
1462 if (PromotedSpaceSizeOfObjects() >= adjusted_allocation_limit) return true;
1468 void UpdateNewSpaceReferencesInExternalStringTable(
1469 ExternalStringTableUpdaterCallback updater_func);
1471 void UpdateReferencesInExternalStringTable(
1472 ExternalStringTableUpdaterCallback updater_func);
1474 void ProcessWeakReferences(WeakObjectRetainer* retainer);
1476 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
1478 // Helper function that governs the promotion policy from new space to
1479 // old. If the object's old address lies below the new space's age
1480 // mark or if we've already filled the bottom 1/16th of the to space,
1481 // we try to promote this object.
1482 inline bool ShouldBePromoted(Address old_address, int object_size);
1484 int MaxObjectSizeInNewSpace() { return kMaxObjectSizeInNewSpace; }
1486 void ClearJSFunctionResultCaches();
1488 void ClearNormalizedMapCaches();
1490 // Clears the cache of ICs related to this map.
1491 void ClearCacheOnMap(Map* map) {
1492 if (FLAG_cleanup_code_caches_at_gc) {
1493 map->ClearCodeCache(this);
1497 GCTracer* tracer() { return tracer_; }
1499 // Returns the size of objects residing in non new spaces.
1500 intptr_t PromotedSpaceSizeOfObjects();
1502 double total_regexp_code_generated() { return total_regexp_code_generated_; }
1503 void IncreaseTotalRegexpCodeGenerated(int size) {
1504 total_regexp_code_generated_ += size;
1507 // Returns maximum GC pause.
1508 int get_max_gc_pause() { return max_gc_pause_; }
1510 // Returns maximum size of objects alive after GC.
1511 intptr_t get_max_alive_after_gc() { return max_alive_after_gc_; }
1513 // Returns minimal interval between two subsequent collections.
1514 int get_min_in_mutator() { return min_in_mutator_; }
1516 MarkCompactCollector* mark_compact_collector() {
1517 return &mark_compact_collector_;
1520 StoreBuffer* store_buffer() {
1521 return &store_buffer_;
1524 Marking* marking() {
1528 IncrementalMarking* incremental_marking() {
1529 return &incremental_marking_;
1532 bool IsSweepingComplete() {
1533 return old_data_space()->IsSweepingComplete() &&
1534 old_pointer_space()->IsSweepingComplete();
1537 bool AdvanceSweepers(int step_size) {
1538 bool sweeping_complete = old_data_space()->AdvanceSweeper(step_size);
1539 sweeping_complete &= old_pointer_space()->AdvanceSweeper(step_size);
1540 return sweeping_complete;
1543 ExternalStringTable* external_string_table() {
1544 return &external_string_table_;
1547 // Returns the current sweep generation.
1548 int sweep_generation() {
1549 return sweep_generation_;
1552 inline Isolate* isolate();
1554 inline void CallGlobalGCPrologueCallback() {
1555 if (global_gc_prologue_callback_ != NULL) global_gc_prologue_callback_();
1558 inline void CallGlobalGCEpilogueCallback() {
1559 if (global_gc_epilogue_callback_ != NULL) global_gc_epilogue_callback_();
1562 inline bool OldGenerationAllocationLimitReached();
1564 inline void DoScavengeObject(Map* map, HeapObject** slot, HeapObject* obj) {
1565 scavenging_visitors_table_.GetVisitor(map)(map, slot, obj);
1568 void QueueMemoryChunkForFree(MemoryChunk* chunk);
1569 void FreeQueuedChunks();
1571 // Completely clear the Instanceof cache (to stop it keeping objects alive
1573 inline void CompletelyClearInstanceofCache();
1575 // The roots that have an index less than this are always in old space.
1576 static const int kOldSpaceRoots = 0x20;
1578 uint32_t HashSeed() {
1579 uint32_t seed = static_cast<uint32_t>(hash_seed()->value());
1580 ASSERT(FLAG_randomize_hashes || seed == 0);
1584 void SetArgumentsAdaptorDeoptPCOffset(int pc_offset) {
1585 ASSERT(arguments_adaptor_deopt_pc_offset() == Smi::FromInt(0));
1586 set_arguments_adaptor_deopt_pc_offset(Smi::FromInt(pc_offset));
1589 void SetConstructStubDeoptPCOffset(int pc_offset) {
1590 ASSERT(construct_stub_deopt_pc_offset() == Smi::FromInt(0));
1591 set_construct_stub_deopt_pc_offset(Smi::FromInt(pc_offset));
1594 // For post mortem debugging.
1595 void RememberUnmappedPage(Address page, bool compacted);
1597 // Global inline caching age: it is incremented on some GCs after context
1598 // disposal. We use it to flush inline caches.
1599 int global_ic_age() {
1600 return global_ic_age_;
1603 void AgeInlineCaches() {
1610 // This can be calculated directly from a pointer to the heap; however, it is
1611 // more expedient to get at the isolate directly from within Heap methods.
1614 Object* roots_[kRootListLength];
1616 intptr_t code_range_size_;
1617 int reserved_semispace_size_;
1618 int max_semispace_size_;
1619 int initial_semispace_size_;
1620 intptr_t max_old_generation_size_;
1621 intptr_t max_executable_size_;
1623 // For keeping track of how much data has survived
1624 // scavenge since last new space expansion.
1625 int survived_since_last_expansion_;
1627 // For keeping track on when to flush RegExp code.
1628 int sweep_generation_;
1630 int always_allocate_scope_depth_;
1631 int linear_allocation_scope_depth_;
1633 // For keeping track of context disposals.
1634 int contexts_disposed_;
1638 int scan_on_scavenge_pages_;
1640 #if defined(V8_TARGET_ARCH_X64)
1641 static const int kMaxObjectSizeInNewSpace = 1024*KB;
1643 static const int kMaxObjectSizeInNewSpace = 512*KB;
1646 NewSpace new_space_;
1647 OldSpace* old_pointer_space_;
1648 OldSpace* old_data_space_;
1649 OldSpace* code_space_;
1650 MapSpace* map_space_;
1651 CellSpace* cell_space_;
1652 LargeObjectSpace* lo_space_;
1653 HeapState gc_state_;
1654 int gc_post_processing_depth_;
1656 // Returns the amount of external memory registered since last global gc.
1657 intptr_t PromotedExternalMemorySize();
1659 int ms_count_; // how many mark-sweep collections happened
1660 unsigned int gc_count_; // how many gc happened
1662 // For post mortem debugging.
1663 static const int kRememberedUnmappedPages = 128;
1664 int remembered_unmapped_pages_index_;
1665 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
1667 // Total length of the strings we failed to flatten since the last GC.
1668 int unflattened_strings_length_;
1670 #define ROOT_ACCESSOR(type, name, camel_name) \
1671 inline void set_##name(type* value) { \
1672 /* The deserializer makes use of the fact that these common roots are */ \
1673 /* never in new space and never on a page that is being compacted. */ \
1674 ASSERT(k##camel_name##RootIndex >= kOldSpaceRoots || !InNewSpace(value)); \
1675 roots_[k##camel_name##RootIndex] = value; \
1677 ROOT_LIST(ROOT_ACCESSOR)
1678 #undef ROOT_ACCESSOR
1681 bool allocation_allowed_;
1683 // If the --gc-interval flag is set to a positive value, this
1684 // variable holds the value indicating the number of allocations
1685 // remain until the next failure and garbage collection.
1686 int allocation_timeout_;
1688 // Do we expect to be able to handle allocation failure at this
1690 bool disallow_allocation_failure_;
1692 HeapDebugUtils* debug_utils_;
1695 // Indicates that the new space should be kept small due to high promotion
1696 // rates caused by the mutator allocating a lot of long-lived objects.
1697 bool new_space_high_promotion_mode_active_;
1699 // Limit that triggers a global GC on the next (normally caused) GC. This
1700 // is checked when we have already decided to do a GC to help determine
1701 // which collector to invoke.
1702 intptr_t old_gen_promotion_limit_;
1704 // Limit that triggers a global GC as soon as is reasonable. This is
1705 // checked before expanding a paged space in the old generation and on
1706 // every allocation in large object space.
1707 intptr_t old_gen_allocation_limit_;
1709 // Sometimes the heuristics dictate that those limits are increased. This
1710 // variable records that fact.
1711 int old_gen_limit_factor_;
1713 // Used to adjust the limits that control the timing of the next GC.
1714 intptr_t size_of_old_gen_at_last_old_space_gc_;
1716 // Limit on the amount of externally allocated memory allowed
1717 // between global GCs. If reached a global GC is forced.
1718 intptr_t external_allocation_limit_;
1720 // The amount of external memory registered through the API kept alive
1721 // by global handles
1722 intptr_t amount_of_external_allocated_memory_;
1724 // Caches the amount of external memory registered at the last global gc.
1725 intptr_t amount_of_external_allocated_memory_at_last_global_gc_;
1727 // Indicates that an allocation has failed in the old generation since the
1729 int old_gen_exhausted_;
1731 Object* global_contexts_list_;
1733 StoreBufferRebuilder store_buffer_rebuilder_;
1735 struct StringTypeTable {
1738 RootListIndex index;
1741 struct ConstantSymbolTable {
1742 const char* contents;
1743 RootListIndex index;
1746 struct StructTable {
1749 RootListIndex index;
1752 static const StringTypeTable string_type_table[];
1753 static const ConstantSymbolTable constant_symbol_table[];
1754 static const StructTable struct_table[];
1756 // The special hidden symbol which is an empty string, but does not match
1757 // any string when looked up in properties.
1758 String* hidden_symbol_;
1760 // GC callback function, called before and after mark-compact GC.
1761 // Allocations in the callback function are disallowed.
1762 struct GCPrologueCallbackPair {
1763 GCPrologueCallbackPair(GCPrologueCallback callback, GCType gc_type)
1764 : callback(callback), gc_type(gc_type) {
1766 bool operator==(const GCPrologueCallbackPair& pair) const {
1767 return pair.callback == callback;
1769 GCPrologueCallback callback;
1772 List<GCPrologueCallbackPair> gc_prologue_callbacks_;
1774 struct GCEpilogueCallbackPair {
1775 GCEpilogueCallbackPair(GCEpilogueCallback callback, GCType gc_type)
1776 : callback(callback), gc_type(gc_type) {
1778 bool operator==(const GCEpilogueCallbackPair& pair) const {
1779 return pair.callback == callback;
1781 GCEpilogueCallback callback;
1784 List<GCEpilogueCallbackPair> gc_epilogue_callbacks_;
1786 GCCallback global_gc_prologue_callback_;
1787 GCCallback global_gc_epilogue_callback_;
1789 // Support for computing object sizes during GC.
1790 HeapObjectCallback gc_safe_size_of_old_object_;
1791 static int GcSafeSizeOfOldObject(HeapObject* object);
1793 // Update the GC state. Called from the mark-compact collector.
1794 void MarkMapPointersAsEncoded(bool encoded) {
1796 gc_safe_size_of_old_object_ = &GcSafeSizeOfOldObject;
1799 // Checks whether a global GC is necessary
1800 GarbageCollector SelectGarbageCollector(AllocationSpace space,
1801 const char** reason);
1803 // Performs garbage collection
1804 // Returns whether there is a chance another major GC could
1805 // collect more garbage.
1806 bool PerformGarbageCollection(GarbageCollector collector,
1810 inline void UpdateOldSpaceLimits();
1812 // Allocate an uninitialized object in map space. The behavior is identical
1813 // to Heap::AllocateRaw(size_in_bytes, MAP_SPACE), except that (a) it doesn't
1814 // have to test the allocation space argument and (b) can reduce code size
1815 // (since both AllocateRaw and AllocateRawMap are inlined).
1816 MUST_USE_RESULT inline MaybeObject* AllocateRawMap();
1818 // Allocate an uninitialized object in the global property cell space.
1819 MUST_USE_RESULT inline MaybeObject* AllocateRawCell();
1821 // Initializes a JSObject based on its map.
1822 void InitializeJSObjectFromMap(JSObject* obj,
1823 FixedArray* properties,
1826 bool CreateInitialMaps();
1827 bool CreateInitialObjects();
1829 // These five Create*EntryStub functions are here and forced to not be inlined
1830 // because of a gcc-4.4 bug that assigns wrong vtable entries.
1831 NO_INLINE(void CreateJSEntryStub());
1832 NO_INLINE(void CreateJSConstructEntryStub());
1834 void CreateFixedStubs();
1836 MaybeObject* CreateOddball(const char* to_string,
1840 // Allocate a JSArray with no elements
1841 MUST_USE_RESULT MaybeObject* AllocateJSArray(
1842 ElementsKind elements_kind,
1843 PretenureFlag pretenure = NOT_TENURED);
1845 // Allocate empty fixed array.
1846 MUST_USE_RESULT MaybeObject* AllocateEmptyFixedArray();
1848 // Allocate empty fixed double array.
1849 MUST_USE_RESULT MaybeObject* AllocateEmptyFixedDoubleArray();
1851 // Performs a minor collection in new generation.
1854 static HeapObject* UpdateNewSpaceReferenceInExternalStringTableEntry(
1858 Address DoScavenge(ObjectVisitor* scavenge_visitor, Address new_space_front);
1859 static void ScavengeStoreBufferCallback(Heap* heap,
1861 StoreBufferEvent event);
1863 // Performs a major collection in the whole heap.
1864 void MarkCompact(GCTracer* tracer);
1866 // Code to be run before and after mark-compact.
1867 void MarkCompactPrologue();
1869 // Record statistics before and after garbage collection.
1870 void ReportStatisticsBeforeGC();
1871 void ReportStatisticsAfterGC();
1873 // Slow part of scavenge object.
1874 static void ScavengeObjectSlow(HeapObject** p, HeapObject* object);
1876 // Initializes a function with a shared part and prototype.
1877 // Note: this code was factored out of AllocateFunction such that
1878 // other parts of the VM could use it. Specifically, a function that creates
1879 // instances of type JS_FUNCTION_TYPE benefit from the use of this function.
1880 // Please note this does not perform a garbage collection.
1881 inline void InitializeFunction(
1882 JSFunction* function,
1883 SharedFunctionInfo* shared,
1886 // Total RegExp code ever generated
1887 double total_regexp_code_generated_;
1892 // Allocates a small number to string cache.
1893 MUST_USE_RESULT MaybeObject* AllocateInitialNumberStringCache();
1894 // Creates and installs the full-sized number string cache.
1895 void AllocateFullSizeNumberStringCache();
1896 // Get the length of the number to string cache based on the max semispace
1898 int FullSizeNumberStringCacheLength();
1899 // Flush the number to string cache.
1900 void FlushNumberStringCache();
1902 void UpdateSurvivalRateTrend(int start_new_space_size);
1904 enum SurvivalRateTrend { INCREASING, STABLE, DECREASING, FLUCTUATING };
1906 static const int kYoungSurvivalRateHighThreshold = 90;
1907 static const int kYoungSurvivalRateLowThreshold = 10;
1908 static const int kYoungSurvivalRateAllowedDeviation = 15;
1910 int young_survivors_after_last_gc_;
1911 int high_survival_rate_period_length_;
1912 int low_survival_rate_period_length_;
1913 double survival_rate_;
1914 SurvivalRateTrend previous_survival_rate_trend_;
1915 SurvivalRateTrend survival_rate_trend_;
1917 void set_survival_rate_trend(SurvivalRateTrend survival_rate_trend) {
1918 ASSERT(survival_rate_trend != FLUCTUATING);
1919 previous_survival_rate_trend_ = survival_rate_trend_;
1920 survival_rate_trend_ = survival_rate_trend;
1923 SurvivalRateTrend survival_rate_trend() {
1924 if (survival_rate_trend_ == STABLE) {
1926 } else if (previous_survival_rate_trend_ == STABLE) {
1927 return survival_rate_trend_;
1928 } else if (survival_rate_trend_ != previous_survival_rate_trend_) {
1931 return survival_rate_trend_;
1935 bool IsStableOrIncreasingSurvivalTrend() {
1936 switch (survival_rate_trend()) {
1945 bool IsStableOrDecreasingSurvivalTrend() {
1946 switch (survival_rate_trend()) {
1955 bool IsIncreasingSurvivalTrend() {
1956 return survival_rate_trend() == INCREASING;
1959 bool IsHighSurvivalRate() {
1960 return high_survival_rate_period_length_ > 0;
1963 bool IsLowSurvivalRate() {
1964 return low_survival_rate_period_length_ > 0;
1967 void SelectScavengingVisitorsTable();
1969 void StartIdleRound() {
1970 mark_sweeps_since_idle_round_started_ = 0;
1971 ms_count_at_last_idle_notification_ = ms_count_;
1974 void FinishIdleRound() {
1975 mark_sweeps_since_idle_round_started_ = kMaxMarkSweepsInIdleRound;
1976 scavenges_since_last_idle_round_ = 0;
1979 bool EnoughGarbageSinceLastIdleRound() {
1980 return (scavenges_since_last_idle_round_ >= kIdleScavengeThreshold);
1983 // Estimates how many milliseconds a Mark-Sweep would take to complete.
1984 // In idle notification handler we assume that this function will return:
1985 // - a number less than 10 for small heaps, which are less than 8Mb.
1986 // - a number greater than 10 for large heaps, which are greater than 32Mb.
1987 int TimeMarkSweepWouldTakeInMs() {
1988 // Rough estimate of how many megabytes of heap can be processed in 1 ms.
1989 static const int kMbPerMs = 2;
1991 int heap_size_mb = static_cast<int>(SizeOfObjects() / MB);
1992 return heap_size_mb / kMbPerMs;
1995 // Returns true if no more GC work is left.
1996 bool IdleGlobalGC();
1998 void AdvanceIdleIncrementalMarking(intptr_t step_size);
2001 static const int kInitialSymbolTableSize = 2048;
2002 static const int kInitialEvalCacheSize = 64;
2003 static const int kInitialNumberStringCacheSize = 256;
2005 // Maximum GC pause.
2008 // Maximum size of objects alive after GC.
2009 intptr_t max_alive_after_gc_;
2011 // Minimal interval between two subsequent collections.
2012 int min_in_mutator_;
2014 // Size of objects alive after last GC.
2015 intptr_t alive_after_last_gc_;
2017 double last_gc_end_timestamp_;
2019 MarkCompactCollector mark_compact_collector_;
2021 StoreBuffer store_buffer_;
2025 IncrementalMarking incremental_marking_;
2027 int number_idle_notifications_;
2028 unsigned int last_idle_notification_gc_count_;
2029 bool last_idle_notification_gc_count_init_;
2031 int mark_sweeps_since_idle_round_started_;
2032 int ms_count_at_last_idle_notification_;
2033 unsigned int gc_count_at_last_idle_gc_;
2034 int scavenges_since_last_idle_round_;
2036 static const int kMaxMarkSweepsInIdleRound = 7;
2037 static const int kIdleScavengeThreshold = 5;
2039 // Shared state read by the scavenge collector and set by ScavengeObject.
2040 PromotionQueue promotion_queue_;
2042 // Flag is set when the heap has been configured. The heap can be repeatedly
2043 // configured through the API until it is set up.
2046 ExternalStringTable external_string_table_;
2048 VisitorDispatchTable<ScavengingCallback> scavenging_visitors_table_;
2050 MemoryChunk* chunks_queued_for_free_;
2052 friend class Factory;
2053 friend class GCTracer;
2054 friend class DisallowAllocationFailure;
2055 friend class AlwaysAllocateScope;
2056 friend class LinearAllocationScope;
2058 friend class Isolate;
2059 friend class MarkCompactCollector;
2060 friend class StaticMarkingVisitor;
2061 friend class MapCompact;
2063 DISALLOW_COPY_AND_ASSIGN(Heap);
2069 static const int kStartMarker = 0xDECADE00;
2070 static const int kEndMarker = 0xDECADE01;
2072 int* start_marker; // 0
2073 int* new_space_size; // 1
2074 int* new_space_capacity; // 2
2075 intptr_t* old_pointer_space_size; // 3
2076 intptr_t* old_pointer_space_capacity; // 4
2077 intptr_t* old_data_space_size; // 5
2078 intptr_t* old_data_space_capacity; // 6
2079 intptr_t* code_space_size; // 7
2080 intptr_t* code_space_capacity; // 8
2081 intptr_t* map_space_size; // 9
2082 intptr_t* map_space_capacity; // 10
2083 intptr_t* cell_space_size; // 11
2084 intptr_t* cell_space_capacity; // 12
2085 intptr_t* lo_space_size; // 13
2086 int* global_handle_count; // 14
2087 int* weak_global_handle_count; // 15
2088 int* pending_global_handle_count; // 16
2089 int* near_death_global_handle_count; // 17
2090 int* free_global_handle_count; // 18
2091 intptr_t* memory_allocator_size; // 19
2092 intptr_t* memory_allocator_capacity; // 20
2093 int* objects_per_type; // 21
2094 int* size_per_type; // 22
2095 int* os_error; // 23
2096 int* end_marker; // 24
2100 class AlwaysAllocateScope {
2102 inline AlwaysAllocateScope();
2103 inline ~AlwaysAllocateScope();
2107 class LinearAllocationScope {
2109 inline LinearAllocationScope();
2110 inline ~LinearAllocationScope();
2115 // Visitor class to verify interior pointers in spaces that do not contain
2116 // or care about intergenerational references. All heap object pointers have to
2117 // point into the heap to a location that has a map pointer at its first word.
2118 // Caveat: Heap::Contains is an approximation because it can return true for
2119 // objects in a heap space but above the allocation pointer.
2120 class VerifyPointersVisitor: public ObjectVisitor {
2122 inline void VisitPointers(Object** start, Object** end);
2127 // Space iterator for iterating over all spaces of the heap.
2128 // Returns each space in turn, and null when it is done.
2129 class AllSpaces BASE_EMBEDDED {
2132 AllSpaces() { counter_ = FIRST_SPACE; }
2138 // Space iterator for iterating over all old spaces of the heap: Old pointer
2139 // space, old data space and code space.
2140 // Returns each space in turn, and null when it is done.
2141 class OldSpaces BASE_EMBEDDED {
2144 OldSpaces() { counter_ = OLD_POINTER_SPACE; }
2150 // Space iterator for iterating over all the paged spaces of the heap:
2151 // Map space, old pointer space, old data space, code space and cell space.
2152 // Returns each space in turn, and null when it is done.
2153 class PagedSpaces BASE_EMBEDDED {
2156 PagedSpaces() { counter_ = OLD_POINTER_SPACE; }
2162 // Space iterator for iterating over all spaces of the heap.
2163 // For each space an object iterator is provided. The deallocation of the
2164 // returned object iterators is handled by the space iterator.
2165 class SpaceIterator : public Malloced {
2168 explicit SpaceIterator(HeapObjectCallback size_func);
2169 virtual ~SpaceIterator();
2172 ObjectIterator* next();
2175 ObjectIterator* CreateIterator();
2177 int current_space_; // from enum AllocationSpace.
2178 ObjectIterator* iterator_; // object iterator for the current space.
2179 HeapObjectCallback size_func_;
2183 // A HeapIterator provides iteration over the whole heap. It
2184 // aggregates the specific iterators for the different spaces as
2185 // these can only iterate over one space only.
2187 // HeapIterator can skip free list nodes (that is, de-allocated heap
2188 // objects that still remain in the heap). As implementation of free
2189 // nodes filtering uses GC marks, it can't be used during MS/MC GC
2190 // phases. Also, it is forbidden to interrupt iteration in this mode,
2191 // as this will leave heap objects marked (and thus, unusable).
2192 class HeapObjectsFilter;
2194 class HeapIterator BASE_EMBEDDED {
2196 enum HeapObjectsFiltering {
2202 explicit HeapIterator(HeapObjectsFiltering filtering);
2209 // Perform the initialization.
2211 // Perform all necessary shutdown (destruction) work.
2213 HeapObject* NextObject();
2215 HeapObjectsFiltering filtering_;
2216 HeapObjectsFilter* filter_;
2217 // Space iterator for iterating all the spaces.
2218 SpaceIterator* space_iterator_;
2219 // Object iterator for the space currently being iterated.
2220 ObjectIterator* object_iterator_;
2224 // Cache for mapping (map, property name) into field offset.
2225 // Cleared at startup and prior to mark sweep collection.
2226 class KeyedLookupCache {
2228 // Lookup field offset for (map, name). If absent, -1 is returned.
2229 int Lookup(Map* map, String* name);
2231 // Update an element in the cache.
2232 void Update(Map* map, String* name, int field_offset);
2237 static const int kLength = 256;
2238 static const int kCapacityMask = kLength - 1;
2239 static const int kMapHashShift = 5;
2240 static const int kHashMask = -4; // Zero the last two bits.
2241 static const int kEntriesPerBucket = 4;
2242 static const int kNotFound = -1;
2244 // kEntriesPerBucket should be a power of 2.
2245 STATIC_ASSERT((kEntriesPerBucket & (kEntriesPerBucket - 1)) == 0);
2246 STATIC_ASSERT(kEntriesPerBucket == -kHashMask);
2249 KeyedLookupCache() {
2250 for (int i = 0; i < kLength; ++i) {
2251 keys_[i].map = NULL;
2252 keys_[i].name = NULL;
2253 field_offsets_[i] = kNotFound;
2257 static inline int Hash(Map* map, String* name);
2259 // Get the address of the keys and field_offsets arrays. Used in
2260 // generated code to perform cache lookups.
2261 Address keys_address() {
2262 return reinterpret_cast<Address>(&keys_);
2265 Address field_offsets_address() {
2266 return reinterpret_cast<Address>(&field_offsets_);
2275 int field_offsets_[kLength];
2277 friend class ExternalReference;
2278 friend class Isolate;
2279 DISALLOW_COPY_AND_ASSIGN(KeyedLookupCache);
2283 // Cache for mapping (array, property name) into descriptor index.
2284 // The cache contains both positive and negative results.
2285 // Descriptor index equals kNotFound means the property is absent.
2286 // Cleared at startup and prior to any gc.
2287 class DescriptorLookupCache {
2289 // Lookup descriptor index for (map, name).
2290 // If absent, kAbsent is returned.
2291 int Lookup(DescriptorArray* array, String* name) {
2292 if (!StringShape(name).IsSymbol()) return kAbsent;
2293 int index = Hash(array, name);
2294 Key& key = keys_[index];
2295 if ((key.array == array) && (key.name == name)) return results_[index];
2299 // Update an element in the cache.
2300 void Update(DescriptorArray* array, String* name, int result) {
2301 ASSERT(result != kAbsent);
2302 if (StringShape(name).IsSymbol()) {
2303 int index = Hash(array, name);
2304 Key& key = keys_[index];
2307 results_[index] = result;
2314 static const int kAbsent = -2;
2317 DescriptorLookupCache() {
2318 for (int i = 0; i < kLength; ++i) {
2319 keys_[i].array = NULL;
2320 keys_[i].name = NULL;
2321 results_[i] = kAbsent;
2325 static int Hash(DescriptorArray* array, String* name) {
2326 // Uses only lower 32 bits if pointers are larger.
2327 uint32_t array_hash =
2328 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(array)) >> 2;
2329 uint32_t name_hash =
2330 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name)) >> 2;
2331 return (array_hash ^ name_hash) % kLength;
2334 static const int kLength = 64;
2336 DescriptorArray* array;
2341 int results_[kLength];
2343 friend class Isolate;
2344 DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
2349 class DisallowAllocationFailure {
2351 inline DisallowAllocationFailure();
2352 inline ~DisallowAllocationFailure();
2360 // A helper class to document/test C++ scopes where we do not
2361 // expect a GC. Usage:
2363 // /* Allocation not allowed: we cannot handle a GC in this scope. */
2364 // { AssertNoAllocation nogc;
2367 class AssertNoAllocation {
2369 inline AssertNoAllocation();
2370 inline ~AssertNoAllocation();
2379 class DisableAssertNoAllocation {
2381 inline DisableAssertNoAllocation();
2382 inline ~DisableAssertNoAllocation();
2390 // GCTracer collects and prints ONE line after each garbage collector
2391 // invocation IFF --trace_gc is used.
2393 class GCTracer BASE_EMBEDDED {
2395 class Scope BASE_EMBEDDED {
2403 MC_UPDATE_NEW_TO_NEW_POINTERS,
2404 MC_UPDATE_ROOT_TO_NEW_POINTERS,
2405 MC_UPDATE_OLD_TO_NEW_POINTERS,
2406 MC_UPDATE_POINTERS_TO_EVACUATED,
2407 MC_UPDATE_POINTERS_BETWEEN_EVACUATED,
2408 MC_UPDATE_MISC_POINTERS,
2413 Scope(GCTracer* tracer, ScopeId scope)
2416 start_time_ = OS::TimeCurrentMillis();
2420 ASSERT(scope_ < kNumberOfScopes); // scope_ is unsigned.
2421 tracer_->scopes_[scope_] += OS::TimeCurrentMillis() - start_time_;
2430 explicit GCTracer(Heap* heap,
2431 const char* gc_reason,
2432 const char* collector_reason);
2435 // Sets the collector.
2436 void set_collector(GarbageCollector collector) { collector_ = collector; }
2438 // Sets the GC count.
2439 void set_gc_count(unsigned int count) { gc_count_ = count; }
2441 // Sets the full GC count.
2442 void set_full_gc_count(int count) { full_gc_count_ = count; }
2444 void increment_promoted_objects_size(int object_size) {
2445 promoted_objects_size_ += object_size;
2449 // Returns a string matching the collector.
2450 const char* CollectorString();
2452 // Returns size of object in heap (in MB).
2453 inline double SizeOfHeapObjects();
2455 // Timestamp set in the constructor.
2458 // Size of objects in heap set in constructor.
2459 intptr_t start_object_size_;
2461 // Size of memory allocated from OS set in constructor.
2462 intptr_t start_memory_size_;
2464 // Type of collector.
2465 GarbageCollector collector_;
2467 // A count (including this one, e.g. the first collection is 1) of the
2468 // number of garbage collections.
2469 unsigned int gc_count_;
2471 // A count (including this one) of the number of full garbage collections.
2474 // Amounts of time spent in different scopes during GC.
2475 double scopes_[Scope::kNumberOfScopes];
2477 // Total amount of space either wasted or contained in one of free lists
2478 // before the current GC.
2479 intptr_t in_free_list_or_wasted_before_gc_;
2481 // Difference between space used in the heap at the beginning of the current
2482 // collection and the end of the previous collection.
2483 intptr_t allocated_since_last_gc_;
2485 // Amount of time spent in mutator that is time elapsed between end of the
2486 // previous collection and the beginning of the current one.
2487 double spent_in_mutator_;
2489 // Size of objects promoted during the current collection.
2490 intptr_t promoted_objects_size_;
2492 // Incremental marking steps counters.
2495 double longest_step_;
2496 int steps_count_since_last_gc_;
2497 double steps_took_since_last_gc_;
2501 const char* gc_reason_;
2502 const char* collector_reason_;
2506 class StringSplitCache {
2508 static Object* Lookup(FixedArray* cache, String* string, String* pattern);
2509 static void Enter(Heap* heap,
2514 static void Clear(FixedArray* cache);
2515 static const int kStringSplitCacheSize = 0x100;
2518 static const int kArrayEntriesPerCacheEntry = 4;
2519 static const int kStringOffset = 0;
2520 static const int kPatternOffset = 1;
2521 static const int kArrayOffset = 2;
2523 static MaybeObject* WrapFixedArrayInJSArray(Object* fixed_array);
2527 class TranscendentalCache {
2529 enum Type {ACOS, ASIN, ATAN, COS, EXP, LOG, SIN, TAN, kNumberOfCaches};
2530 static const int kTranscendentalTypeBits = 3;
2531 STATIC_ASSERT((1 << kTranscendentalTypeBits) >= kNumberOfCaches);
2533 // Returns a heap number with f(input), where f is a math function specified
2534 // by the 'type' argument.
2535 MUST_USE_RESULT inline MaybeObject* Get(Type type, double input);
2537 // The cache contains raw Object pointers. This method disposes of
2538 // them before a garbage collection.
2543 static const int kCacheSize = 512;
2545 explicit SubCache(Type t);
2547 MUST_USE_RESULT inline MaybeObject* Get(double input);
2549 inline double Calculate(double input);
2558 uint32_t integers[2];
2561 inline static int Hash(const Converter& c) {
2562 uint32_t hash = (c.integers[0] ^ c.integers[1]);
2563 hash ^= static_cast<int32_t>(hash) >> 16;
2564 hash ^= static_cast<int32_t>(hash) >> 8;
2565 return (hash & (kCacheSize - 1));
2568 Element elements_[kCacheSize];
2572 // Allow access to the caches_ array as an ExternalReference.
2573 friend class ExternalReference;
2574 // Inline implementation of the cache.
2575 friend class TranscendentalCacheStub;
2576 // For evaluating value.
2577 friend class TranscendentalCache;
2579 DISALLOW_COPY_AND_ASSIGN(SubCache);
2582 TranscendentalCache() {
2583 for (int i = 0; i < kNumberOfCaches; ++i) caches_[i] = NULL;
2586 // Used to create an external reference.
2587 inline Address cache_array_address();
2590 friend class Isolate;
2591 // Inline implementation of the caching.
2592 friend class TranscendentalCacheStub;
2593 // Allow access to the caches_ array as an ExternalReference.
2594 friend class ExternalReference;
2596 SubCache* caches_[kNumberOfCaches];
2597 DISALLOW_COPY_AND_ASSIGN(TranscendentalCache);
2601 // Abstract base class for checking whether a weak object should be retained.
2602 class WeakObjectRetainer {
2604 virtual ~WeakObjectRetainer() {}
2606 // Return whether this object should be retained. If NULL is returned the
2607 // object has no references. Otherwise the address of the retained object
2608 // should be returned as in some GC situations the object has been moved.
2609 virtual Object* RetainAs(Object* object) = 0;
2613 // Intrusive object marking uses least significant bit of
2614 // heap object's map word to mark objects.
2615 // Normally all map words have least significant bit set
2616 // because they contain tagged map pointer.
2617 // If the bit is not set object is marked.
2618 // All objects should be unmarked before resuming
2619 // JavaScript execution.
2620 class IntrusiveMarking {
2622 static bool IsMarked(HeapObject* object) {
2623 return (object->map_word().ToRawValue() & kNotMarkedBit) == 0;
2626 static void ClearMark(HeapObject* object) {
2627 uintptr_t map_word = object->map_word().ToRawValue();
2628 object->set_map_word(MapWord::FromRawValue(map_word | kNotMarkedBit));
2629 ASSERT(!IsMarked(object));
2632 static void SetMark(HeapObject* object) {
2633 uintptr_t map_word = object->map_word().ToRawValue();
2634 object->set_map_word(MapWord::FromRawValue(map_word & ~kNotMarkedBit));
2635 ASSERT(IsMarked(object));
2638 static Map* MapOfMarkedObject(HeapObject* object) {
2639 uintptr_t map_word = object->map_word().ToRawValue();
2640 return MapWord::FromRawValue(map_word | kNotMarkedBit).ToMap();
2643 static int SizeOfMarkedObject(HeapObject* object) {
2644 return object->SizeFromMap(MapOfMarkedObject(object));
2648 static const uintptr_t kNotMarkedBit = 0x1;
2649 STATIC_ASSERT((kHeapObjectTag & kNotMarkedBit) != 0);
2653 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
2654 // Helper class for tracing paths to a search target Object from all roots.
2655 // The TracePathFrom() method can be used to trace paths from a specific
2656 // object to the search target object.
2657 class PathTracer : public ObjectVisitor {
2660 FIND_ALL, // Will find all matches.
2661 FIND_FIRST // Will stop the search after first match.
2664 // For the WhatToFind arg, if FIND_FIRST is specified, tracing will stop
2665 // after the first match. If FIND_ALL is specified, then tracing will be
2666 // done for all matches.
2667 PathTracer(Object* search_target,
2668 WhatToFind what_to_find,
2669 VisitMode visit_mode)
2670 : search_target_(search_target),
2671 found_target_(false),
2672 found_target_in_trace_(false),
2673 what_to_find_(what_to_find),
2674 visit_mode_(visit_mode),
2678 virtual void VisitPointers(Object** start, Object** end);
2681 void TracePathFrom(Object** root);
2683 bool found() const { return found_target_; }
2685 static Object* const kAnyGlobalObject;
2689 class UnmarkVisitor;
2691 void MarkRecursively(Object** p, MarkVisitor* mark_visitor);
2692 void UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor);
2693 virtual void ProcessResults();
2695 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2696 static const int kMarkTag = 2;
2698 Object* search_target_;
2700 bool found_target_in_trace_;
2701 WhatToFind what_to_find_;
2702 VisitMode visit_mode_;
2703 List<Object*> object_stack_;
2705 AssertNoAllocation no_alloc; // i.e. no gc allowed.
2708 DISALLOW_IMPLICIT_CONSTRUCTORS(PathTracer);
2710 #endif // DEBUG || LIVE_OBJECT_LIST
2712 } } // namespace v8::internal
2714 #endif // V8_HEAP_H_