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.
30 #include "accessors.h"
32 #include "bootstrapper.h"
34 #include "compilation-cache.h"
36 #include "deoptimizer.h"
37 #include "global-handles.h"
38 #include "heap-profiler.h"
39 #include "incremental-marking.h"
40 #include "liveobjectlist-inl.h"
41 #include "mark-compact.h"
43 #include "objects-visiting.h"
44 #include "objects-visiting-inl.h"
45 #include "runtime-profiler.h"
46 #include "scopeinfo.h"
48 #include "store-buffer.h"
49 #include "v8threads.h"
50 #include "vm-state-inl.h"
51 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
52 #include "regexp-macro-assembler.h"
53 #include "arm/regexp-macro-assembler-arm.h"
55 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
56 #include "regexp-macro-assembler.h"
57 #include "mips/regexp-macro-assembler-mips.h"
63 static LazyMutex gc_initializer_mutex = LAZY_MUTEX_INITIALIZER;
68 // semispace_size_ should be a power of 2 and old_generation_size_ should be
69 // a multiple of Page::kPageSize.
71 #define LUMP_OF_MEMORY (128 * KB)
73 #elif defined(V8_TARGET_ARCH_X64)
74 #define LUMP_OF_MEMORY (2 * MB)
75 code_range_size_(512*MB),
77 #define LUMP_OF_MEMORY MB
80 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
81 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
82 initial_semispace_size_(Page::kPageSize),
83 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
84 max_executable_size_(256l * LUMP_OF_MEMORY),
86 // Variables set based on semispace_size_ and old_generation_size_ in
87 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
88 // Will be 4 * reserved_semispace_size_ to ensure that young
89 // generation can be aligned to its size.
90 survived_since_last_expansion_(0),
92 always_allocate_scope_depth_(0),
93 linear_allocation_scope_depth_(0),
94 contexts_disposed_(0),
96 scan_on_scavenge_pages_(0),
98 old_pointer_space_(NULL),
99 old_data_space_(NULL),
104 gc_state_(NOT_IN_GC),
105 gc_post_processing_depth_(0),
108 remembered_unmapped_pages_index_(0),
109 unflattened_strings_length_(0),
111 allocation_allowed_(true),
112 allocation_timeout_(0),
113 disallow_allocation_failure_(false),
116 new_space_high_promotion_mode_active_(false),
117 old_gen_promotion_limit_(kMinimumPromotionLimit),
118 old_gen_allocation_limit_(kMinimumAllocationLimit),
119 old_gen_limit_factor_(1),
120 size_of_old_gen_at_last_old_space_gc_(0),
121 external_allocation_limit_(0),
122 amount_of_external_allocated_memory_(0),
123 amount_of_external_allocated_memory_at_last_global_gc_(0),
124 old_gen_exhausted_(false),
125 store_buffer_rebuilder_(store_buffer()),
126 hidden_symbol_(NULL),
127 global_gc_prologue_callback_(NULL),
128 global_gc_epilogue_callback_(NULL),
129 gc_safe_size_of_old_object_(NULL),
130 total_regexp_code_generated_(0),
132 young_survivors_after_last_gc_(0),
133 high_survival_rate_period_length_(0),
135 previous_survival_rate_trend_(Heap::STABLE),
136 survival_rate_trend_(Heap::STABLE),
138 max_alive_after_gc_(0),
139 min_in_mutator_(kMaxInt),
140 alive_after_last_gc_(0),
141 last_gc_end_timestamp_(0.0),
144 incremental_marking_(this),
145 number_idle_notifications_(0),
146 last_idle_notification_gc_count_(0),
147 last_idle_notification_gc_count_init_(false),
148 idle_notification_will_schedule_next_gc_(false),
149 mark_sweeps_since_idle_round_started_(0),
150 ms_count_at_last_idle_notification_(0),
151 gc_count_at_last_idle_gc_(0),
152 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
153 promotion_queue_(this),
155 chunks_queued_for_free_(NULL) {
156 // Allow build-time customization of the max semispace size. Building
157 // V8 with snapshots and a non-default max semispace size is much
158 // easier if you can define it as part of the build environment.
159 #if defined(V8_MAX_SEMISPACE_SIZE)
160 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
163 intptr_t max_virtual = OS::MaxVirtualMemory();
165 if (max_virtual > 0) {
166 if (code_range_size_ > 0) {
167 // Reserve no more than 1/8 of the memory for the code range.
168 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
172 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
173 global_contexts_list_ = NULL;
174 mark_compact_collector_.heap_ = this;
175 external_string_table_.heap_ = this;
179 intptr_t Heap::Capacity() {
180 if (!HasBeenSetUp()) return 0;
182 return new_space_.Capacity() +
183 old_pointer_space_->Capacity() +
184 old_data_space_->Capacity() +
185 code_space_->Capacity() +
186 map_space_->Capacity() +
187 cell_space_->Capacity();
191 intptr_t Heap::CommittedMemory() {
192 if (!HasBeenSetUp()) return 0;
194 return new_space_.CommittedMemory() +
195 old_pointer_space_->CommittedMemory() +
196 old_data_space_->CommittedMemory() +
197 code_space_->CommittedMemory() +
198 map_space_->CommittedMemory() +
199 cell_space_->CommittedMemory() +
203 intptr_t Heap::CommittedMemoryExecutable() {
204 if (!HasBeenSetUp()) return 0;
206 return isolate()->memory_allocator()->SizeExecutable();
210 intptr_t Heap::Available() {
211 if (!HasBeenSetUp()) return 0;
213 return new_space_.Available() +
214 old_pointer_space_->Available() +
215 old_data_space_->Available() +
216 code_space_->Available() +
217 map_space_->Available() +
218 cell_space_->Available();
222 bool Heap::HasBeenSetUp() {
223 return old_pointer_space_ != NULL &&
224 old_data_space_ != NULL &&
225 code_space_ != NULL &&
226 map_space_ != NULL &&
227 cell_space_ != NULL &&
232 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
233 if (IntrusiveMarking::IsMarked(object)) {
234 return IntrusiveMarking::SizeOfMarkedObject(object);
236 return object->SizeFromMap(object->map());
240 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
241 const char** reason) {
242 // Is global GC requested?
243 if (space != NEW_SPACE || FLAG_gc_global) {
244 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
245 *reason = "GC in old space requested";
246 return MARK_COMPACTOR;
249 // Is enough data promoted to justify a global GC?
250 if (OldGenerationPromotionLimitReached()) {
251 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
252 *reason = "promotion limit reached";
253 return MARK_COMPACTOR;
256 // Have allocation in OLD and LO failed?
257 if (old_gen_exhausted_) {
258 isolate_->counters()->
259 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
260 *reason = "old generations exhausted";
261 return MARK_COMPACTOR;
264 // Is there enough space left in OLD to guarantee that a scavenge can
267 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
268 // for object promotion. It counts only the bytes that the memory
269 // allocator has not yet allocated from the OS and assigned to any space,
270 // and does not count available bytes already in the old space or code
271 // space. Undercounting is safe---we may get an unrequested full GC when
272 // a scavenge would have succeeded.
273 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
274 isolate_->counters()->
275 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
276 *reason = "scavenge might not succeed";
277 return MARK_COMPACTOR;
286 // TODO(1238405): Combine the infrastructure for --heap-stats and
287 // --log-gc to avoid the complicated preprocessor and flag testing.
288 void Heap::ReportStatisticsBeforeGC() {
289 // Heap::ReportHeapStatistics will also log NewSpace statistics when
290 // compiled --log-gc is set. The following logic is used to avoid
293 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
294 if (FLAG_heap_stats) {
295 ReportHeapStatistics("Before GC");
296 } else if (FLAG_log_gc) {
297 new_space_.ReportStatistics();
299 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
302 new_space_.CollectStatistics();
303 new_space_.ReportStatistics();
304 new_space_.ClearHistograms();
310 void Heap::PrintShortHeapStatistics() {
311 if (!FLAG_trace_gc_verbose) return;
312 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
313 ", available: %8" V8_PTR_PREFIX "d\n",
314 isolate_->memory_allocator()->Size(),
315 isolate_->memory_allocator()->Available());
316 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
317 ", available: %8" V8_PTR_PREFIX "d\n",
318 Heap::new_space_.Size(),
319 new_space_.Available());
320 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
321 ", available: %8" V8_PTR_PREFIX "d"
322 ", waste: %8" V8_PTR_PREFIX "d\n",
323 old_pointer_space_->Size(),
324 old_pointer_space_->Available(),
325 old_pointer_space_->Waste());
326 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
327 ", available: %8" V8_PTR_PREFIX "d"
328 ", waste: %8" V8_PTR_PREFIX "d\n",
329 old_data_space_->Size(),
330 old_data_space_->Available(),
331 old_data_space_->Waste());
332 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
333 ", available: %8" V8_PTR_PREFIX "d"
334 ", waste: %8" V8_PTR_PREFIX "d\n",
336 code_space_->Available(),
337 code_space_->Waste());
338 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
339 ", available: %8" V8_PTR_PREFIX "d"
340 ", waste: %8" V8_PTR_PREFIX "d\n",
342 map_space_->Available(),
343 map_space_->Waste());
344 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
345 ", available: %8" V8_PTR_PREFIX "d"
346 ", waste: %8" V8_PTR_PREFIX "d\n",
348 cell_space_->Available(),
349 cell_space_->Waste());
350 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
351 ", available: %8" V8_PTR_PREFIX "d\n",
353 lo_space_->Available());
357 // TODO(1238405): Combine the infrastructure for --heap-stats and
358 // --log-gc to avoid the complicated preprocessor and flag testing.
359 void Heap::ReportStatisticsAfterGC() {
360 // Similar to the before GC, we use some complicated logic to ensure that
361 // NewSpace statistics are logged exactly once when --log-gc is turned on.
363 if (FLAG_heap_stats) {
364 new_space_.CollectStatistics();
365 ReportHeapStatistics("After GC");
366 } else if (FLAG_log_gc) {
367 new_space_.ReportStatistics();
370 if (FLAG_log_gc) new_space_.ReportStatistics();
375 void Heap::GarbageCollectionPrologue() {
376 isolate_->transcendental_cache()->Clear();
377 ClearJSFunctionResultCaches();
379 unflattened_strings_length_ = 0;
381 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
382 allow_allocation(false);
384 if (FLAG_verify_heap) {
388 if (FLAG_gc_verbose) Print();
392 ReportStatisticsBeforeGC();
395 LiveObjectList::GCPrologue();
396 store_buffer()->GCPrologue();
399 intptr_t Heap::SizeOfObjects() {
402 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
403 total += space->SizeOfObjects();
408 void Heap::GarbageCollectionEpilogue() {
409 store_buffer()->GCEpilogue();
410 LiveObjectList::GCEpilogue();
412 allow_allocation(true);
415 if (FLAG_verify_heap) {
419 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
420 if (FLAG_print_handles) PrintHandles();
421 if (FLAG_gc_verbose) Print();
422 if (FLAG_code_stats) ReportCodeStatistics("After GC");
425 isolate_->counters()->alive_after_last_gc()->Set(
426 static_cast<int>(SizeOfObjects()));
428 isolate_->counters()->symbol_table_capacity()->Set(
429 symbol_table()->Capacity());
430 isolate_->counters()->number_of_symbols()->Set(
431 symbol_table()->NumberOfElements());
433 ReportStatisticsAfterGC();
435 #ifdef ENABLE_DEBUGGER_SUPPORT
436 isolate_->debug()->AfterGarbageCollection();
437 #endif // ENABLE_DEBUGGER_SUPPORT
441 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
442 // Since we are ignoring the return value, the exact choice of space does
443 // not matter, so long as we do not specify NEW_SPACE, which would not
445 mark_compact_collector_.SetFlags(flags);
446 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
447 mark_compact_collector_.SetFlags(kNoGCFlags);
451 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
452 // Since we are ignoring the return value, the exact choice of space does
453 // not matter, so long as we do not specify NEW_SPACE, which would not
455 // Major GC would invoke weak handle callbacks on weakly reachable
456 // handles, but won't collect weakly reachable objects until next
457 // major GC. Therefore if we collect aggressively and weak handle callback
458 // has been invoked, we rerun major GC to release objects which become
460 // Note: as weak callbacks can execute arbitrary code, we cannot
461 // hope that eventually there will be no weak callbacks invocations.
462 // Therefore stop recollecting after several attempts.
463 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
464 kReduceMemoryFootprintMask);
465 isolate_->compilation_cache()->Clear();
466 const int kMaxNumberOfAttempts = 7;
467 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
468 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
472 mark_compact_collector()->SetFlags(kNoGCFlags);
476 incremental_marking()->UncommitMarkingDeque();
480 bool Heap::CollectGarbage(AllocationSpace space,
481 GarbageCollector collector,
482 const char* gc_reason,
483 const char* collector_reason) {
484 // The VM is in the GC state until exiting this function.
485 VMState state(isolate_, GC);
488 // Reset the allocation timeout to the GC interval, but make sure to
489 // allow at least a few allocations after a collection. The reason
490 // for this is that we have a lot of allocation sequences and we
491 // assume that a garbage collection will allow the subsequent
492 // allocation attempts to go through.
493 allocation_timeout_ = Max(6, FLAG_gc_interval);
496 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
497 if (FLAG_trace_incremental_marking) {
498 PrintF("[IncrementalMarking] Scavenge during marking.\n");
502 if (collector == MARK_COMPACTOR &&
503 !mark_compact_collector()->abort_incremental_marking_ &&
504 !incremental_marking()->IsStopped() &&
505 !incremental_marking()->should_hurry() &&
506 FLAG_incremental_marking_steps) {
507 if (FLAG_trace_incremental_marking) {
508 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
510 collector = SCAVENGER;
511 collector_reason = "incremental marking delaying mark-sweep";
514 bool next_gc_likely_to_collect_more = false;
516 { GCTracer tracer(this, gc_reason, collector_reason);
517 GarbageCollectionPrologue();
518 // The GC count was incremented in the prologue. Tell the tracer about
520 tracer.set_gc_count(gc_count_);
522 // Tell the tracer which collector we've selected.
523 tracer.set_collector(collector);
525 HistogramTimer* rate = (collector == SCAVENGER)
526 ? isolate_->counters()->gc_scavenger()
527 : isolate_->counters()->gc_compactor();
529 next_gc_likely_to_collect_more =
530 PerformGarbageCollection(collector, &tracer);
533 GarbageCollectionEpilogue();
536 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
537 if (incremental_marking()->IsStopped()) {
538 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
539 incremental_marking()->Start();
543 return next_gc_likely_to_collect_more;
547 void Heap::PerformScavenge() {
548 GCTracer tracer(this, NULL, NULL);
549 if (incremental_marking()->IsStopped()) {
550 PerformGarbageCollection(SCAVENGER, &tracer);
552 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
558 // Helper class for verifying the symbol table.
559 class SymbolTableVerifier : public ObjectVisitor {
561 void VisitPointers(Object** start, Object** end) {
562 // Visit all HeapObject pointers in [start, end).
563 for (Object** p = start; p < end; p++) {
564 if ((*p)->IsHeapObject()) {
565 // Check that the symbol is actually a symbol.
566 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
574 static void VerifySymbolTable() {
576 SymbolTableVerifier verifier;
577 HEAP->symbol_table()->IterateElements(&verifier);
582 static bool AbortIncrementalMarkingAndCollectGarbage(
584 AllocationSpace space,
585 const char* gc_reason = NULL) {
586 heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
587 bool result = heap->CollectGarbage(space, gc_reason);
588 heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
593 void Heap::ReserveSpace(
595 int pointer_space_size,
600 int large_object_size) {
601 NewSpace* new_space = Heap::new_space();
602 PagedSpace* old_pointer_space = Heap::old_pointer_space();
603 PagedSpace* old_data_space = Heap::old_data_space();
604 PagedSpace* code_space = Heap::code_space();
605 PagedSpace* map_space = Heap::map_space();
606 PagedSpace* cell_space = Heap::cell_space();
607 LargeObjectSpace* lo_space = Heap::lo_space();
608 bool gc_performed = true;
610 static const int kThreshold = 20;
611 while (gc_performed && counter++ < kThreshold) {
612 gc_performed = false;
613 if (!new_space->ReserveSpace(new_space_size)) {
614 Heap::CollectGarbage(NEW_SPACE,
615 "failed to reserve space in the new space");
618 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
619 AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
620 "failed to reserve space in the old pointer space");
623 if (!(old_data_space->ReserveSpace(data_space_size))) {
624 AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
625 "failed to reserve space in the old data space");
628 if (!(code_space->ReserveSpace(code_space_size))) {
629 AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
630 "failed to reserve space in the code space");
633 if (!(map_space->ReserveSpace(map_space_size))) {
634 AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
635 "failed to reserve space in the map space");
638 if (!(cell_space->ReserveSpace(cell_space_size))) {
639 AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
640 "failed to reserve space in the cell space");
643 // We add a slack-factor of 2 in order to have space for a series of
644 // large-object allocations that are only just larger than the page size.
645 large_object_size *= 2;
646 // The ReserveSpace method on the large object space checks how much
647 // we can expand the old generation. This includes expansion caused by
648 // allocation in the other spaces.
649 large_object_size += cell_space_size + map_space_size + code_space_size +
650 data_space_size + pointer_space_size;
651 if (!(lo_space->ReserveSpace(large_object_size))) {
652 AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
653 "failed to reserve space in the large object space");
659 // Failed to reserve the space after several attempts.
660 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
665 void Heap::EnsureFromSpaceIsCommitted() {
666 if (new_space_.CommitFromSpaceIfNeeded()) return;
668 // Committing memory to from space failed.
669 // Try shrinking and try again.
671 if (new_space_.CommitFromSpaceIfNeeded()) return;
673 // Committing memory to from space failed again.
674 // Memory is exhausted and we will die.
675 V8::FatalProcessOutOfMemory("Committing semi space failed.");
679 void Heap::ClearJSFunctionResultCaches() {
680 if (isolate_->bootstrapper()->IsActive()) return;
682 Object* context = global_contexts_list_;
683 while (!context->IsUndefined()) {
684 // Get the caches for this context. GC can happen when the context
685 // is not fully initialized, so the caches can be undefined.
686 Object* caches_or_undefined =
687 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
688 if (!caches_or_undefined->IsUndefined()) {
689 FixedArray* caches = FixedArray::cast(caches_or_undefined);
691 int length = caches->length();
692 for (int i = 0; i < length; i++) {
693 JSFunctionResultCache::cast(caches->get(i))->Clear();
696 // Get the next context:
697 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
703 void Heap::ClearNormalizedMapCaches() {
704 if (isolate_->bootstrapper()->IsActive() &&
705 !incremental_marking()->IsMarking()) {
709 Object* context = global_contexts_list_;
710 while (!context->IsUndefined()) {
711 // GC can happen when the context is not fully initialized,
712 // so the cache can be undefined.
714 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
715 if (!cache->IsUndefined()) {
716 NormalizedMapCache::cast(cache)->Clear();
718 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
723 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
724 double survival_rate =
725 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
726 start_new_space_size;
728 if (survival_rate > kYoungSurvivalRateHighThreshold) {
729 high_survival_rate_period_length_++;
731 high_survival_rate_period_length_ = 0;
734 if (survival_rate < kYoungSurvivalRateLowThreshold) {
735 low_survival_rate_period_length_++;
737 low_survival_rate_period_length_ = 0;
740 double survival_rate_diff = survival_rate_ - survival_rate;
742 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
743 set_survival_rate_trend(DECREASING);
744 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
745 set_survival_rate_trend(INCREASING);
747 set_survival_rate_trend(STABLE);
750 survival_rate_ = survival_rate;
753 bool Heap::PerformGarbageCollection(GarbageCollector collector,
755 bool next_gc_likely_to_collect_more = false;
757 if (collector != SCAVENGER) {
758 PROFILE(isolate_, CodeMovingGCEvent());
761 if (FLAG_verify_heap) {
764 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
765 ASSERT(!allocation_allowed_);
766 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
767 global_gc_prologue_callback_();
771 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
773 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
774 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
775 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
779 EnsureFromSpaceIsCommitted();
781 int start_new_space_size = Heap::new_space()->SizeAsInt();
783 if (IsHighSurvivalRate()) {
784 // We speed up the incremental marker if it is running so that it
785 // does not fall behind the rate of promotion, which would cause a
786 // constantly growing old space.
787 incremental_marking()->NotifyOfHighPromotionRate();
790 if (collector == MARK_COMPACTOR) {
791 // Perform mark-sweep with optional compaction.
794 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
795 IsStableOrIncreasingSurvivalTrend();
797 UpdateSurvivalRateTrend(start_new_space_size);
799 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSize();
801 if (high_survival_rate_during_scavenges &&
802 IsStableOrIncreasingSurvivalTrend()) {
803 // Stable high survival rates of young objects both during partial and
804 // full collection indicate that mutator is either building or modifying
805 // a structure with a long lifetime.
806 // In this case we aggressively raise old generation memory limits to
807 // postpone subsequent mark-sweep collection and thus trade memory
808 // space for the mutation speed.
809 old_gen_limit_factor_ = 2;
811 old_gen_limit_factor_ = 1;
814 old_gen_promotion_limit_ =
815 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
816 old_gen_allocation_limit_ =
817 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
819 old_gen_exhausted_ = false;
825 UpdateSurvivalRateTrend(start_new_space_size);
828 if (!new_space_high_promotion_mode_active_ &&
829 new_space_.Capacity() == new_space_.MaximumCapacity() &&
830 IsStableOrIncreasingSurvivalTrend() &&
831 IsHighSurvivalRate()) {
832 // Stable high survival rates even though young generation is at
833 // maximum capacity indicates that most objects will be promoted.
834 // To decrease scavenger pauses and final mark-sweep pauses, we
835 // have to limit maximal capacity of the young generation.
836 new_space_high_promotion_mode_active_ = true;
838 PrintF("Limited new space size due to high promotion rate: %d MB\n",
839 new_space_.InitialCapacity() / MB);
841 } else if (new_space_high_promotion_mode_active_ &&
842 IsStableOrDecreasingSurvivalTrend() &&
843 IsLowSurvivalRate()) {
844 // Decreasing low survival rates might indicate that the above high
845 // promotion mode is over and we should allow the young generation
847 new_space_high_promotion_mode_active_ = false;
849 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
850 new_space_.MaximumCapacity() / MB);
854 if (new_space_high_promotion_mode_active_ &&
855 new_space_.Capacity() > new_space_.InitialCapacity()) {
859 isolate_->counters()->objs_since_last_young()->Set(0);
861 gc_post_processing_depth_++;
862 { DisableAssertNoAllocation allow_allocation;
863 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
864 next_gc_likely_to_collect_more =
865 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
867 gc_post_processing_depth_--;
869 // Update relocatables.
870 Relocatable::PostGarbageCollectionProcessing();
872 if (collector == MARK_COMPACTOR) {
873 // Register the amount of external allocated memory.
874 amount_of_external_allocated_memory_at_last_global_gc_ =
875 amount_of_external_allocated_memory_;
878 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
879 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
880 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
881 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
885 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
886 ASSERT(!allocation_allowed_);
887 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
888 global_gc_epilogue_callback_();
890 if (FLAG_verify_heap) {
894 return next_gc_likely_to_collect_more;
898 void Heap::MarkCompact(GCTracer* tracer) {
899 gc_state_ = MARK_COMPACT;
900 LOG(isolate_, ResourceEvent("markcompact", "begin"));
902 mark_compact_collector_.Prepare(tracer);
905 tracer->set_full_gc_count(ms_count_);
907 MarkCompactPrologue();
909 mark_compact_collector_.CollectGarbage();
911 LOG(isolate_, ResourceEvent("markcompact", "end"));
913 gc_state_ = NOT_IN_GC;
915 isolate_->counters()->objs_since_last_full()->Set(0);
917 contexts_disposed_ = 0;
919 isolate_->set_context_exit_happened(false);
923 void Heap::MarkCompactPrologue() {
924 // At any old GC clear the keyed lookup cache to enable collection of unused
926 isolate_->keyed_lookup_cache()->Clear();
927 isolate_->context_slot_cache()->Clear();
928 isolate_->descriptor_lookup_cache()->Clear();
929 StringSplitCache::Clear(string_split_cache());
931 isolate_->compilation_cache()->MarkCompactPrologue();
933 CompletelyClearInstanceofCache();
935 FlushNumberStringCache();
936 if (FLAG_cleanup_code_caches_at_gc) {
937 polymorphic_code_cache()->set_cache(undefined_value());
940 ClearNormalizedMapCaches();
944 Object* Heap::FindCodeObject(Address a) {
945 return isolate()->inner_pointer_to_code_cache()->
946 GcSafeFindCodeForInnerPointer(a);
950 // Helper class for copying HeapObjects
951 class ScavengeVisitor: public ObjectVisitor {
953 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
955 void VisitPointer(Object** p) { ScavengePointer(p); }
957 void VisitPointers(Object** start, Object** end) {
958 // Copy all HeapObject pointers in [start, end)
959 for (Object** p = start; p < end; p++) ScavengePointer(p);
963 void ScavengePointer(Object** p) {
965 if (!heap_->InNewSpace(object)) return;
966 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
967 reinterpret_cast<HeapObject*>(object));
975 // Visitor class to verify pointers in code or data space do not point into
977 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
979 void VisitPointers(Object** start, Object**end) {
980 for (Object** current = start; current < end; current++) {
981 if ((*current)->IsHeapObject()) {
982 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
989 static void VerifyNonPointerSpacePointers() {
990 // Verify that there are no pointers to new space in spaces where we
991 // do not expect them.
992 VerifyNonPointerSpacePointersVisitor v;
993 HeapObjectIterator code_it(HEAP->code_space());
994 for (HeapObject* object = code_it.Next();
995 object != NULL; object = code_it.Next())
998 // The old data space was normally swept conservatively so that the iterator
999 // doesn't work, so we normally skip the next bit.
1000 if (!HEAP->old_data_space()->was_swept_conservatively()) {
1001 HeapObjectIterator data_it(HEAP->old_data_space());
1002 for (HeapObject* object = data_it.Next();
1003 object != NULL; object = data_it.Next())
1004 object->Iterate(&v);
1010 void Heap::CheckNewSpaceExpansionCriteria() {
1011 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1012 survived_since_last_expansion_ > new_space_.Capacity() &&
1013 !new_space_high_promotion_mode_active_) {
1014 // Grow the size of new space if there is room to grow, enough data
1015 // has survived scavenge since the last expansion and we are not in
1016 // high promotion mode.
1018 survived_since_last_expansion_ = 0;
1023 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1024 return heap->InNewSpace(*p) &&
1025 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1029 void Heap::ScavengeStoreBufferCallback(
1032 StoreBufferEvent event) {
1033 heap->store_buffer_rebuilder_.Callback(page, event);
1037 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1038 if (event == kStoreBufferStartScanningPagesEvent) {
1039 start_of_current_page_ = NULL;
1040 current_page_ = NULL;
1041 } else if (event == kStoreBufferScanningPageEvent) {
1042 if (current_page_ != NULL) {
1043 // If this page already overflowed the store buffer during this iteration.
1044 if (current_page_->scan_on_scavenge()) {
1045 // Then we should wipe out the entries that have been added for it.
1046 store_buffer_->SetTop(start_of_current_page_);
1047 } else if (store_buffer_->Top() - start_of_current_page_ >=
1048 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1049 // Did we find too many pointers in the previous page? The heuristic is
1050 // that no page can take more then 1/5 the remaining slots in the store
1052 current_page_->set_scan_on_scavenge(true);
1053 store_buffer_->SetTop(start_of_current_page_);
1055 // In this case the page we scanned took a reasonable number of slots in
1056 // the store buffer. It has now been rehabilitated and is no longer
1057 // marked scan_on_scavenge.
1058 ASSERT(!current_page_->scan_on_scavenge());
1061 start_of_current_page_ = store_buffer_->Top();
1062 current_page_ = page;
1063 } else if (event == kStoreBufferFullEvent) {
1064 // The current page overflowed the store buffer again. Wipe out its entries
1065 // in the store buffer and mark it scan-on-scavenge again. This may happen
1066 // several times while scanning.
1067 if (current_page_ == NULL) {
1068 // Store Buffer overflowed while scanning promoted objects. These are not
1069 // in any particular page, though they are likely to be clustered by the
1070 // allocation routines.
1071 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1073 // Store Buffer overflowed while scanning a particular old space page for
1074 // pointers to new space.
1075 ASSERT(current_page_ == page);
1076 ASSERT(page != NULL);
1077 current_page_->set_scan_on_scavenge(true);
1078 ASSERT(start_of_current_page_ != store_buffer_->Top());
1079 store_buffer_->SetTop(start_of_current_page_);
1087 void PromotionQueue::Initialize() {
1088 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1089 // entries (where each is a pair of intptr_t). This allows us to simplify
1090 // the test fpr when to switch pages.
1091 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1093 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1095 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1096 emergency_stack_ = NULL;
1101 void PromotionQueue::RelocateQueueHead() {
1102 ASSERT(emergency_stack_ == NULL);
1104 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1105 intptr_t* head_start = rear_;
1106 intptr_t* head_end =
1107 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1110 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1112 emergency_stack_ = new List<Entry>(2 * entries_count);
1114 while (head_start != head_end) {
1115 int size = static_cast<int>(*(head_start++));
1116 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1117 emergency_stack_->Add(Entry(obj, size));
1123 void Heap::Scavenge() {
1125 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1128 gc_state_ = SCAVENGE;
1130 // Implements Cheney's copying algorithm
1131 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1133 // Clear descriptor cache.
1134 isolate_->descriptor_lookup_cache()->Clear();
1136 // Used for updating survived_since_last_expansion_ at function end.
1137 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1139 CheckNewSpaceExpansionCriteria();
1141 SelectScavengingVisitorsTable();
1143 incremental_marking()->PrepareForScavenge();
1145 AdvanceSweepers(static_cast<int>(new_space_.Size()));
1147 // Flip the semispaces. After flipping, to space is empty, from space has
1150 new_space_.ResetAllocationInfo();
1152 // We need to sweep newly copied objects which can be either in the
1153 // to space or promoted to the old generation. For to-space
1154 // objects, we treat the bottom of the to space as a queue. Newly
1155 // copied and unswept objects lie between a 'front' mark and the
1156 // allocation pointer.
1158 // Promoted objects can go into various old-generation spaces, and
1159 // can be allocated internally in the spaces (from the free list).
1160 // We treat the top of the to space as a queue of addresses of
1161 // promoted objects. The addresses of newly promoted and unswept
1162 // objects lie between a 'front' mark and a 'rear' mark that is
1163 // updated as a side effect of promoting an object.
1165 // There is guaranteed to be enough room at the top of the to space
1166 // for the addresses of promoted objects: every object promoted
1167 // frees up its size in bytes from the top of the new space, and
1168 // objects are at least one pointer in size.
1169 Address new_space_front = new_space_.ToSpaceStart();
1170 promotion_queue_.Initialize();
1173 store_buffer()->Clean();
1176 ScavengeVisitor scavenge_visitor(this);
1178 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1180 // Copy objects reachable from the old generation.
1182 StoreBufferRebuildScope scope(this,
1184 &ScavengeStoreBufferCallback);
1185 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1188 // Copy objects reachable from cells by scavenging cell values directly.
1189 HeapObjectIterator cell_iterator(cell_space_);
1190 for (HeapObject* cell = cell_iterator.Next();
1191 cell != NULL; cell = cell_iterator.Next()) {
1192 if (cell->IsJSGlobalPropertyCell()) {
1193 Address value_address =
1194 reinterpret_cast<Address>(cell) +
1195 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1196 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1200 // Scavenge object reachable from the global contexts list directly.
1201 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1203 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1204 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1205 &IsUnscavengedHeapObject);
1206 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1208 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1210 UpdateNewSpaceReferencesInExternalStringTable(
1211 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1213 promotion_queue_.Destroy();
1215 LiveObjectList::UpdateReferencesForScavengeGC();
1216 if (!FLAG_watch_ic_patching) {
1217 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1219 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1221 ASSERT(new_space_front == new_space_.top());
1224 new_space_.set_age_mark(new_space_.top());
1226 new_space_.LowerInlineAllocationLimit(
1227 new_space_.inline_allocation_limit_step());
1229 // Update how much has survived scavenge.
1230 IncrementYoungSurvivorsCounter(static_cast<int>(
1231 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1233 LOG(isolate_, ResourceEvent("scavenge", "end"));
1235 gc_state_ = NOT_IN_GC;
1237 scavenges_since_last_idle_round_++;
1241 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1243 MapWord first_word = HeapObject::cast(*p)->map_word();
1245 if (!first_word.IsForwardingAddress()) {
1246 // Unreachable external string can be finalized.
1247 heap->FinalizeExternalString(String::cast(*p));
1251 // String is still reachable.
1252 return String::cast(first_word.ToForwardingAddress());
1256 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1257 ExternalStringTableUpdaterCallback updater_func) {
1258 if (FLAG_verify_heap) {
1259 external_string_table_.Verify();
1262 if (external_string_table_.new_space_strings_.is_empty()) return;
1264 Object** start = &external_string_table_.new_space_strings_[0];
1265 Object** end = start + external_string_table_.new_space_strings_.length();
1266 Object** last = start;
1268 for (Object** p = start; p < end; ++p) {
1269 ASSERT(InFromSpace(*p));
1270 String* target = updater_func(this, p);
1272 if (target == NULL) continue;
1274 ASSERT(target->IsExternalString());
1276 if (InNewSpace(target)) {
1277 // String is still in new space. Update the table entry.
1281 // String got promoted. Move it to the old string list.
1282 external_string_table_.AddOldString(target);
1286 ASSERT(last <= end);
1287 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1291 void Heap::UpdateReferencesInExternalStringTable(
1292 ExternalStringTableUpdaterCallback updater_func) {
1294 // Update old space string references.
1295 if (external_string_table_.old_space_strings_.length() > 0) {
1296 Object** start = &external_string_table_.old_space_strings_[0];
1297 Object** end = start + external_string_table_.old_space_strings_.length();
1298 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1301 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1305 static Object* ProcessFunctionWeakReferences(Heap* heap,
1307 WeakObjectRetainer* retainer) {
1308 Object* undefined = heap->undefined_value();
1309 Object* head = undefined;
1310 JSFunction* tail = NULL;
1311 Object* candidate = function;
1312 while (candidate != undefined) {
1313 // Check whether to keep the candidate in the list.
1314 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1315 Object* retain = retainer->RetainAs(candidate);
1316 if (retain != NULL) {
1317 if (head == undefined) {
1318 // First element in the list.
1321 // Subsequent elements in the list.
1322 ASSERT(tail != NULL);
1323 tail->set_next_function_link(retain);
1325 // Retained function is new tail.
1326 candidate_function = reinterpret_cast<JSFunction*>(retain);
1327 tail = candidate_function;
1329 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1331 if (retain == undefined) break;
1334 // Move to next element in the list.
1335 candidate = candidate_function->next_function_link();
1338 // Terminate the list if there is one or more elements.
1340 tail->set_next_function_link(undefined);
1347 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1348 Object* undefined = undefined_value();
1349 Object* head = undefined;
1350 Context* tail = NULL;
1351 Object* candidate = global_contexts_list_;
1352 while (candidate != undefined) {
1353 // Check whether to keep the candidate in the list.
1354 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1355 Object* retain = retainer->RetainAs(candidate);
1356 if (retain != NULL) {
1357 if (head == undefined) {
1358 // First element in the list.
1361 // Subsequent elements in the list.
1362 ASSERT(tail != NULL);
1363 tail->set_unchecked(this,
1364 Context::NEXT_CONTEXT_LINK,
1366 UPDATE_WRITE_BARRIER);
1368 // Retained context is new tail.
1369 candidate_context = reinterpret_cast<Context*>(retain);
1370 tail = candidate_context;
1372 if (retain == undefined) break;
1374 // Process the weak list of optimized functions for the context.
1375 Object* function_list_head =
1376 ProcessFunctionWeakReferences(
1378 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1380 candidate_context->set_unchecked(this,
1381 Context::OPTIMIZED_FUNCTIONS_LIST,
1383 UPDATE_WRITE_BARRIER);
1386 // Move to next element in the list.
1387 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1390 // Terminate the list if there is one or more elements.
1392 tail->set_unchecked(this,
1393 Context::NEXT_CONTEXT_LINK,
1394 Heap::undefined_value(),
1395 UPDATE_WRITE_BARRIER);
1398 // Update the head of the list of contexts.
1399 global_contexts_list_ = head;
1403 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1404 AssertNoAllocation no_allocation;
1406 class VisitorAdapter : public ObjectVisitor {
1408 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1409 : visitor_(visitor) {}
1410 virtual void VisitPointers(Object** start, Object** end) {
1411 for (Object** p = start; p < end; p++) {
1412 if ((*p)->IsExternalString()) {
1413 visitor_->VisitExternalString(Utils::ToLocal(
1414 Handle<String>(String::cast(*p))));
1419 v8::ExternalResourceVisitor* visitor_;
1420 } visitor_adapter(visitor);
1421 external_string_table_.Iterate(&visitor_adapter);
1425 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1427 static inline void VisitPointer(Heap* heap, Object** p) {
1428 Object* object = *p;
1429 if (!heap->InNewSpace(object)) return;
1430 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1431 reinterpret_cast<HeapObject*>(object));
1436 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1437 Address new_space_front) {
1439 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1440 // The addresses new_space_front and new_space_.top() define a
1441 // queue of unprocessed copied objects. Process them until the
1443 while (new_space_front != new_space_.top()) {
1444 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1445 HeapObject* object = HeapObject::FromAddress(new_space_front);
1447 NewSpaceScavenger::IterateBody(object->map(), object);
1450 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1454 // Promote and process all the to-be-promoted objects.
1456 StoreBufferRebuildScope scope(this,
1458 &ScavengeStoreBufferCallback);
1459 while (!promotion_queue()->is_empty()) {
1462 promotion_queue()->remove(&target, &size);
1464 // Promoted object might be already partially visited
1465 // during old space pointer iteration. Thus we search specificly
1466 // for pointers to from semispace instead of looking for pointers
1468 ASSERT(!target->IsMap());
1469 IterateAndMarkPointersToFromSpace(target->address(),
1470 target->address() + size,
1475 // Take another spin if there are now unswept objects in new space
1476 // (there are currently no more unswept promoted objects).
1477 } while (new_space_front != new_space_.top());
1479 return new_space_front;
1483 enum LoggingAndProfiling {
1484 LOGGING_AND_PROFILING_ENABLED,
1485 LOGGING_AND_PROFILING_DISABLED
1489 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1492 template<MarksHandling marks_handling,
1493 LoggingAndProfiling logging_and_profiling_mode>
1494 class ScavengingVisitor : public StaticVisitorBase {
1496 static void Initialize() {
1497 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1498 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1499 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1500 table_.Register(kVisitByteArray, &EvacuateByteArray);
1501 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1502 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1504 table_.Register(kVisitGlobalContext,
1505 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1506 template VisitSpecialized<Context::kSize>);
1508 table_.Register(kVisitConsString,
1509 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1510 template VisitSpecialized<ConsString::kSize>);
1512 table_.Register(kVisitSlicedString,
1513 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1514 template VisitSpecialized<SlicedString::kSize>);
1516 table_.Register(kVisitSharedFunctionInfo,
1517 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1518 template VisitSpecialized<SharedFunctionInfo::kSize>);
1520 table_.Register(kVisitJSWeakMap,
1521 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1524 table_.Register(kVisitJSRegExp,
1525 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1528 if (marks_handling == IGNORE_MARKS) {
1529 table_.Register(kVisitJSFunction,
1530 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1531 template VisitSpecialized<JSFunction::kSize>);
1533 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1536 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1538 kVisitDataObjectGeneric>();
1540 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1542 kVisitJSObjectGeneric>();
1544 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1546 kVisitStructGeneric>();
1549 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1554 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1555 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1557 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1558 bool should_record = false;
1560 should_record = FLAG_heap_stats;
1562 should_record = should_record || FLAG_log_gc;
1563 if (should_record) {
1564 if (heap->new_space()->Contains(obj)) {
1565 heap->new_space()->RecordAllocation(obj);
1567 heap->new_space()->RecordPromotion(obj);
1572 // Helper function used by CopyObject to copy a source object to an
1573 // allocated target object and update the forwarding pointer in the source
1574 // object. Returns the target object.
1575 INLINE(static void MigrateObject(Heap* heap,
1579 // Copy the content of source to target.
1580 heap->CopyBlock(target->address(), source->address(), size);
1582 // Set the forwarding address.
1583 source->set_map_word(MapWord::FromForwardingAddress(target));
1585 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1586 // Update NewSpace stats if necessary.
1587 RecordCopiedObject(heap, target);
1588 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1589 Isolate* isolate = heap->isolate();
1590 if (isolate->logger()->is_logging() ||
1591 CpuProfiler::is_profiling(isolate)) {
1592 if (target->IsSharedFunctionInfo()) {
1593 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1594 source->address(), target->address()));
1599 if (marks_handling == TRANSFER_MARKS) {
1600 if (Marking::TransferColor(source, target)) {
1601 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1606 template<ObjectContents object_contents, SizeRestriction size_restriction>
1607 static inline void EvacuateObject(Map* map,
1611 SLOW_ASSERT((size_restriction != SMALL) ||
1612 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1613 SLOW_ASSERT(object->Size() == object_size);
1615 Heap* heap = map->GetHeap();
1616 if (heap->ShouldBePromoted(object->address(), object_size)) {
1617 MaybeObject* maybe_result;
1619 if ((size_restriction != SMALL) &&
1620 (object_size > Page::kMaxNonCodeHeapObjectSize)) {
1621 maybe_result = heap->lo_space()->AllocateRaw(object_size,
1624 if (object_contents == DATA_OBJECT) {
1625 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
1627 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
1631 Object* result = NULL; // Initialization to please compiler.
1632 if (maybe_result->ToObject(&result)) {
1633 HeapObject* target = HeapObject::cast(result);
1635 // Order is important: slot might be inside of the target if target
1636 // was allocated over a dead object and slot comes from the store
1639 MigrateObject(heap, object, target, object_size);
1641 if (object_contents == POINTER_OBJECT) {
1642 heap->promotion_queue()->insert(target, object_size);
1645 heap->tracer()->increment_promoted_objects_size(object_size);
1649 MaybeObject* allocation = heap->new_space()->AllocateRaw(object_size);
1650 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1651 Object* result = allocation->ToObjectUnchecked();
1652 HeapObject* target = HeapObject::cast(result);
1654 // Order is important: slot might be inside of the target if target
1655 // was allocated over a dead object and slot comes from the store
1658 MigrateObject(heap, object, target, object_size);
1663 static inline void EvacuateJSFunction(Map* map,
1665 HeapObject* object) {
1666 ObjectEvacuationStrategy<POINTER_OBJECT>::
1667 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1669 HeapObject* target = *slot;
1670 MarkBit mark_bit = Marking::MarkBitFrom(target);
1671 if (Marking::IsBlack(mark_bit)) {
1672 // This object is black and it might not be rescanned by marker.
1673 // We should explicitly record code entry slot for compaction because
1674 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1675 // miss it as it is not HeapObject-tagged.
1676 Address code_entry_slot =
1677 target->address() + JSFunction::kCodeEntryOffset;
1678 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1679 map->GetHeap()->mark_compact_collector()->
1680 RecordCodeEntrySlot(code_entry_slot, code);
1685 static inline void EvacuateFixedArray(Map* map,
1687 HeapObject* object) {
1688 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1689 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1696 static inline void EvacuateFixedDoubleArray(Map* map,
1698 HeapObject* object) {
1699 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1700 int object_size = FixedDoubleArray::SizeFor(length);
1701 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1708 static inline void EvacuateByteArray(Map* map,
1710 HeapObject* object) {
1711 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1712 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1716 static inline void EvacuateSeqAsciiString(Map* map,
1718 HeapObject* object) {
1719 int object_size = SeqAsciiString::cast(object)->
1720 SeqAsciiStringSize(map->instance_type());
1721 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1725 static inline void EvacuateSeqTwoByteString(Map* map,
1727 HeapObject* object) {
1728 int object_size = SeqTwoByteString::cast(object)->
1729 SeqTwoByteStringSize(map->instance_type());
1730 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1734 static inline bool IsShortcutCandidate(int type) {
1735 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1738 static inline void EvacuateShortcutCandidate(Map* map,
1740 HeapObject* object) {
1741 ASSERT(IsShortcutCandidate(map->instance_type()));
1743 Heap* heap = map->GetHeap();
1745 if (marks_handling == IGNORE_MARKS &&
1746 ConsString::cast(object)->unchecked_second() ==
1747 heap->empty_string()) {
1749 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1753 if (!heap->InNewSpace(first)) {
1754 object->set_map_word(MapWord::FromForwardingAddress(first));
1758 MapWord first_word = first->map_word();
1759 if (first_word.IsForwardingAddress()) {
1760 HeapObject* target = first_word.ToForwardingAddress();
1763 object->set_map_word(MapWord::FromForwardingAddress(target));
1767 heap->DoScavengeObject(first->map(), slot, first);
1768 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1772 int object_size = ConsString::kSize;
1773 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
1776 template<ObjectContents object_contents>
1777 class ObjectEvacuationStrategy {
1779 template<int object_size>
1780 static inline void VisitSpecialized(Map* map,
1782 HeapObject* object) {
1783 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1786 static inline void Visit(Map* map,
1788 HeapObject* object) {
1789 int object_size = map->instance_size();
1790 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1794 static VisitorDispatchTable<ScavengingCallback> table_;
1798 template<MarksHandling marks_handling,
1799 LoggingAndProfiling logging_and_profiling_mode>
1800 VisitorDispatchTable<ScavengingCallback>
1801 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1804 static void InitializeScavengingVisitorsTables() {
1805 ScavengingVisitor<TRANSFER_MARKS,
1806 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1807 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1808 ScavengingVisitor<TRANSFER_MARKS,
1809 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1810 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1814 void Heap::SelectScavengingVisitorsTable() {
1815 bool logging_and_profiling =
1816 isolate()->logger()->is_logging() ||
1817 CpuProfiler::is_profiling(isolate()) ||
1818 (isolate()->heap_profiler() != NULL &&
1819 isolate()->heap_profiler()->is_profiling());
1821 if (!incremental_marking()->IsMarking()) {
1822 if (!logging_and_profiling) {
1823 scavenging_visitors_table_.CopyFrom(
1824 ScavengingVisitor<IGNORE_MARKS,
1825 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1827 scavenging_visitors_table_.CopyFrom(
1828 ScavengingVisitor<IGNORE_MARKS,
1829 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1832 if (!logging_and_profiling) {
1833 scavenging_visitors_table_.CopyFrom(
1834 ScavengingVisitor<TRANSFER_MARKS,
1835 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1837 scavenging_visitors_table_.CopyFrom(
1838 ScavengingVisitor<TRANSFER_MARKS,
1839 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1842 if (incremental_marking()->IsCompacting()) {
1843 // When compacting forbid short-circuiting of cons-strings.
1844 // Scavenging code relies on the fact that new space object
1845 // can't be evacuated into evacuation candidate but
1846 // short-circuiting violates this assumption.
1847 scavenging_visitors_table_.Register(
1848 StaticVisitorBase::kVisitShortcutCandidate,
1849 scavenging_visitors_table_.GetVisitorById(
1850 StaticVisitorBase::kVisitConsString));
1856 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1857 SLOW_ASSERT(HEAP->InFromSpace(object));
1858 MapWord first_word = object->map_word();
1859 SLOW_ASSERT(!first_word.IsForwardingAddress());
1860 Map* map = first_word.ToMap();
1861 map->GetHeap()->DoScavengeObject(map, p, object);
1865 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1866 int instance_size) {
1868 { MaybeObject* maybe_result = AllocateRawMap();
1869 if (!maybe_result->ToObject(&result)) return maybe_result;
1872 // Map::cast cannot be used due to uninitialized map field.
1873 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1874 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1875 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1876 reinterpret_cast<Map*>(result)->set_visitor_id(
1877 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1878 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
1879 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
1880 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1881 reinterpret_cast<Map*>(result)->set_bit_field(0);
1882 reinterpret_cast<Map*>(result)->set_bit_field2(0);
1887 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
1889 ElementsKind elements_kind) {
1891 { MaybeObject* maybe_result = AllocateRawMap();
1892 if (!maybe_result->ToObject(&result)) return maybe_result;
1895 Map* map = reinterpret_cast<Map*>(result);
1896 map->set_map_no_write_barrier(meta_map());
1897 map->set_instance_type(instance_type);
1898 map->set_visitor_id(
1899 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1900 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
1901 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
1902 map->set_instance_size(instance_size);
1903 map->set_inobject_properties(0);
1904 map->set_pre_allocated_property_fields(0);
1905 map->init_instance_descriptors();
1906 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1907 map->set_prototype_transitions(empty_fixed_array(), SKIP_WRITE_BARRIER);
1908 map->set_unused_property_fields(0);
1909 map->set_bit_field(0);
1910 map->set_bit_field2(1 << Map::kIsExtensible);
1911 map->set_elements_kind(elements_kind);
1913 // If the map object is aligned fill the padding area with Smi 0 objects.
1914 if (Map::kPadStart < Map::kSize) {
1915 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1917 Map::kSize - Map::kPadStart);
1923 MaybeObject* Heap::AllocateCodeCache() {
1924 CodeCache* code_cache;
1925 { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
1926 if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
1928 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1929 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
1934 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1935 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1939 MaybeObject* Heap::AllocateAccessorPair() {
1940 AccessorPair* accessors;
1941 { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
1942 if (!maybe_accessors->To(&accessors)) return maybe_accessors;
1944 accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
1945 accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
1950 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
1951 TypeFeedbackInfo* info;
1952 { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
1953 if (!maybe_info->To(&info)) return maybe_info;
1955 info->set_ic_total_count(0);
1956 info->set_ic_with_typeinfo_count(0);
1957 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
1958 SKIP_WRITE_BARRIER);
1963 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
1964 AliasedArgumentsEntry* entry;
1965 { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
1966 if (!maybe_entry->To(&entry)) return maybe_entry;
1968 entry->set_aliased_context_slot(aliased_context_slot);
1973 const Heap::StringTypeTable Heap::string_type_table[] = {
1974 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1975 {type, size, k##camel_name##MapRootIndex},
1976 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1977 #undef STRING_TYPE_ELEMENT
1981 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1982 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1983 {contents, k##name##RootIndex},
1984 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1985 #undef CONSTANT_SYMBOL_ELEMENT
1989 const Heap::StructTable Heap::struct_table[] = {
1990 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1991 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1992 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1993 #undef STRUCT_TABLE_ELEMENT
1997 bool Heap::CreateInitialMaps() {
1999 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2000 if (!maybe_obj->ToObject(&obj)) return false;
2002 // Map::cast cannot be used due to uninitialized map field.
2003 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2004 set_meta_map(new_meta_map);
2005 new_meta_map->set_map(new_meta_map);
2007 { MaybeObject* maybe_obj =
2008 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2009 if (!maybe_obj->ToObject(&obj)) return false;
2011 set_fixed_array_map(Map::cast(obj));
2013 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2014 if (!maybe_obj->ToObject(&obj)) return false;
2016 set_oddball_map(Map::cast(obj));
2018 // Allocate the empty array.
2019 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2020 if (!maybe_obj->ToObject(&obj)) return false;
2022 set_empty_fixed_array(FixedArray::cast(obj));
2024 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2025 if (!maybe_obj->ToObject(&obj)) return false;
2027 set_null_value(Oddball::cast(obj));
2028 Oddball::cast(obj)->set_kind(Oddball::kNull);
2030 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2031 if (!maybe_obj->ToObject(&obj)) return false;
2033 set_undefined_value(Oddball::cast(obj));
2034 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2035 ASSERT(!InNewSpace(undefined_value()));
2037 // Allocate the empty descriptor array.
2038 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2039 if (!maybe_obj->ToObject(&obj)) return false;
2041 set_empty_descriptor_array(DescriptorArray::cast(obj));
2043 // Fix the instance_descriptors for the existing maps.
2044 meta_map()->init_instance_descriptors();
2045 meta_map()->set_code_cache(empty_fixed_array());
2046 meta_map()->set_prototype_transitions(empty_fixed_array());
2048 fixed_array_map()->init_instance_descriptors();
2049 fixed_array_map()->set_code_cache(empty_fixed_array());
2050 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
2052 oddball_map()->init_instance_descriptors();
2053 oddball_map()->set_code_cache(empty_fixed_array());
2054 oddball_map()->set_prototype_transitions(empty_fixed_array());
2056 // Fix prototype object for existing maps.
2057 meta_map()->set_prototype(null_value());
2058 meta_map()->set_constructor(null_value());
2060 fixed_array_map()->set_prototype(null_value());
2061 fixed_array_map()->set_constructor(null_value());
2063 oddball_map()->set_prototype(null_value());
2064 oddball_map()->set_constructor(null_value());
2066 { MaybeObject* maybe_obj =
2067 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2068 if (!maybe_obj->ToObject(&obj)) return false;
2070 set_fixed_cow_array_map(Map::cast(obj));
2071 ASSERT(fixed_array_map() != fixed_cow_array_map());
2073 { MaybeObject* maybe_obj =
2074 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2075 if (!maybe_obj->ToObject(&obj)) return false;
2077 set_scope_info_map(Map::cast(obj));
2079 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2080 if (!maybe_obj->ToObject(&obj)) return false;
2082 set_heap_number_map(Map::cast(obj));
2084 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2085 if (!maybe_obj->ToObject(&obj)) return false;
2087 set_foreign_map(Map::cast(obj));
2089 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2090 const StringTypeTable& entry = string_type_table[i];
2091 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2092 if (!maybe_obj->ToObject(&obj)) return false;
2094 roots_[entry.index] = Map::cast(obj);
2097 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2098 if (!maybe_obj->ToObject(&obj)) return false;
2100 set_undetectable_string_map(Map::cast(obj));
2101 Map::cast(obj)->set_is_undetectable();
2103 { MaybeObject* maybe_obj =
2104 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2105 if (!maybe_obj->ToObject(&obj)) return false;
2107 set_undetectable_ascii_string_map(Map::cast(obj));
2108 Map::cast(obj)->set_is_undetectable();
2110 { MaybeObject* maybe_obj =
2111 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2112 if (!maybe_obj->ToObject(&obj)) return false;
2114 set_fixed_double_array_map(Map::cast(obj));
2116 { MaybeObject* maybe_obj =
2117 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2118 if (!maybe_obj->ToObject(&obj)) return false;
2120 set_byte_array_map(Map::cast(obj));
2122 { MaybeObject* maybe_obj =
2123 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2124 if (!maybe_obj->ToObject(&obj)) return false;
2126 set_free_space_map(Map::cast(obj));
2128 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2129 if (!maybe_obj->ToObject(&obj)) return false;
2131 set_empty_byte_array(ByteArray::cast(obj));
2133 { MaybeObject* maybe_obj =
2134 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2135 if (!maybe_obj->ToObject(&obj)) return false;
2137 set_external_pixel_array_map(Map::cast(obj));
2139 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2140 ExternalArray::kAlignedSize);
2141 if (!maybe_obj->ToObject(&obj)) return false;
2143 set_external_byte_array_map(Map::cast(obj));
2145 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2146 ExternalArray::kAlignedSize);
2147 if (!maybe_obj->ToObject(&obj)) return false;
2149 set_external_unsigned_byte_array_map(Map::cast(obj));
2151 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2152 ExternalArray::kAlignedSize);
2153 if (!maybe_obj->ToObject(&obj)) return false;
2155 set_external_short_array_map(Map::cast(obj));
2157 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2158 ExternalArray::kAlignedSize);
2159 if (!maybe_obj->ToObject(&obj)) return false;
2161 set_external_unsigned_short_array_map(Map::cast(obj));
2163 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2164 ExternalArray::kAlignedSize);
2165 if (!maybe_obj->ToObject(&obj)) return false;
2167 set_external_int_array_map(Map::cast(obj));
2169 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2170 ExternalArray::kAlignedSize);
2171 if (!maybe_obj->ToObject(&obj)) return false;
2173 set_external_unsigned_int_array_map(Map::cast(obj));
2175 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2176 ExternalArray::kAlignedSize);
2177 if (!maybe_obj->ToObject(&obj)) return false;
2179 set_external_float_array_map(Map::cast(obj));
2181 { MaybeObject* maybe_obj =
2182 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2183 if (!maybe_obj->ToObject(&obj)) return false;
2185 set_non_strict_arguments_elements_map(Map::cast(obj));
2187 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2188 ExternalArray::kAlignedSize);
2189 if (!maybe_obj->ToObject(&obj)) return false;
2191 set_external_double_array_map(Map::cast(obj));
2193 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2194 if (!maybe_obj->ToObject(&obj)) return false;
2196 set_code_map(Map::cast(obj));
2198 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2199 JSGlobalPropertyCell::kSize);
2200 if (!maybe_obj->ToObject(&obj)) return false;
2202 set_global_property_cell_map(Map::cast(obj));
2204 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2205 if (!maybe_obj->ToObject(&obj)) return false;
2207 set_one_pointer_filler_map(Map::cast(obj));
2209 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2210 if (!maybe_obj->ToObject(&obj)) return false;
2212 set_two_pointer_filler_map(Map::cast(obj));
2214 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2215 const StructTable& entry = struct_table[i];
2216 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2217 if (!maybe_obj->ToObject(&obj)) return false;
2219 roots_[entry.index] = Map::cast(obj);
2222 { MaybeObject* maybe_obj =
2223 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2224 if (!maybe_obj->ToObject(&obj)) return false;
2226 set_hash_table_map(Map::cast(obj));
2228 { MaybeObject* maybe_obj =
2229 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2230 if (!maybe_obj->ToObject(&obj)) return false;
2232 set_function_context_map(Map::cast(obj));
2234 { MaybeObject* maybe_obj =
2235 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2236 if (!maybe_obj->ToObject(&obj)) return false;
2238 set_catch_context_map(Map::cast(obj));
2240 { MaybeObject* maybe_obj =
2241 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2242 if (!maybe_obj->ToObject(&obj)) return false;
2244 set_with_context_map(Map::cast(obj));
2246 { MaybeObject* maybe_obj =
2247 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2248 if (!maybe_obj->ToObject(&obj)) return false;
2250 set_block_context_map(Map::cast(obj));
2252 { MaybeObject* maybe_obj =
2253 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2254 if (!maybe_obj->ToObject(&obj)) return false;
2256 set_module_context_map(Map::cast(obj));
2258 { MaybeObject* maybe_obj =
2259 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2260 if (!maybe_obj->ToObject(&obj)) return false;
2262 Map* global_context_map = Map::cast(obj);
2263 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2264 set_global_context_map(global_context_map);
2266 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2267 SharedFunctionInfo::kAlignedSize);
2268 if (!maybe_obj->ToObject(&obj)) return false;
2270 set_shared_function_info_map(Map::cast(obj));
2272 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2273 JSMessageObject::kSize);
2274 if (!maybe_obj->ToObject(&obj)) return false;
2276 set_message_object_map(Map::cast(obj));
2278 ASSERT(!InNewSpace(empty_fixed_array()));
2283 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2284 // Statically ensure that it is safe to allocate heap numbers in paged
2286 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2287 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2290 { MaybeObject* maybe_result =
2291 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2292 if (!maybe_result->ToObject(&result)) return maybe_result;
2295 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2296 HeapNumber::cast(result)->set_value(value);
2301 MaybeObject* Heap::AllocateHeapNumber(double value) {
2302 // Use general version, if we're forced to always allocate.
2303 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2305 // This version of AllocateHeapNumber is optimized for
2306 // allocation in new space.
2307 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2308 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2310 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2311 if (!maybe_result->ToObject(&result)) return maybe_result;
2313 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2314 HeapNumber::cast(result)->set_value(value);
2319 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2321 { MaybeObject* maybe_result = AllocateRawCell();
2322 if (!maybe_result->ToObject(&result)) return maybe_result;
2324 HeapObject::cast(result)->set_map_no_write_barrier(
2325 global_property_cell_map());
2326 JSGlobalPropertyCell::cast(result)->set_value(value);
2331 MaybeObject* Heap::CreateOddball(const char* to_string,
2335 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2336 if (!maybe_result->ToObject(&result)) return maybe_result;
2338 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2342 bool Heap::CreateApiObjects() {
2345 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2346 if (!maybe_obj->ToObject(&obj)) return false;
2348 // Don't use Smi-only elements optimizations for objects with the neander
2349 // map. There are too many cases where element values are set directly with a
2350 // bottleneck to trap the Smi-only -> fast elements transition, and there
2351 // appears to be no benefit for optimize this case.
2352 Map* new_neander_map = Map::cast(obj);
2353 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2354 set_neander_map(new_neander_map);
2356 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2357 if (!maybe_obj->ToObject(&obj)) return false;
2360 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2361 if (!maybe_elements->ToObject(&elements)) return false;
2363 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2364 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2365 set_message_listeners(JSObject::cast(obj));
2371 void Heap::CreateJSEntryStub() {
2373 set_js_entry_code(*stub.GetCode());
2377 void Heap::CreateJSConstructEntryStub() {
2378 JSConstructEntryStub stub;
2379 set_js_construct_entry_code(*stub.GetCode());
2383 void Heap::CreateFixedStubs() {
2384 // Here we create roots for fixed stubs. They are needed at GC
2385 // for cooking and uncooking (check out frames.cc).
2386 // The eliminates the need for doing dictionary lookup in the
2387 // stub cache for these stubs.
2389 // gcc-4.4 has problem generating correct code of following snippet:
2390 // { JSEntryStub stub;
2391 // js_entry_code_ = *stub.GetCode();
2393 // { JSConstructEntryStub stub;
2394 // js_construct_entry_code_ = *stub.GetCode();
2396 // To workaround the problem, make separate functions without inlining.
2397 Heap::CreateJSEntryStub();
2398 Heap::CreateJSConstructEntryStub();
2400 // Create stubs that should be there, so we don't unexpectedly have to
2401 // create them if we need them during the creation of another stub.
2402 // Stub creation mixes raw pointers and handles in an unsafe manner so
2403 // we cannot create stubs while we are creating stubs.
2404 CodeStub::GenerateStubsAheadOfTime();
2408 bool Heap::CreateInitialObjects() {
2411 // The -0 value must be set before NumberFromDouble works.
2412 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2413 if (!maybe_obj->ToObject(&obj)) return false;
2415 set_minus_zero_value(HeapNumber::cast(obj));
2416 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2418 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2419 if (!maybe_obj->ToObject(&obj)) return false;
2421 set_nan_value(HeapNumber::cast(obj));
2423 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2424 if (!maybe_obj->ToObject(&obj)) return false;
2426 set_infinity_value(HeapNumber::cast(obj));
2428 // The hole has not been created yet, but we want to put something
2429 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2430 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2432 // Allocate initial symbol table.
2433 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2434 if (!maybe_obj->ToObject(&obj)) return false;
2436 // Don't use set_symbol_table() due to asserts.
2437 roots_[kSymbolTableRootIndex] = obj;
2439 // Finish initializing oddballs after creating symboltable.
2440 { MaybeObject* maybe_obj =
2441 undefined_value()->Initialize("undefined",
2443 Oddball::kUndefined);
2444 if (!maybe_obj->ToObject(&obj)) return false;
2447 // Initialize the null_value.
2448 { MaybeObject* maybe_obj =
2449 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2450 if (!maybe_obj->ToObject(&obj)) return false;
2453 { MaybeObject* maybe_obj = CreateOddball("true",
2456 if (!maybe_obj->ToObject(&obj)) return false;
2458 set_true_value(Oddball::cast(obj));
2460 { MaybeObject* maybe_obj = CreateOddball("false",
2463 if (!maybe_obj->ToObject(&obj)) return false;
2465 set_false_value(Oddball::cast(obj));
2467 { MaybeObject* maybe_obj = CreateOddball("hole",
2470 if (!maybe_obj->ToObject(&obj)) return false;
2472 set_the_hole_value(Oddball::cast(obj));
2474 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2476 Oddball::kArgumentMarker);
2477 if (!maybe_obj->ToObject(&obj)) return false;
2479 set_arguments_marker(Oddball::cast(obj));
2481 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2484 if (!maybe_obj->ToObject(&obj)) return false;
2486 set_no_interceptor_result_sentinel(obj);
2488 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2491 if (!maybe_obj->ToObject(&obj)) return false;
2493 set_termination_exception(obj);
2495 // Allocate the empty string.
2496 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2497 if (!maybe_obj->ToObject(&obj)) return false;
2499 set_empty_string(String::cast(obj));
2501 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2502 { MaybeObject* maybe_obj =
2503 LookupAsciiSymbol(constant_symbol_table[i].contents);
2504 if (!maybe_obj->ToObject(&obj)) return false;
2506 roots_[constant_symbol_table[i].index] = String::cast(obj);
2509 // Allocate the hidden symbol which is used to identify the hidden properties
2510 // in JSObjects. The hash code has a special value so that it will not match
2511 // the empty string when searching for the property. It cannot be part of the
2512 // loop above because it needs to be allocated manually with the special
2513 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2514 // that it will always be at the first entry in property descriptors.
2515 { MaybeObject* maybe_obj =
2516 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2517 if (!maybe_obj->ToObject(&obj)) return false;
2519 hidden_symbol_ = String::cast(obj);
2521 // Allocate the foreign for __proto__.
2522 { MaybeObject* maybe_obj =
2523 AllocateForeign((Address) &Accessors::ObjectPrototype);
2524 if (!maybe_obj->ToObject(&obj)) return false;
2526 set_prototype_accessors(Foreign::cast(obj));
2528 // Allocate the code_stubs dictionary. The initial size is set to avoid
2529 // expanding the dictionary during bootstrapping.
2530 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2531 if (!maybe_obj->ToObject(&obj)) return false;
2533 set_code_stubs(UnseededNumberDictionary::cast(obj));
2536 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2537 // is set to avoid expanding the dictionary during bootstrapping.
2538 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2539 if (!maybe_obj->ToObject(&obj)) return false;
2541 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2543 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2544 if (!maybe_obj->ToObject(&obj)) return false;
2546 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2548 set_instanceof_cache_function(Smi::FromInt(0));
2549 set_instanceof_cache_map(Smi::FromInt(0));
2550 set_instanceof_cache_answer(Smi::FromInt(0));
2554 // Allocate the dictionary of intrinsic function names.
2555 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2556 if (!maybe_obj->ToObject(&obj)) return false;
2558 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2560 if (!maybe_obj->ToObject(&obj)) return false;
2562 set_intrinsic_function_names(StringDictionary::cast(obj));
2564 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2565 if (!maybe_obj->ToObject(&obj)) return false;
2567 set_number_string_cache(FixedArray::cast(obj));
2569 // Allocate cache for single character ASCII strings.
2570 { MaybeObject* maybe_obj =
2571 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2572 if (!maybe_obj->ToObject(&obj)) return false;
2574 set_single_character_string_cache(FixedArray::cast(obj));
2576 // Allocate cache for string split.
2577 { MaybeObject* maybe_obj =
2578 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2579 if (!maybe_obj->ToObject(&obj)) return false;
2581 set_string_split_cache(FixedArray::cast(obj));
2583 // Allocate cache for external strings pointing to native source code.
2584 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2585 if (!maybe_obj->ToObject(&obj)) return false;
2587 set_natives_source_cache(FixedArray::cast(obj));
2589 // Handling of script id generation is in FACTORY->NewScript.
2590 set_last_script_id(undefined_value());
2592 // Initialize keyed lookup cache.
2593 isolate_->keyed_lookup_cache()->Clear();
2595 // Initialize context slot cache.
2596 isolate_->context_slot_cache()->Clear();
2598 // Initialize descriptor cache.
2599 isolate_->descriptor_lookup_cache()->Clear();
2601 // Initialize compilation cache.
2602 isolate_->compilation_cache()->Clear();
2608 Object* StringSplitCache::Lookup(
2609 FixedArray* cache, String* string, String* pattern) {
2610 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2611 uint32_t hash = string->Hash();
2612 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2613 ~(kArrayEntriesPerCacheEntry - 1));
2614 if (cache->get(index + kStringOffset) == string &&
2615 cache->get(index + kPatternOffset) == pattern) {
2616 return cache->get(index + kArrayOffset);
2618 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2619 if (cache->get(index + kStringOffset) == string &&
2620 cache->get(index + kPatternOffset) == pattern) {
2621 return cache->get(index + kArrayOffset);
2623 return Smi::FromInt(0);
2627 void StringSplitCache::Enter(Heap* heap,
2631 FixedArray* array) {
2632 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2633 uint32_t hash = string->Hash();
2634 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2635 ~(kArrayEntriesPerCacheEntry - 1));
2636 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2637 cache->set(index + kStringOffset, string);
2638 cache->set(index + kPatternOffset, pattern);
2639 cache->set(index + kArrayOffset, array);
2642 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2643 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2644 cache->set(index2 + kStringOffset, string);
2645 cache->set(index2 + kPatternOffset, pattern);
2646 cache->set(index2 + kArrayOffset, array);
2648 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2649 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2650 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2651 cache->set(index + kStringOffset, string);
2652 cache->set(index + kPatternOffset, pattern);
2653 cache->set(index + kArrayOffset, array);
2656 if (array->length() < 100) { // Limit how many new symbols we want to make.
2657 for (int i = 0; i < array->length(); i++) {
2658 String* str = String::cast(array->get(i));
2660 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2661 if (maybe_symbol->ToObject(&symbol)) {
2662 array->set(i, symbol);
2666 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2670 void StringSplitCache::Clear(FixedArray* cache) {
2671 for (int i = 0; i < kStringSplitCacheSize; i++) {
2672 cache->set(i, Smi::FromInt(0));
2677 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2678 MaybeObject* maybe_obj =
2679 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2684 int Heap::FullSizeNumberStringCacheLength() {
2685 // Compute the size of the number string cache based on the max newspace size.
2686 // The number string cache has a minimum size based on twice the initial cache
2687 // size to ensure that it is bigger after being made 'full size'.
2688 int number_string_cache_size = max_semispace_size_ / 512;
2689 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2690 Min(0x4000, number_string_cache_size));
2691 // There is a string and a number per entry so the length is twice the number
2693 return number_string_cache_size * 2;
2697 void Heap::AllocateFullSizeNumberStringCache() {
2698 // The idea is to have a small number string cache in the snapshot to keep
2699 // boot-time memory usage down. If we expand the number string cache already
2700 // while creating the snapshot then that didn't work out.
2701 ASSERT(!Serializer::enabled());
2702 MaybeObject* maybe_obj =
2703 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2705 if (maybe_obj->ToObject(&new_cache)) {
2706 // We don't bother to repopulate the cache with entries from the old cache.
2707 // It will be repopulated soon enough with new strings.
2708 set_number_string_cache(FixedArray::cast(new_cache));
2710 // If allocation fails then we just return without doing anything. It is only
2711 // a cache, so best effort is OK here.
2715 void Heap::FlushNumberStringCache() {
2716 // Flush the number to string cache.
2717 int len = number_string_cache()->length();
2718 for (int i = 0; i < len; i++) {
2719 number_string_cache()->set_undefined(this, i);
2724 static inline int double_get_hash(double d) {
2725 DoubleRepresentation rep(d);
2726 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2730 static inline int smi_get_hash(Smi* smi) {
2731 return smi->value();
2735 Object* Heap::GetNumberStringCache(Object* number) {
2737 int mask = (number_string_cache()->length() >> 1) - 1;
2738 if (number->IsSmi()) {
2739 hash = smi_get_hash(Smi::cast(number)) & mask;
2741 hash = double_get_hash(number->Number()) & mask;
2743 Object* key = number_string_cache()->get(hash * 2);
2744 if (key == number) {
2745 return String::cast(number_string_cache()->get(hash * 2 + 1));
2746 } else if (key->IsHeapNumber() &&
2747 number->IsHeapNumber() &&
2748 key->Number() == number->Number()) {
2749 return String::cast(number_string_cache()->get(hash * 2 + 1));
2751 return undefined_value();
2755 void Heap::SetNumberStringCache(Object* number, String* string) {
2757 int mask = (number_string_cache()->length() >> 1) - 1;
2758 if (number->IsSmi()) {
2759 hash = smi_get_hash(Smi::cast(number)) & mask;
2761 hash = double_get_hash(number->Number()) & mask;
2763 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2764 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2765 // The first time we have a hash collision, we move to the full sized
2766 // number string cache.
2767 AllocateFullSizeNumberStringCache();
2770 number_string_cache()->set(hash * 2, number);
2771 number_string_cache()->set(hash * 2 + 1, string);
2775 MaybeObject* Heap::NumberToString(Object* number,
2776 bool check_number_string_cache) {
2777 isolate_->counters()->number_to_string_runtime()->Increment();
2778 if (check_number_string_cache) {
2779 Object* cached = GetNumberStringCache(number);
2780 if (cached != undefined_value()) {
2786 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2788 if (number->IsSmi()) {
2789 int num = Smi::cast(number)->value();
2790 str = IntToCString(num, buffer);
2792 double num = HeapNumber::cast(number)->value();
2793 str = DoubleToCString(num, buffer);
2797 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2798 if (maybe_js_string->ToObject(&js_string)) {
2799 SetNumberStringCache(number, String::cast(js_string));
2801 return maybe_js_string;
2805 MaybeObject* Heap::Uint32ToString(uint32_t value,
2806 bool check_number_string_cache) {
2808 MaybeObject* maybe = NumberFromUint32(value);
2809 if (!maybe->To<Object>(&number)) return maybe;
2810 return NumberToString(number, check_number_string_cache);
2814 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2815 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2819 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2820 ExternalArrayType array_type) {
2821 switch (array_type) {
2822 case kExternalByteArray:
2823 return kExternalByteArrayMapRootIndex;
2824 case kExternalUnsignedByteArray:
2825 return kExternalUnsignedByteArrayMapRootIndex;
2826 case kExternalShortArray:
2827 return kExternalShortArrayMapRootIndex;
2828 case kExternalUnsignedShortArray:
2829 return kExternalUnsignedShortArrayMapRootIndex;
2830 case kExternalIntArray:
2831 return kExternalIntArrayMapRootIndex;
2832 case kExternalUnsignedIntArray:
2833 return kExternalUnsignedIntArrayMapRootIndex;
2834 case kExternalFloatArray:
2835 return kExternalFloatArrayMapRootIndex;
2836 case kExternalDoubleArray:
2837 return kExternalDoubleArrayMapRootIndex;
2838 case kExternalPixelArray:
2839 return kExternalPixelArrayMapRootIndex;
2842 return kUndefinedValueRootIndex;
2847 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2848 // We need to distinguish the minus zero value and this cannot be
2849 // done after conversion to int. Doing this by comparing bit
2850 // patterns is faster than using fpclassify() et al.
2851 static const DoubleRepresentation minus_zero(-0.0);
2853 DoubleRepresentation rep(value);
2854 if (rep.bits == minus_zero.bits) {
2855 return AllocateHeapNumber(-0.0, pretenure);
2858 int int_value = FastD2I(value);
2859 if (value == int_value && Smi::IsValid(int_value)) {
2860 return Smi::FromInt(int_value);
2863 // Materialize the value in the heap.
2864 return AllocateHeapNumber(value, pretenure);
2868 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2869 // Statically ensure that it is safe to allocate foreigns in paged spaces.
2870 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
2871 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2873 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2874 if (!maybe_result->To(&result)) return maybe_result;
2875 result->set_foreign_address(address);
2880 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
2881 SharedFunctionInfo* share;
2882 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2883 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
2885 // Set pointer fields.
2886 share->set_name(name);
2887 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
2888 share->set_code(illegal);
2889 share->set_scope_info(ScopeInfo::Empty());
2890 Code* construct_stub =
2891 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2892 share->set_construct_stub(construct_stub);
2893 share->set_instance_class_name(Object_symbol());
2894 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
2895 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
2896 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
2897 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
2898 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
2899 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
2900 share->set_deopt_counter(FLAG_deopt_every_n_times);
2901 share->set_profiler_ticks(0);
2902 share->set_ast_node_count(0);
2904 // Set integer fields (smi or int, depending on the architecture).
2905 share->set_length(0);
2906 share->set_formal_parameter_count(0);
2907 share->set_expected_nof_properties(0);
2908 share->set_num_literals(0);
2909 share->set_start_position_and_type(0);
2910 share->set_end_position(0);
2911 share->set_function_token_position(0);
2912 // All compiler hints default to false or 0.
2913 share->set_compiler_hints(0);
2914 share->set_this_property_assignments_count(0);
2915 share->set_opt_count(0);
2921 MaybeObject* Heap::AllocateJSMessageObject(String* type,
2926 Object* stack_trace,
2927 Object* stack_frames) {
2929 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2930 if (!maybe_result->ToObject(&result)) return maybe_result;
2932 JSMessageObject* message = JSMessageObject::cast(result);
2933 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2934 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2935 message->set_type(type);
2936 message->set_arguments(arguments);
2937 message->set_start_position(start_position);
2938 message->set_end_position(end_position);
2939 message->set_script(script);
2940 message->set_stack_trace(stack_trace);
2941 message->set_stack_frames(stack_frames);
2947 // Returns true for a character in a range. Both limits are inclusive.
2948 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2949 // This makes uses of the the unsigned wraparound.
2950 return character - from <= to - from;
2954 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
2959 // Numeric strings have a different hash algorithm not known by
2960 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2961 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
2962 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
2964 // Now we know the length is 2, we might as well make use of that fact
2965 // when building the new string.
2966 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2967 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
2969 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
2970 if (!maybe_result->ToObject(&result)) return maybe_result;
2972 char* dest = SeqAsciiString::cast(result)->GetChars();
2978 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
2979 if (!maybe_result->ToObject(&result)) return maybe_result;
2981 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2989 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
2990 int first_length = first->length();
2991 if (first_length == 0) {
2995 int second_length = second->length();
2996 if (second_length == 0) {
3000 int length = first_length + second_length;
3002 // Optimization for 2-byte strings often used as keys in a decompression
3003 // dictionary. Check whether we already have the string in the symbol
3004 // table to prevent creation of many unneccesary strings.
3006 unsigned c1 = first->Get(0);
3007 unsigned c2 = second->Get(0);
3008 return MakeOrFindTwoCharacterString(this, c1, c2);
3011 bool first_is_ascii = first->IsAsciiRepresentation();
3012 bool second_is_ascii = second->IsAsciiRepresentation();
3013 bool is_ascii = first_is_ascii && second_is_ascii;
3015 // Make sure that an out of memory exception is thrown if the length
3016 // of the new cons string is too large.
3017 if (length > String::kMaxLength || length < 0) {
3018 isolate()->context()->mark_out_of_memory();
3019 return Failure::OutOfMemoryException();
3022 bool is_ascii_data_in_two_byte_string = false;
3024 // At least one of the strings uses two-byte representation so we
3025 // can't use the fast case code for short ASCII strings below, but
3026 // we can try to save memory if all chars actually fit in ASCII.
3027 is_ascii_data_in_two_byte_string =
3028 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3029 if (is_ascii_data_in_two_byte_string) {
3030 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3034 // If the resulting string is small make a flat string.
3035 if (length < ConsString::kMinLength) {
3036 // Note that neither of the two inputs can be a slice because:
3037 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3038 ASSERT(first->IsFlat());
3039 ASSERT(second->IsFlat());
3042 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3043 if (!maybe_result->ToObject(&result)) return maybe_result;
3045 // Copy the characters into the new object.
3046 char* dest = SeqAsciiString::cast(result)->GetChars();
3049 if (first->IsExternalString()) {
3050 src = ExternalAsciiString::cast(first)->GetChars();
3052 src = SeqAsciiString::cast(first)->GetChars();
3054 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3055 // Copy second part.
3056 if (second->IsExternalString()) {
3057 src = ExternalAsciiString::cast(second)->GetChars();
3059 src = SeqAsciiString::cast(second)->GetChars();
3061 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3064 if (is_ascii_data_in_two_byte_string) {
3066 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3067 if (!maybe_result->ToObject(&result)) return maybe_result;
3069 // Copy the characters into the new object.
3070 char* dest = SeqAsciiString::cast(result)->GetChars();
3071 String::WriteToFlat(first, dest, 0, first_length);
3072 String::WriteToFlat(second, dest + first_length, 0, second_length);
3073 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3078 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3079 if (!maybe_result->ToObject(&result)) return maybe_result;
3081 // Copy the characters into the new object.
3082 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3083 String::WriteToFlat(first, dest, 0, first_length);
3084 String::WriteToFlat(second, dest + first_length, 0, second_length);
3089 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3090 cons_ascii_string_map() : cons_string_map();
3093 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3094 if (!maybe_result->ToObject(&result)) return maybe_result;
3097 AssertNoAllocation no_gc;
3098 ConsString* cons_string = ConsString::cast(result);
3099 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3100 cons_string->set_length(length);
3101 cons_string->set_hash_field(String::kEmptyHashField);
3102 cons_string->set_first(first, mode);
3103 cons_string->set_second(second, mode);
3108 MaybeObject* Heap::AllocateSubString(String* buffer,
3111 PretenureFlag pretenure) {
3112 int length = end - start;
3114 return empty_string();
3115 } else if (length == 1) {
3116 return LookupSingleCharacterStringFromCode(buffer->Get(start));
3117 } else if (length == 2) {
3118 // Optimization for 2-byte strings often used as keys in a decompression
3119 // dictionary. Check whether we already have the string in the symbol
3120 // table to prevent creation of many unneccesary strings.
3121 unsigned c1 = buffer->Get(start);
3122 unsigned c2 = buffer->Get(start + 1);
3123 return MakeOrFindTwoCharacterString(this, c1, c2);
3126 // Make an attempt to flatten the buffer to reduce access time.
3127 buffer = buffer->TryFlattenGetString();
3129 if (!FLAG_string_slices ||
3130 !buffer->IsFlat() ||
3131 length < SlicedString::kMinLength ||
3132 pretenure == TENURED) {
3134 // WriteToFlat takes care of the case when an indirect string has a
3135 // different encoding from its underlying string. These encodings may
3136 // differ because of externalization.
3137 bool is_ascii = buffer->IsAsciiRepresentation();
3138 { MaybeObject* maybe_result = is_ascii
3139 ? AllocateRawAsciiString(length, pretenure)
3140 : AllocateRawTwoByteString(length, pretenure);
3141 if (!maybe_result->ToObject(&result)) return maybe_result;
3143 String* string_result = String::cast(result);
3144 // Copy the characters into the new object.
3146 ASSERT(string_result->IsAsciiRepresentation());
3147 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3148 String::WriteToFlat(buffer, dest, start, end);
3150 ASSERT(string_result->IsTwoByteRepresentation());
3151 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3152 String::WriteToFlat(buffer, dest, start, end);
3157 ASSERT(buffer->IsFlat());
3159 if (FLAG_verify_heap) {
3160 buffer->StringVerify();
3165 // When slicing an indirect string we use its encoding for a newly created
3166 // slice and don't check the encoding of the underlying string. This is safe
3167 // even if the encodings are different because of externalization. If an
3168 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3169 // codes of the underlying string must still fit into ASCII (because
3170 // externalization must not change char codes).
3171 { Map* map = buffer->IsAsciiRepresentation()
3172 ? sliced_ascii_string_map()
3173 : sliced_string_map();
3174 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3175 if (!maybe_result->ToObject(&result)) return maybe_result;
3178 AssertNoAllocation no_gc;
3179 SlicedString* sliced_string = SlicedString::cast(result);
3180 sliced_string->set_length(length);
3181 sliced_string->set_hash_field(String::kEmptyHashField);
3182 if (buffer->IsConsString()) {
3183 ConsString* cons = ConsString::cast(buffer);
3184 ASSERT(cons->second()->length() == 0);
3185 sliced_string->set_parent(cons->first());
3186 sliced_string->set_offset(start);
3187 } else if (buffer->IsSlicedString()) {
3188 // Prevent nesting sliced strings.
3189 SlicedString* parent_slice = SlicedString::cast(buffer);
3190 sliced_string->set_parent(parent_slice->parent());
3191 sliced_string->set_offset(start + parent_slice->offset());
3193 sliced_string->set_parent(buffer);
3194 sliced_string->set_offset(start);
3196 ASSERT(sliced_string->parent()->IsSeqString() ||
3197 sliced_string->parent()->IsExternalString());
3202 MaybeObject* Heap::AllocateExternalStringFromAscii(
3203 const ExternalAsciiString::Resource* resource) {
3204 size_t length = resource->length();
3205 if (length > static_cast<size_t>(String::kMaxLength)) {
3206 isolate()->context()->mark_out_of_memory();
3207 return Failure::OutOfMemoryException();
3210 Map* map = external_ascii_string_map();
3212 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3213 if (!maybe_result->ToObject(&result)) return maybe_result;
3216 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3217 external_string->set_length(static_cast<int>(length));
3218 external_string->set_hash_field(String::kEmptyHashField);
3219 external_string->set_resource(resource);
3225 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3226 const ExternalTwoByteString::Resource* resource) {
3227 size_t length = resource->length();
3228 if (length > static_cast<size_t>(String::kMaxLength)) {
3229 isolate()->context()->mark_out_of_memory();
3230 return Failure::OutOfMemoryException();
3233 // For small strings we check whether the resource contains only
3234 // ASCII characters. If yes, we use a different string map.
3235 static const size_t kAsciiCheckLengthLimit = 32;
3236 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3237 String::IsAscii(resource->data(), static_cast<int>(length));
3238 Map* map = is_ascii ?
3239 external_string_with_ascii_data_map() : external_string_map();
3241 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3242 if (!maybe_result->ToObject(&result)) return maybe_result;
3245 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3246 external_string->set_length(static_cast<int>(length));
3247 external_string->set_hash_field(String::kEmptyHashField);
3248 external_string->set_resource(resource);
3254 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3255 if (code <= String::kMaxAsciiCharCode) {
3256 Object* value = single_character_string_cache()->get(code);
3257 if (value != undefined_value()) return value;
3260 buffer[0] = static_cast<char>(code);
3262 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3264 if (!maybe_result->ToObject(&result)) return maybe_result;
3265 single_character_string_cache()->set(code, result);
3270 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3271 if (!maybe_result->ToObject(&result)) return maybe_result;
3273 String* answer = String::cast(result);
3274 answer->Set(0, code);
3279 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3280 if (length < 0 || length > ByteArray::kMaxLength) {
3281 return Failure::OutOfMemoryException();
3283 if (pretenure == NOT_TENURED) {
3284 return AllocateByteArray(length);
3286 int size = ByteArray::SizeFor(length);
3288 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3289 ? old_data_space_->AllocateRaw(size)
3290 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3291 if (!maybe_result->ToObject(&result)) return maybe_result;
3294 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3296 reinterpret_cast<ByteArray*>(result)->set_length(length);
3301 MaybeObject* Heap::AllocateByteArray(int length) {
3302 if (length < 0 || length > ByteArray::kMaxLength) {
3303 return Failure::OutOfMemoryException();
3305 int size = ByteArray::SizeFor(length);
3306 AllocationSpace space =
3307 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3309 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3310 if (!maybe_result->ToObject(&result)) return maybe_result;
3313 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3315 reinterpret_cast<ByteArray*>(result)->set_length(length);
3320 void Heap::CreateFillerObjectAt(Address addr, int size) {
3321 if (size == 0) return;
3322 HeapObject* filler = HeapObject::FromAddress(addr);
3323 if (size == kPointerSize) {
3324 filler->set_map_no_write_barrier(one_pointer_filler_map());
3325 } else if (size == 2 * kPointerSize) {
3326 filler->set_map_no_write_barrier(two_pointer_filler_map());
3328 filler->set_map_no_write_barrier(free_space_map());
3329 FreeSpace::cast(filler)->set_size(size);
3334 MaybeObject* Heap::AllocateExternalArray(int length,
3335 ExternalArrayType array_type,
3336 void* external_pointer,
3337 PretenureFlag pretenure) {
3338 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3340 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3343 if (!maybe_result->ToObject(&result)) return maybe_result;
3346 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3347 MapForExternalArrayType(array_type));
3348 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3349 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3356 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3358 Handle<Object> self_reference,
3360 // Allocate ByteArray before the Code object, so that we do not risk
3361 // leaving uninitialized Code object (and breaking the heap).
3362 ByteArray* reloc_info;
3363 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3364 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3367 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3368 int obj_size = Code::SizeFor(body_size);
3369 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3370 MaybeObject* maybe_result;
3371 // Large code objects and code objects which should stay at a fixed address
3372 // are allocated in large object space.
3373 if (obj_size > code_space()->AreaSize() || immovable) {
3374 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3376 maybe_result = code_space_->AllocateRaw(obj_size);
3380 if (!maybe_result->ToObject(&result)) return maybe_result;
3382 // Initialize the object
3383 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3384 Code* code = Code::cast(result);
3385 ASSERT(!isolate_->code_range()->exists() ||
3386 isolate_->code_range()->contains(code->address()));
3387 code->set_instruction_size(desc.instr_size);
3388 code->set_relocation_info(reloc_info);
3389 code->set_flags(flags);
3390 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3391 code->set_check_type(RECEIVER_MAP_CHECK);
3393 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3394 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3395 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3396 code->set_gc_metadata(Smi::FromInt(0));
3397 code->set_ic_age(global_ic_age_);
3398 // Allow self references to created code object by patching the handle to
3399 // point to the newly allocated Code object.
3400 if (!self_reference.is_null()) {
3401 *(self_reference.location()) = code;
3403 // Migrate generated code.
3404 // The generated code can contain Object** values (typically from handles)
3405 // that are dereferenced during the copy to point directly to the actual heap
3406 // objects. These pointers can include references to the code object itself,
3407 // through the self_reference parameter.
3408 code->CopyFrom(desc);
3411 if (FLAG_verify_heap) {
3419 MaybeObject* Heap::CopyCode(Code* code) {
3420 // Allocate an object the same size as the code object.
3421 int obj_size = code->Size();
3422 MaybeObject* maybe_result;
3423 if (obj_size > code_space()->AreaSize()) {
3424 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3426 maybe_result = code_space_->AllocateRaw(obj_size);
3430 if (!maybe_result->ToObject(&result)) return maybe_result;
3432 // Copy code object.
3433 Address old_addr = code->address();
3434 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3435 CopyBlock(new_addr, old_addr, obj_size);
3436 // Relocate the copy.
3437 Code* new_code = Code::cast(result);
3438 ASSERT(!isolate_->code_range()->exists() ||
3439 isolate_->code_range()->contains(code->address()));
3440 new_code->Relocate(new_addr - old_addr);
3445 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3446 // Allocate ByteArray before the Code object, so that we do not risk
3447 // leaving uninitialized Code object (and breaking the heap).
3448 Object* reloc_info_array;
3449 { MaybeObject* maybe_reloc_info_array =
3450 AllocateByteArray(reloc_info.length(), TENURED);
3451 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3452 return maybe_reloc_info_array;
3456 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3458 int new_obj_size = Code::SizeFor(new_body_size);
3460 Address old_addr = code->address();
3462 size_t relocation_offset =
3463 static_cast<size_t>(code->instruction_end() - old_addr);
3465 MaybeObject* maybe_result;
3466 if (new_obj_size > code_space()->AreaSize()) {
3467 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3469 maybe_result = code_space_->AllocateRaw(new_obj_size);
3473 if (!maybe_result->ToObject(&result)) return maybe_result;
3475 // Copy code object.
3476 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3478 // Copy header and instructions.
3479 memcpy(new_addr, old_addr, relocation_offset);
3481 Code* new_code = Code::cast(result);
3482 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3484 // Copy patched rinfo.
3485 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3487 // Relocate the copy.
3488 ASSERT(!isolate_->code_range()->exists() ||
3489 isolate_->code_range()->contains(code->address()));
3490 new_code->Relocate(new_addr - old_addr);
3493 if (FLAG_verify_heap) {
3501 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3502 ASSERT(gc_state_ == NOT_IN_GC);
3503 ASSERT(map->instance_type() != MAP_TYPE);
3504 // If allocation failures are disallowed, we may allocate in a different
3505 // space when new space is full and the object is not a large object.
3506 AllocationSpace retry_space =
3507 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3509 { MaybeObject* maybe_result =
3510 AllocateRaw(map->instance_size(), space, retry_space);
3511 if (!maybe_result->ToObject(&result)) return maybe_result;
3513 // No need for write barrier since object is white and map is in old space.
3514 HeapObject::cast(result)->set_map_no_write_barrier(map);
3519 void Heap::InitializeFunction(JSFunction* function,
3520 SharedFunctionInfo* shared,
3521 Object* prototype) {
3522 ASSERT(!prototype->IsMap());
3523 function->initialize_properties();
3524 function->initialize_elements();
3525 function->set_shared(shared);
3526 function->set_code(shared->code());
3527 function->set_prototype_or_initial_map(prototype);
3528 function->set_context(undefined_value());
3529 function->set_literals_or_bindings(empty_fixed_array());
3530 function->set_next_function_link(undefined_value());
3534 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3535 // Allocate the prototype. Make sure to use the object function
3536 // from the function's context, since the function can be from a
3537 // different context.
3538 JSFunction* object_function =
3539 function->context()->global_context()->object_function();
3541 // Each function prototype gets a copy of the object function map.
3542 // This avoid unwanted sharing of maps between prototypes of different
3545 ASSERT(object_function->has_initial_map());
3546 { MaybeObject* maybe_map =
3547 object_function->initial_map()->CopyDropTransitions();
3548 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3551 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3552 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3554 // When creating the prototype for the function we must set its
3555 // constructor to the function.
3557 { MaybeObject* maybe_result =
3558 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3559 constructor_symbol(), function, DONT_ENUM);
3560 if (!maybe_result->ToObject(&result)) return maybe_result;
3566 MaybeObject* Heap::AllocateFunction(Map* function_map,
3567 SharedFunctionInfo* shared,
3569 PretenureFlag pretenure) {
3570 AllocationSpace space =
3571 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3573 { MaybeObject* maybe_result = Allocate(function_map, space);
3574 if (!maybe_result->ToObject(&result)) return maybe_result;
3576 InitializeFunction(JSFunction::cast(result), shared, prototype);
3581 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3582 // To get fast allocation and map sharing for arguments objects we
3583 // allocate them based on an arguments boilerplate.
3585 JSObject* boilerplate;
3586 int arguments_object_size;
3587 bool strict_mode_callee = callee->IsJSFunction() &&
3588 !JSFunction::cast(callee)->shared()->is_classic_mode();
3589 if (strict_mode_callee) {
3591 isolate()->context()->global_context()->
3592 strict_mode_arguments_boilerplate();
3593 arguments_object_size = kArgumentsObjectSizeStrict;
3596 isolate()->context()->global_context()->arguments_boilerplate();
3597 arguments_object_size = kArgumentsObjectSize;
3600 // This calls Copy directly rather than using Heap::AllocateRaw so we
3601 // duplicate the check here.
3602 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3604 // Check that the size of the boilerplate matches our
3605 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3606 // on the size being a known constant.
3607 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3609 // Do the allocation.
3611 { MaybeObject* maybe_result =
3612 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3613 if (!maybe_result->ToObject(&result)) return maybe_result;
3616 // Copy the content. The arguments boilerplate doesn't have any
3617 // fields that point to new space so it's safe to skip the write
3619 CopyBlock(HeapObject::cast(result)->address(),
3620 boilerplate->address(),
3621 JSObject::kHeaderSize);
3623 // Set the length property.
3624 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3625 Smi::FromInt(length),
3626 SKIP_WRITE_BARRIER);
3627 // Set the callee property for non-strict mode arguments object only.
3628 if (!strict_mode_callee) {
3629 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3633 // Check the state of the object
3634 ASSERT(JSObject::cast(result)->HasFastProperties());
3635 ASSERT(JSObject::cast(result)->HasFastElements());
3641 static bool HasDuplicates(DescriptorArray* descriptors) {
3642 int count = descriptors->number_of_descriptors();
3644 String* prev_key = descriptors->GetKey(0);
3645 for (int i = 1; i != count; i++) {
3646 String* current_key = descriptors->GetKey(i);
3647 if (prev_key == current_key) return true;
3648 prev_key = current_key;
3655 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3656 ASSERT(!fun->has_initial_map());
3658 // First create a new map with the size and number of in-object properties
3659 // suggested by the function.
3660 int instance_size = fun->shared()->CalculateInstanceSize();
3661 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3663 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3664 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3667 // Fetch or allocate prototype.
3669 if (fun->has_instance_prototype()) {
3670 prototype = fun->instance_prototype();
3672 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3673 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3676 Map* map = Map::cast(map_obj);
3677 map->set_inobject_properties(in_object_properties);
3678 map->set_unused_property_fields(in_object_properties);
3679 map->set_prototype(prototype);
3680 ASSERT(map->has_fast_elements());
3682 // If the function has only simple this property assignments add
3683 // field descriptors for these to the initial map as the object
3684 // cannot be constructed without having these properties. Guard by
3685 // the inline_new flag so we only change the map if we generate a
3686 // specialized construct stub.
3687 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3688 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3689 int count = fun->shared()->this_property_assignments_count();
3690 if (count > in_object_properties) {
3691 // Inline constructor can only handle inobject properties.
3692 fun->shared()->ForbidInlineConstructor();
3694 DescriptorArray* descriptors;
3695 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
3696 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
3697 return maybe_descriptors_obj;
3700 DescriptorArray::WhitenessWitness witness(descriptors);
3701 for (int i = 0; i < count; i++) {
3702 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3703 ASSERT(name->IsSymbol());
3704 FieldDescriptor field(name, i, NONE);
3705 field.SetEnumerationIndex(i);
3706 descriptors->Set(i, &field, witness);
3708 descriptors->SetNextEnumerationIndex(count);
3709 descriptors->SortUnchecked(witness);
3711 // The descriptors may contain duplicates because the compiler does not
3712 // guarantee the uniqueness of property names (it would have required
3713 // quadratic time). Once the descriptors are sorted we can check for
3714 // duplicates in linear time.
3715 if (HasDuplicates(descriptors)) {
3716 fun->shared()->ForbidInlineConstructor();
3718 map->set_instance_descriptors(descriptors);
3719 map->set_pre_allocated_property_fields(count);
3720 map->set_unused_property_fields(in_object_properties - count);
3725 fun->shared()->StartInobjectSlackTracking(map);
3731 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3732 FixedArray* properties,
3734 obj->set_properties(properties);
3735 obj->initialize_elements();
3736 // TODO(1240798): Initialize the object's body using valid initial values
3737 // according to the object's initial map. For example, if the map's
3738 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3739 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3740 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3741 // verification code has to cope with (temporarily) invalid objects. See
3742 // for example, JSArray::JSArrayVerify).
3744 // We cannot always fill with one_pointer_filler_map because objects
3745 // created from API functions expect their internal fields to be initialized
3746 // with undefined_value.
3747 // Pre-allocated fields need to be initialized with undefined_value as well
3748 // so that object accesses before the constructor completes (e.g. in the
3749 // debugger) will not cause a crash.
3750 if (map->constructor()->IsJSFunction() &&
3751 JSFunction::cast(map->constructor())->shared()->
3752 IsInobjectSlackTrackingInProgress()) {
3753 // We might want to shrink the object later.
3754 ASSERT(obj->GetInternalFieldCount() == 0);
3755 filler = Heap::one_pointer_filler_map();
3757 filler = Heap::undefined_value();
3759 obj->InitializeBody(map, Heap::undefined_value(), filler);
3763 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3764 // JSFunctions should be allocated using AllocateFunction to be
3765 // properly initialized.
3766 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3768 // Both types of global objects should be allocated using
3769 // AllocateGlobalObject to be properly initialized.
3770 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3771 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3773 // Allocate the backing storage for the properties.
3775 map->pre_allocated_property_fields() +
3776 map->unused_property_fields() -
3777 map->inobject_properties();
3778 ASSERT(prop_size >= 0);
3780 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3781 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3784 // Allocate the JSObject.
3785 AllocationSpace space =
3786 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3787 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
3789 { MaybeObject* maybe_obj = Allocate(map, space);
3790 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3793 // Initialize the JSObject.
3794 InitializeJSObjectFromMap(JSObject::cast(obj),
3795 FixedArray::cast(properties),
3797 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3798 JSObject::cast(obj)->HasFastElements());
3803 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3804 PretenureFlag pretenure) {
3805 // Allocate the initial map if absent.
3806 if (!constructor->has_initial_map()) {
3807 Object* initial_map;
3808 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3809 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3811 constructor->set_initial_map(Map::cast(initial_map));
3812 Map::cast(initial_map)->set_constructor(constructor);
3814 // Allocate the object based on the constructors initial map.
3815 MaybeObject* result = AllocateJSObjectFromMap(
3816 constructor->initial_map(), pretenure);
3818 // Make sure result is NOT a global object if valid.
3819 Object* non_failure;
3820 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3826 MaybeObject* Heap::AllocateJSArrayAndStorage(
3827 ElementsKind elements_kind,
3830 ArrayStorageAllocationMode mode,
3831 PretenureFlag pretenure) {
3832 ASSERT(capacity >= length);
3833 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3835 if (!maybe_array->To(&array)) return maybe_array;
3837 if (capacity == 0) {
3838 array->set_length(Smi::FromInt(0));
3839 array->set_elements(empty_fixed_array());
3843 FixedArrayBase* elms;
3844 MaybeObject* maybe_elms = NULL;
3845 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3846 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3847 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3849 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3850 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3853 ASSERT(elements_kind == FAST_ELEMENTS ||
3854 elements_kind == FAST_SMI_ONLY_ELEMENTS);
3855 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3856 maybe_elms = AllocateUninitializedFixedArray(capacity);
3858 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3859 maybe_elms = AllocateFixedArrayWithHoles(capacity);
3862 if (!maybe_elms->To(&elms)) return maybe_elms;
3864 array->set_elements(elms);
3865 array->set_length(Smi::FromInt(length));
3870 MaybeObject* Heap::AllocateJSArrayWithElements(
3871 FixedArrayBase* elements,
3872 ElementsKind elements_kind,
3873 PretenureFlag pretenure) {
3874 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3876 if (!maybe_array->To(&array)) return maybe_array;
3878 array->set_elements(elements);
3879 array->set_length(Smi::FromInt(elements->length()));
3884 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3886 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3887 // maps. Will probably depend on the identity of the handler object, too.
3889 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3890 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3891 map->set_prototype(prototype);
3893 // Allocate the proxy object.
3895 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3896 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3897 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3898 result->set_handler(handler);
3899 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
3904 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3906 Object* construct_trap,
3907 Object* prototype) {
3909 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3910 // maps. Will probably depend on the identity of the handler object, too.
3912 MaybeObject* maybe_map_obj =
3913 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3914 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3915 map->set_prototype(prototype);
3917 // Allocate the proxy object.
3918 JSFunctionProxy* result;
3919 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3920 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3921 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3922 result->set_handler(handler);
3923 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
3924 result->set_call_trap(call_trap);
3925 result->set_construct_trap(construct_trap);
3930 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
3931 ASSERT(constructor->has_initial_map());
3932 Map* map = constructor->initial_map();
3934 // Make sure no field properties are described in the initial map.
3935 // This guarantees us that normalizing the properties does not
3936 // require us to change property values to JSGlobalPropertyCells.
3937 ASSERT(map->NextFreePropertyIndex() == 0);
3939 // Make sure we don't have a ton of pre-allocated slots in the
3940 // global objects. They will be unused once we normalize the object.
3941 ASSERT(map->unused_property_fields() == 0);
3942 ASSERT(map->inobject_properties() == 0);
3944 // Initial size of the backing store to avoid resize of the storage during
3945 // bootstrapping. The size differs between the JS global object ad the
3947 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3949 // Allocate a dictionary object for backing storage.
3951 { MaybeObject* maybe_obj =
3952 StringDictionary::Allocate(
3953 map->NumberOfDescribedProperties() * 2 + initial_size);
3954 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3956 StringDictionary* dictionary = StringDictionary::cast(obj);
3958 // The global object might be created from an object template with accessors.
3959 // Fill these accessors into the dictionary.
3960 DescriptorArray* descs = map->instance_descriptors();
3961 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3962 PropertyDetails details(descs->GetDetails(i));
3963 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3965 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3966 Object* value = descs->GetCallbacksObject(i);
3967 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
3968 if (!maybe_value->ToObject(&value)) return maybe_value;
3972 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3973 if (!maybe_result->ToObject(&result)) return maybe_result;
3975 dictionary = StringDictionary::cast(result);
3978 // Allocate the global object and initialize it with the backing store.
3979 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3980 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3982 JSObject* global = JSObject::cast(obj);
3983 InitializeJSObjectFromMap(global, dictionary, map);
3985 // Create a new map for the global object.
3986 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3987 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3989 Map* new_map = Map::cast(obj);
3991 // Set up the global object as a normalized object.
3992 global->set_map(new_map);
3993 global->map()->clear_instance_descriptors();
3994 global->set_properties(dictionary);
3996 // Make sure result is a global object with properties in dictionary.
3997 ASSERT(global->IsGlobalObject());
3998 ASSERT(!global->HasFastProperties());
4003 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4004 // Never used to copy functions. If functions need to be copied we
4005 // have to be careful to clear the literals array.
4006 SLOW_ASSERT(!source->IsJSFunction());
4009 Map* map = source->map();
4010 int object_size = map->instance_size();
4013 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4015 // If we're forced to always allocate, we use the general allocation
4016 // functions which may leave us with an object in old space.
4017 if (always_allocate()) {
4018 { MaybeObject* maybe_clone =
4019 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4020 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4022 Address clone_address = HeapObject::cast(clone)->address();
4023 CopyBlock(clone_address,
4026 // Update write barrier for all fields that lie beyond the header.
4027 RecordWrites(clone_address,
4028 JSObject::kHeaderSize,
4029 (object_size - JSObject::kHeaderSize) / kPointerSize);
4031 wb_mode = SKIP_WRITE_BARRIER;
4032 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4033 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4035 SLOW_ASSERT(InNewSpace(clone));
4036 // Since we know the clone is allocated in new space, we can copy
4037 // the contents without worrying about updating the write barrier.
4038 CopyBlock(HeapObject::cast(clone)->address(),
4044 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4045 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4046 FixedArray* properties = FixedArray::cast(source->properties());
4047 // Update elements if necessary.
4048 if (elements->length() > 0) {
4050 { MaybeObject* maybe_elem;
4051 if (elements->map() == fixed_cow_array_map()) {
4052 maybe_elem = FixedArray::cast(elements);
4053 } else if (source->HasFastDoubleElements()) {
4054 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4056 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4058 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4060 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4062 // Update properties if necessary.
4063 if (properties->length() > 0) {
4065 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4066 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4068 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4070 // Return the new clone.
4075 MaybeObject* Heap::ReinitializeJSReceiver(
4076 JSReceiver* object, InstanceType type, int size) {
4077 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4079 // Allocate fresh map.
4080 // TODO(rossberg): Once we optimize proxies, cache these maps.
4082 MaybeObject* maybe = AllocateMap(type, size);
4083 if (!maybe->To<Map>(&map)) return maybe;
4085 // Check that the receiver has at least the size of the fresh object.
4086 int size_difference = object->map()->instance_size() - map->instance_size();
4087 ASSERT(size_difference >= 0);
4089 map->set_prototype(object->map()->prototype());
4091 // Allocate the backing storage for the properties.
4092 int prop_size = map->unused_property_fields() - map->inobject_properties();
4094 maybe = AllocateFixedArray(prop_size, TENURED);
4095 if (!maybe->ToObject(&properties)) return maybe;
4097 // Functions require some allocation, which might fail here.
4098 SharedFunctionInfo* shared = NULL;
4099 if (type == JS_FUNCTION_TYPE) {
4101 maybe = LookupAsciiSymbol("<freezing call trap>");
4102 if (!maybe->To<String>(&name)) return maybe;
4103 maybe = AllocateSharedFunctionInfo(name);
4104 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4107 // Because of possible retries of this function after failure,
4108 // we must NOT fail after this point, where we have changed the type!
4110 // Reset the map for the object.
4111 object->set_map(map);
4112 JSObject* jsobj = JSObject::cast(object);
4114 // Reinitialize the object from the constructor map.
4115 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4117 // Functions require some minimal initialization.
4118 if (type == JS_FUNCTION_TYPE) {
4119 map->set_function_with_prototype(true);
4120 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4121 JSFunction::cast(object)->set_context(
4122 isolate()->context()->global_context());
4125 // Put in filler if the new object is smaller than the old.
4126 if (size_difference > 0) {
4127 CreateFillerObjectAt(
4128 object->address() + map->instance_size(), size_difference);
4135 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4136 JSGlobalProxy* object) {
4137 ASSERT(constructor->has_initial_map());
4138 Map* map = constructor->initial_map();
4140 // Check that the already allocated object has the same size and type as
4141 // objects allocated using the constructor.
4142 ASSERT(map->instance_size() == object->map()->instance_size());
4143 ASSERT(map->instance_type() == object->map()->instance_type());
4145 // Allocate the backing storage for the properties.
4146 int prop_size = map->unused_property_fields() - map->inobject_properties();
4148 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4149 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4152 // Reset the map for the object.
4153 object->set_map(constructor->initial_map());
4155 // Reinitialize the object from the constructor map.
4156 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4161 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4162 PretenureFlag pretenure) {
4163 if (string.length() == 1) {
4164 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4167 { MaybeObject* maybe_result =
4168 AllocateRawAsciiString(string.length(), pretenure);
4169 if (!maybe_result->ToObject(&result)) return maybe_result;
4172 // Copy the characters into the new object.
4173 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4174 for (int i = 0; i < string.length(); i++) {
4175 string_result->SeqAsciiStringSet(i, string[i]);
4181 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4182 PretenureFlag pretenure) {
4183 // Count the number of characters in the UTF-8 string and check if
4184 // it is an ASCII string.
4185 Access<UnicodeCache::Utf8Decoder>
4186 decoder(isolate_->unicode_cache()->utf8_decoder());
4187 decoder->Reset(string.start(), string.length());
4189 while (decoder->has_more()) {
4190 uint32_t r = decoder->GetNext();
4191 if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4199 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4200 if (!maybe_result->ToObject(&result)) return maybe_result;
4203 // Convert and copy the characters into the new object.
4204 String* string_result = String::cast(result);
4205 decoder->Reset(string.start(), string.length());
4208 uint32_t r = decoder->GetNext();
4209 if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4210 string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4211 string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4213 string_result->Set(i++, r);
4220 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4221 PretenureFlag pretenure) {
4222 // Check if the string is an ASCII string.
4223 MaybeObject* maybe_result;
4224 if (String::IsAscii(string.start(), string.length())) {
4225 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4226 } else { // It's not an ASCII string.
4227 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4230 if (!maybe_result->ToObject(&result)) return maybe_result;
4232 // Copy the characters into the new object, which may be either ASCII or
4234 String* string_result = String::cast(result);
4235 for (int i = 0; i < string.length(); i++) {
4236 string_result->Set(i, string[i]);
4242 Map* Heap::SymbolMapForString(String* string) {
4243 // If the string is in new space it cannot be used as a symbol.
4244 if (InNewSpace(string)) return NULL;
4246 // Find the corresponding symbol map for strings.
4247 switch (string->map()->instance_type()) {
4248 case STRING_TYPE: return symbol_map();
4249 case ASCII_STRING_TYPE: return ascii_symbol_map();
4250 case CONS_STRING_TYPE: return cons_symbol_map();
4251 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4252 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4253 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4254 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4255 return external_symbol_with_ascii_data_map();
4256 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4257 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4258 return short_external_ascii_symbol_map();
4259 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4260 return short_external_symbol_with_ascii_data_map();
4261 default: return NULL; // No match found.
4266 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4268 uint32_t hash_field) {
4270 // Ensure the chars matches the number of characters in the buffer.
4271 ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4272 // Determine whether the string is ASCII.
4273 bool is_ascii = true;
4274 while (buffer->has_more()) {
4275 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4282 // Compute map and object size.
4287 if (chars > SeqAsciiString::kMaxLength) {
4288 return Failure::OutOfMemoryException();
4290 map = ascii_symbol_map();
4291 size = SeqAsciiString::SizeFor(chars);
4293 if (chars > SeqTwoByteString::kMaxLength) {
4294 return Failure::OutOfMemoryException();
4297 size = SeqTwoByteString::SizeFor(chars);
4302 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4303 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4304 : old_data_space_->AllocateRaw(size);
4305 if (!maybe_result->ToObject(&result)) return maybe_result;
4308 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4309 // Set length and hash fields of the allocated string.
4310 String* answer = String::cast(result);
4311 answer->set_length(chars);
4312 answer->set_hash_field(hash_field);
4314 ASSERT_EQ(size, answer->Size());
4316 // Fill in the characters.
4319 uint32_t character = buffer->GetNext();
4320 if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4321 answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4322 answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4324 answer->Set(i++, character);
4331 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4332 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4333 return Failure::OutOfMemoryException();
4336 int size = SeqAsciiString::SizeFor(length);
4337 ASSERT(size <= SeqAsciiString::kMaxSize);
4339 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4340 AllocationSpace retry_space = OLD_DATA_SPACE;
4342 if (space == NEW_SPACE) {
4343 if (size > kMaxObjectSizeInNewSpace) {
4344 // Allocate in large object space, retry space will be ignored.
4346 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4347 // Allocate in new space, retry in large object space.
4348 retry_space = LO_SPACE;
4350 } else if (space == OLD_DATA_SPACE &&
4351 size > Page::kMaxNonCodeHeapObjectSize) {
4355 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4356 if (!maybe_result->ToObject(&result)) return maybe_result;
4359 // Partially initialize the object.
4360 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4361 String::cast(result)->set_length(length);
4362 String::cast(result)->set_hash_field(String::kEmptyHashField);
4363 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4368 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4369 PretenureFlag pretenure) {
4370 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4371 return Failure::OutOfMemoryException();
4373 int size = SeqTwoByteString::SizeFor(length);
4374 ASSERT(size <= SeqTwoByteString::kMaxSize);
4375 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4376 AllocationSpace retry_space = OLD_DATA_SPACE;
4378 if (space == NEW_SPACE) {
4379 if (size > kMaxObjectSizeInNewSpace) {
4380 // Allocate in large object space, retry space will be ignored.
4382 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4383 // Allocate in new space, retry in large object space.
4384 retry_space = LO_SPACE;
4386 } else if (space == OLD_DATA_SPACE &&
4387 size > Page::kMaxNonCodeHeapObjectSize) {
4391 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4392 if (!maybe_result->ToObject(&result)) return maybe_result;
4395 // Partially initialize the object.
4396 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4397 String::cast(result)->set_length(length);
4398 String::cast(result)->set_hash_field(String::kEmptyHashField);
4399 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4404 MaybeObject* Heap::AllocateJSArray(
4405 ElementsKind elements_kind,
4406 PretenureFlag pretenure) {
4407 Context* global_context = isolate()->context()->global_context();
4408 JSFunction* array_function = global_context->array_function();
4409 Map* map = array_function->initial_map();
4410 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4411 map = Map::cast(global_context->double_js_array_map());
4412 } else if (elements_kind == FAST_ELEMENTS || !FLAG_smi_only_arrays) {
4413 map = Map::cast(global_context->object_js_array_map());
4415 ASSERT(elements_kind == FAST_SMI_ONLY_ELEMENTS);
4416 ASSERT(map == global_context->smi_js_array_map());
4419 return AllocateJSObjectFromMap(map, pretenure);
4423 MaybeObject* Heap::AllocateEmptyFixedArray() {
4424 int size = FixedArray::SizeFor(0);
4426 { MaybeObject* maybe_result =
4427 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4428 if (!maybe_result->ToObject(&result)) return maybe_result;
4430 // Initialize the object.
4431 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4433 reinterpret_cast<FixedArray*>(result)->set_length(0);
4438 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4439 if (length < 0 || length > FixedArray::kMaxLength) {
4440 return Failure::OutOfMemoryException();
4443 // Use the general function if we're forced to always allocate.
4444 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4445 // Allocate the raw data for a fixed array.
4446 int size = FixedArray::SizeFor(length);
4447 return size <= kMaxObjectSizeInNewSpace
4448 ? new_space_.AllocateRaw(size)
4449 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4453 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4454 int len = src->length();
4456 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4457 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4459 if (InNewSpace(obj)) {
4460 HeapObject* dst = HeapObject::cast(obj);
4461 dst->set_map_no_write_barrier(map);
4462 CopyBlock(dst->address() + kPointerSize,
4463 src->address() + kPointerSize,
4464 FixedArray::SizeFor(len) - kPointerSize);
4467 HeapObject::cast(obj)->set_map_no_write_barrier(map);
4468 FixedArray* result = FixedArray::cast(obj);
4469 result->set_length(len);
4472 AssertNoAllocation no_gc;
4473 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4474 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4479 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4481 int len = src->length();
4483 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4484 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4486 HeapObject* dst = HeapObject::cast(obj);
4487 dst->set_map_no_write_barrier(map);
4489 dst->address() + FixedDoubleArray::kLengthOffset,
4490 src->address() + FixedDoubleArray::kLengthOffset,
4491 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4496 MaybeObject* Heap::AllocateFixedArray(int length) {
4497 ASSERT(length >= 0);
4498 if (length == 0) return empty_fixed_array();
4500 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4501 if (!maybe_result->ToObject(&result)) return maybe_result;
4503 // Initialize header.
4504 FixedArray* array = reinterpret_cast<FixedArray*>(result);
4505 array->set_map_no_write_barrier(fixed_array_map());
4506 array->set_length(length);
4508 ASSERT(!InNewSpace(undefined_value()));
4509 MemsetPointer(array->data_start(), undefined_value(), length);
4514 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4515 if (length < 0 || length > FixedArray::kMaxLength) {
4516 return Failure::OutOfMemoryException();
4519 AllocationSpace space =
4520 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4521 int size = FixedArray::SizeFor(length);
4522 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4523 // Too big for new space.
4525 } else if (space == OLD_POINTER_SPACE &&
4526 size > Page::kMaxNonCodeHeapObjectSize) {
4527 // Too big for old pointer space.
4531 AllocationSpace retry_space =
4532 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4534 return AllocateRaw(size, space, retry_space);
4538 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4541 PretenureFlag pretenure,
4543 ASSERT(length >= 0);
4544 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4545 if (length == 0) return heap->empty_fixed_array();
4547 ASSERT(!heap->InNewSpace(filler));
4549 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4550 if (!maybe_result->ToObject(&result)) return maybe_result;
4553 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4554 FixedArray* array = FixedArray::cast(result);
4555 array->set_length(length);
4556 MemsetPointer(array->data_start(), filler, length);
4561 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4562 return AllocateFixedArrayWithFiller(this,
4569 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4570 PretenureFlag pretenure) {
4571 return AllocateFixedArrayWithFiller(this,
4578 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4579 if (length == 0) return empty_fixed_array();
4582 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4583 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4586 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4588 FixedArray::cast(obj)->set_length(length);
4593 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4594 int size = FixedDoubleArray::SizeFor(0);
4596 { MaybeObject* maybe_result =
4597 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4598 if (!maybe_result->ToObject(&result)) return maybe_result;
4600 // Initialize the object.
4601 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4602 fixed_double_array_map());
4603 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4608 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4610 PretenureFlag pretenure) {
4611 if (length == 0) return empty_fixed_array();
4613 Object* elements_object;
4614 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4615 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4616 FixedDoubleArray* elements =
4617 reinterpret_cast<FixedDoubleArray*>(elements_object);
4619 elements->set_map_no_write_barrier(fixed_double_array_map());
4620 elements->set_length(length);
4625 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4627 PretenureFlag pretenure) {
4628 if (length == 0) return empty_fixed_array();
4630 Object* elements_object;
4631 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4632 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4633 FixedDoubleArray* elements =
4634 reinterpret_cast<FixedDoubleArray*>(elements_object);
4636 for (int i = 0; i < length; ++i) {
4637 elements->set_the_hole(i);
4640 elements->set_map_no_write_barrier(fixed_double_array_map());
4641 elements->set_length(length);
4646 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4647 PretenureFlag pretenure) {
4648 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4649 return Failure::OutOfMemoryException();
4652 AllocationSpace space =
4653 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4654 int size = FixedDoubleArray::SizeFor(length);
4655 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4656 // Too big for new space.
4658 } else if (space == OLD_DATA_SPACE &&
4659 size > Page::kMaxNonCodeHeapObjectSize) {
4660 // Too big for old data space.
4664 AllocationSpace retry_space =
4665 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4667 return AllocateRaw(size, space, retry_space);
4671 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4673 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4674 if (!maybe_result->ToObject(&result)) return maybe_result;
4676 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4678 ASSERT(result->IsHashTable());
4683 MaybeObject* Heap::AllocateGlobalContext() {
4685 { MaybeObject* maybe_result =
4686 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4687 if (!maybe_result->ToObject(&result)) return maybe_result;
4689 Context* context = reinterpret_cast<Context*>(result);
4690 context->set_map_no_write_barrier(global_context_map());
4691 context->set_smi_js_array_map(undefined_value());
4692 context->set_double_js_array_map(undefined_value());
4693 context->set_object_js_array_map(undefined_value());
4694 ASSERT(context->IsGlobalContext());
4695 ASSERT(result->IsContext());
4700 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4701 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4703 { MaybeObject* maybe_result = AllocateFixedArray(length);
4704 if (!maybe_result->ToObject(&result)) return maybe_result;
4706 Context* context = reinterpret_cast<Context*>(result);
4707 context->set_map_no_write_barrier(function_context_map());
4708 context->set_closure(function);
4709 context->set_previous(function->context());
4710 context->set_extension(NULL);
4711 context->set_global(function->context()->global());
4716 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4719 Object* thrown_object) {
4720 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4722 { MaybeObject* maybe_result =
4723 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4724 if (!maybe_result->ToObject(&result)) return maybe_result;
4726 Context* context = reinterpret_cast<Context*>(result);
4727 context->set_map_no_write_barrier(catch_context_map());
4728 context->set_closure(function);
4729 context->set_previous(previous);
4730 context->set_extension(name);
4731 context->set_global(previous->global());
4732 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4737 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4739 JSObject* extension) {
4741 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4742 if (!maybe_result->ToObject(&result)) return maybe_result;
4744 Context* context = reinterpret_cast<Context*>(result);
4745 context->set_map_no_write_barrier(with_context_map());
4746 context->set_closure(function);
4747 context->set_previous(previous);
4748 context->set_extension(extension);
4749 context->set_global(previous->global());
4754 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4756 ScopeInfo* scope_info) {
4758 { MaybeObject* maybe_result =
4759 AllocateFixedArrayWithHoles(scope_info->ContextLength());
4760 if (!maybe_result->ToObject(&result)) return maybe_result;
4762 Context* context = reinterpret_cast<Context*>(result);
4763 context->set_map_no_write_barrier(block_context_map());
4764 context->set_closure(function);
4765 context->set_previous(previous);
4766 context->set_extension(scope_info);
4767 context->set_global(previous->global());
4772 MaybeObject* Heap::AllocateScopeInfo(int length) {
4773 FixedArray* scope_info;
4774 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4775 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4776 scope_info->set_map_no_write_barrier(scope_info_map());
4781 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4784 #define MAKE_CASE(NAME, Name, name) \
4785 case NAME##_TYPE: map = name##_map(); break;
4786 STRUCT_LIST(MAKE_CASE)
4790 return Failure::InternalError();
4792 int size = map->instance_size();
4793 AllocationSpace space =
4794 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
4796 { MaybeObject* maybe_result = Allocate(map, space);
4797 if (!maybe_result->ToObject(&result)) return maybe_result;
4799 Struct::cast(result)->InitializeBody(size);
4804 bool Heap::IsHeapIterable() {
4805 return (!old_pointer_space()->was_swept_conservatively() &&
4806 !old_data_space()->was_swept_conservatively());
4810 void Heap::EnsureHeapIsIterable() {
4811 ASSERT(IsAllocationAllowed());
4812 if (!IsHeapIterable()) {
4813 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
4815 ASSERT(IsHeapIterable());
4819 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
4820 // This flag prevents incremental marking from requesting GC via stack guard
4821 idle_notification_will_schedule_next_gc_ = true;
4822 incremental_marking()->Step(step_size);
4823 idle_notification_will_schedule_next_gc_ = false;
4825 if (incremental_marking()->IsComplete()) {
4826 bool uncommit = false;
4827 if (gc_count_at_last_idle_gc_ == gc_count_) {
4828 // No GC since the last full GC, the mutator is probably not active.
4829 isolate_->compilation_cache()->Clear();
4832 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4833 gc_count_at_last_idle_gc_ = gc_count_;
4835 new_space_.Shrink();
4836 UncommitFromSpace();
4842 bool Heap::IdleNotification(int hint) {
4843 const int kMaxHint = 1000;
4844 intptr_t size_factor = Min(Max(hint, 30), kMaxHint) / 10;
4845 // The size factor is in range [3..100].
4846 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
4848 if (contexts_disposed_ > 0) {
4849 if (hint >= kMaxHint) {
4850 // The embedder is requesting a lot of GC work after context disposal,
4851 // we age inline caches so that they don't keep objects from
4852 // the old context alive.
4855 int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
4856 if (hint >= mark_sweep_time && !FLAG_expose_gc &&
4857 incremental_marking()->IsStopped()) {
4858 HistogramTimerScope scope(isolate_->counters()->gc_context());
4859 CollectAllGarbage(kReduceMemoryFootprintMask,
4860 "idle notification: contexts disposed");
4862 AdvanceIdleIncrementalMarking(step_size);
4863 contexts_disposed_ = 0;
4865 // Make sure that we have no pending context disposals.
4866 // Take into account that we might have decided to delay full collection
4867 // because incremental marking is in progress.
4868 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
4872 if (hint >= kMaxHint || !FLAG_incremental_marking ||
4873 FLAG_expose_gc || Serializer::enabled()) {
4874 return IdleGlobalGC();
4877 // By doing small chunks of GC work in each IdleNotification,
4878 // perform a round of incremental GCs and after that wait until
4879 // the mutator creates enough garbage to justify a new round.
4880 // An incremental GC progresses as follows:
4881 // 1. many incremental marking steps,
4882 // 2. one old space mark-sweep-compact,
4883 // 3. many lazy sweep steps.
4884 // Use mark-sweep-compact events to count incremental GCs in a round.
4887 if (incremental_marking()->IsStopped()) {
4888 if (!IsSweepingComplete() &&
4889 !AdvanceSweepers(static_cast<int>(step_size))) {
4894 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4895 if (EnoughGarbageSinceLastIdleRound()) {
4902 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
4903 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
4904 ms_count_at_last_idle_notification_ = ms_count_;
4906 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4911 if (incremental_marking()->IsStopped()) {
4912 if (!WorthStartingGCWhenIdle()) {
4916 incremental_marking()->Start();
4919 AdvanceIdleIncrementalMarking(step_size);
4924 bool Heap::IdleGlobalGC() {
4925 static const int kIdlesBeforeScavenge = 4;
4926 static const int kIdlesBeforeMarkSweep = 7;
4927 static const int kIdlesBeforeMarkCompact = 8;
4928 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
4929 static const unsigned int kGCsBetweenCleanup = 4;
4931 if (!last_idle_notification_gc_count_init_) {
4932 last_idle_notification_gc_count_ = gc_count_;
4933 last_idle_notification_gc_count_init_ = true;
4936 bool uncommit = true;
4937 bool finished = false;
4939 // Reset the number of idle notifications received when a number of
4940 // GCs have taken place. This allows another round of cleanup based
4941 // on idle notifications if enough work has been carried out to
4942 // provoke a number of garbage collections.
4943 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4944 number_idle_notifications_ =
4945 Min(number_idle_notifications_ + 1, kMaxIdleCount);
4947 number_idle_notifications_ = 0;
4948 last_idle_notification_gc_count_ = gc_count_;
4951 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
4952 CollectGarbage(NEW_SPACE, "idle notification");
4953 new_space_.Shrink();
4954 last_idle_notification_gc_count_ = gc_count_;
4955 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
4956 // Before doing the mark-sweep collections we clear the
4957 // compilation cache to avoid hanging on to source code and
4958 // generated code for cached functions.
4959 isolate_->compilation_cache()->Clear();
4961 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
4962 new_space_.Shrink();
4963 last_idle_notification_gc_count_ = gc_count_;
4965 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
4966 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
4967 new_space_.Shrink();
4968 last_idle_notification_gc_count_ = gc_count_;
4969 number_idle_notifications_ = 0;
4971 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
4972 // If we have received more than kIdlesBeforeMarkCompact idle
4973 // notifications we do not perform any cleanup because we don't
4974 // expect to gain much by doing so.
4978 if (uncommit) UncommitFromSpace();
4986 void Heap::Print() {
4987 if (!HasBeenSetUp()) return;
4988 isolate()->PrintStack();
4990 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4995 void Heap::ReportCodeStatistics(const char* title) {
4996 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4997 PagedSpace::ResetCodeStatistics();
4998 // We do not look for code in new space, map space, or old space. If code
4999 // somehow ends up in those spaces, we would miss it here.
5000 code_space_->CollectCodeStatistics();
5001 lo_space_->CollectCodeStatistics();
5002 PagedSpace::ReportCodeStatistics();
5006 // This function expects that NewSpace's allocated objects histogram is
5007 // populated (via a call to CollectStatistics or else as a side effect of a
5008 // just-completed scavenge collection).
5009 void Heap::ReportHeapStatistics(const char* title) {
5011 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5013 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5014 old_gen_promotion_limit_);
5015 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5016 old_gen_allocation_limit_);
5017 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5020 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5021 isolate_->global_handles()->PrintStats();
5024 PrintF("Heap statistics : ");
5025 isolate_->memory_allocator()->ReportStatistics();
5026 PrintF("To space : ");
5027 new_space_.ReportStatistics();
5028 PrintF("Old pointer space : ");
5029 old_pointer_space_->ReportStatistics();
5030 PrintF("Old data space : ");
5031 old_data_space_->ReportStatistics();
5032 PrintF("Code space : ");
5033 code_space_->ReportStatistics();
5034 PrintF("Map space : ");
5035 map_space_->ReportStatistics();
5036 PrintF("Cell space : ");
5037 cell_space_->ReportStatistics();
5038 PrintF("Large object space : ");
5039 lo_space_->ReportStatistics();
5040 PrintF(">>>>>> ========================================= >>>>>>\n");
5045 bool Heap::Contains(HeapObject* value) {
5046 return Contains(value->address());
5050 bool Heap::Contains(Address addr) {
5051 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5052 return HasBeenSetUp() &&
5053 (new_space_.ToSpaceContains(addr) ||
5054 old_pointer_space_->Contains(addr) ||
5055 old_data_space_->Contains(addr) ||
5056 code_space_->Contains(addr) ||
5057 map_space_->Contains(addr) ||
5058 cell_space_->Contains(addr) ||
5059 lo_space_->SlowContains(addr));
5063 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5064 return InSpace(value->address(), space);
5068 bool Heap::InSpace(Address addr, AllocationSpace space) {
5069 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5070 if (!HasBeenSetUp()) return false;
5074 return new_space_.ToSpaceContains(addr);
5075 case OLD_POINTER_SPACE:
5076 return old_pointer_space_->Contains(addr);
5077 case OLD_DATA_SPACE:
5078 return old_data_space_->Contains(addr);
5080 return code_space_->Contains(addr);
5082 return map_space_->Contains(addr);
5084 return cell_space_->Contains(addr);
5086 return lo_space_->SlowContains(addr);
5094 void Heap::Verify() {
5095 ASSERT(HasBeenSetUp());
5097 store_buffer()->Verify();
5099 VerifyPointersVisitor visitor;
5100 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5102 new_space_.Verify();
5104 old_pointer_space_->Verify(&visitor);
5105 map_space_->Verify(&visitor);
5107 VerifyPointersVisitor no_dirty_regions_visitor;
5108 old_data_space_->Verify(&no_dirty_regions_visitor);
5109 code_space_->Verify(&no_dirty_regions_visitor);
5110 cell_space_->Verify(&no_dirty_regions_visitor);
5112 lo_space_->Verify();
5114 VerifyNoAccessorPairSharing();
5118 void Heap::VerifyNoAccessorPairSharing() {
5119 // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5120 // that we mark only unmarked pairs, then we clear all marks, restoring the
5121 // initial state. We use the Smi tag of the AccessorPair's getter as the
5122 // marking bit, because we can never see a Smi as the getter.
5123 for (int phase = 0; phase < 2; phase++) {
5124 HeapObjectIterator iter(map_space());
5125 for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5127 DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5128 for (int i = 0; i < descs->number_of_descriptors(); i++) {
5129 if (descs->GetType(i) == CALLBACKS &&
5130 descs->GetValue(i)->IsAccessorPair()) {
5131 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5132 uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5133 uintptr_t after = (phase == 0) ?
5134 ((before & ~kSmiTagMask) | kSmiTag) :
5135 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5136 CHECK(before != after);
5137 accessors->set_getter(reinterpret_cast<Object*>(after));
5147 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5148 Object* symbol = NULL;
5150 { MaybeObject* maybe_new_table =
5151 symbol_table()->LookupSymbol(string, &symbol);
5152 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5154 // Can't use set_symbol_table because SymbolTable::cast knows that
5155 // SymbolTable is a singleton and checks for identity.
5156 roots_[kSymbolTableRootIndex] = new_table;
5157 ASSERT(symbol != NULL);
5162 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5163 Object* symbol = NULL;
5165 { MaybeObject* maybe_new_table =
5166 symbol_table()->LookupAsciiSymbol(string, &symbol);
5167 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5169 // Can't use set_symbol_table because SymbolTable::cast knows that
5170 // SymbolTable is a singleton and checks for identity.
5171 roots_[kSymbolTableRootIndex] = new_table;
5172 ASSERT(symbol != NULL);
5177 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5180 Object* symbol = NULL;
5182 { MaybeObject* maybe_new_table =
5183 symbol_table()->LookupSubStringAsciiSymbol(string,
5187 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5189 // Can't use set_symbol_table because SymbolTable::cast knows that
5190 // SymbolTable is a singleton and checks for identity.
5191 roots_[kSymbolTableRootIndex] = new_table;
5192 ASSERT(symbol != NULL);
5197 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5198 Object* symbol = NULL;
5200 { MaybeObject* maybe_new_table =
5201 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5202 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5204 // Can't use set_symbol_table because SymbolTable::cast knows that
5205 // SymbolTable is a singleton and checks for identity.
5206 roots_[kSymbolTableRootIndex] = new_table;
5207 ASSERT(symbol != NULL);
5212 MaybeObject* Heap::LookupSymbol(String* string) {
5213 if (string->IsSymbol()) return string;
5214 Object* symbol = NULL;
5216 { MaybeObject* maybe_new_table =
5217 symbol_table()->LookupString(string, &symbol);
5218 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5220 // Can't use set_symbol_table because SymbolTable::cast knows that
5221 // SymbolTable is a singleton and checks for identity.
5222 roots_[kSymbolTableRootIndex] = new_table;
5223 ASSERT(symbol != NULL);
5228 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5229 if (string->IsSymbol()) {
5233 return symbol_table()->LookupSymbolIfExists(string, symbol);
5238 void Heap::ZapFromSpace() {
5239 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5240 new_space_.FromSpaceEnd());
5241 while (it.has_next()) {
5242 NewSpacePage* page = it.next();
5243 for (Address cursor = page->area_start(), limit = page->area_end();
5245 cursor += kPointerSize) {
5246 Memory::Address_at(cursor) = kFromSpaceZapValue;
5253 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5255 ObjectSlotCallback callback) {
5256 Address slot_address = start;
5258 // We are not collecting slots on new space objects during mutation
5259 // thus we have to scan for pointers to evacuation candidates when we
5260 // promote objects. But we should not record any slots in non-black
5261 // objects. Grey object's slots would be rescanned.
5262 // White object might not survive until the end of collection
5263 // it would be a violation of the invariant to record it's slots.
5264 bool record_slots = false;
5265 if (incremental_marking()->IsCompacting()) {
5266 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5267 record_slots = Marking::IsBlack(mark_bit);
5270 while (slot_address < end) {
5271 Object** slot = reinterpret_cast<Object**>(slot_address);
5272 Object* object = *slot;
5273 // If the store buffer becomes overfull we mark pages as being exempt from
5274 // the store buffer. These pages are scanned to find pointers that point
5275 // to the new space. In that case we may hit newly promoted objects and
5276 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5277 if (object->IsHeapObject()) {
5278 if (Heap::InFromSpace(object)) {
5279 callback(reinterpret_cast<HeapObject**>(slot),
5280 HeapObject::cast(object));
5281 Object* new_object = *slot;
5282 if (InNewSpace(new_object)) {
5283 SLOW_ASSERT(Heap::InToSpace(new_object));
5284 SLOW_ASSERT(new_object->IsHeapObject());
5285 store_buffer_.EnterDirectlyIntoStoreBuffer(
5286 reinterpret_cast<Address>(slot));
5288 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5289 } else if (record_slots &&
5290 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5291 mark_compact_collector()->RecordSlot(slot, slot, object);
5294 slot_address += kPointerSize;
5300 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5303 bool IsAMapPointerAddress(Object** addr) {
5304 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5305 int mod = a % Map::kSize;
5306 return mod >= Map::kPointerFieldsBeginOffset &&
5307 mod < Map::kPointerFieldsEndOffset;
5311 bool EverythingsAPointer(Object** addr) {
5316 static void CheckStoreBuffer(Heap* heap,
5319 Object**** store_buffer_position,
5320 Object*** store_buffer_top,
5321 CheckStoreBufferFilter filter,
5322 Address special_garbage_start,
5323 Address special_garbage_end) {
5324 Map* free_space_map = heap->free_space_map();
5325 for ( ; current < limit; current++) {
5326 Object* o = *current;
5327 Address current_address = reinterpret_cast<Address>(current);
5329 if (o == free_space_map) {
5330 Address current_address = reinterpret_cast<Address>(current);
5331 FreeSpace* free_space =
5332 FreeSpace::cast(HeapObject::FromAddress(current_address));
5333 int skip = free_space->Size();
5334 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5336 current_address += skip - kPointerSize;
5337 current = reinterpret_cast<Object**>(current_address);
5340 // Skip the current linear allocation space between top and limit which is
5341 // unmarked with the free space map, but can contain junk.
5342 if (current_address == special_garbage_start &&
5343 special_garbage_end != special_garbage_start) {
5344 current_address = special_garbage_end - kPointerSize;
5345 current = reinterpret_cast<Object**>(current_address);
5348 if (!(*filter)(current)) continue;
5349 ASSERT(current_address < special_garbage_start ||
5350 current_address >= special_garbage_end);
5351 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5352 // We have to check that the pointer does not point into new space
5353 // without trying to cast it to a heap object since the hash field of
5354 // a string can contain values like 1 and 3 which are tagged null
5356 if (!heap->InNewSpace(o)) continue;
5357 while (**store_buffer_position < current &&
5358 *store_buffer_position < store_buffer_top) {
5359 (*store_buffer_position)++;
5361 if (**store_buffer_position != current ||
5362 *store_buffer_position == store_buffer_top) {
5363 Object** obj_start = current;
5364 while (!(*obj_start)->IsMap()) obj_start--;
5371 // Check that the store buffer contains all intergenerational pointers by
5372 // scanning a page and ensuring that all pointers to young space are in the
5374 void Heap::OldPointerSpaceCheckStoreBuffer() {
5375 OldSpace* space = old_pointer_space();
5376 PageIterator pages(space);
5378 store_buffer()->SortUniq();
5380 while (pages.has_next()) {
5381 Page* page = pages.next();
5382 Object** current = reinterpret_cast<Object**>(page->area_start());
5384 Address end = page->area_end();
5386 Object*** store_buffer_position = store_buffer()->Start();
5387 Object*** store_buffer_top = store_buffer()->Top();
5389 Object** limit = reinterpret_cast<Object**>(end);
5390 CheckStoreBuffer(this,
5393 &store_buffer_position,
5395 &EverythingsAPointer,
5402 void Heap::MapSpaceCheckStoreBuffer() {
5403 MapSpace* space = map_space();
5404 PageIterator pages(space);
5406 store_buffer()->SortUniq();
5408 while (pages.has_next()) {
5409 Page* page = pages.next();
5410 Object** current = reinterpret_cast<Object**>(page->area_start());
5412 Address end = page->area_end();
5414 Object*** store_buffer_position = store_buffer()->Start();
5415 Object*** store_buffer_top = store_buffer()->Top();
5417 Object** limit = reinterpret_cast<Object**>(end);
5418 CheckStoreBuffer(this,
5421 &store_buffer_position,
5423 &IsAMapPointerAddress,
5430 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5431 LargeObjectIterator it(lo_space());
5432 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5433 // We only have code, sequential strings, or fixed arrays in large
5434 // object space, and only fixed arrays can possibly contain pointers to
5435 // the young generation.
5436 if (object->IsFixedArray()) {
5437 Object*** store_buffer_position = store_buffer()->Start();
5438 Object*** store_buffer_top = store_buffer()->Top();
5439 Object** current = reinterpret_cast<Object**>(object->address());
5441 reinterpret_cast<Object**>(object->address() + object->Size());
5442 CheckStoreBuffer(this,
5445 &store_buffer_position,
5447 &EverythingsAPointer,
5456 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5457 IterateStrongRoots(v, mode);
5458 IterateWeakRoots(v, mode);
5462 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5463 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5464 v->Synchronize(VisitorSynchronization::kSymbolTable);
5465 if (mode != VISIT_ALL_IN_SCAVENGE &&
5466 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5467 // Scavenge collections have special processing for this.
5468 external_string_table_.Iterate(v);
5470 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5474 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5475 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5476 v->Synchronize(VisitorSynchronization::kStrongRootList);
5478 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5479 v->Synchronize(VisitorSynchronization::kSymbol);
5481 isolate_->bootstrapper()->Iterate(v);
5482 v->Synchronize(VisitorSynchronization::kBootstrapper);
5483 isolate_->Iterate(v);
5484 v->Synchronize(VisitorSynchronization::kTop);
5485 Relocatable::Iterate(v);
5486 v->Synchronize(VisitorSynchronization::kRelocatable);
5488 #ifdef ENABLE_DEBUGGER_SUPPORT
5489 isolate_->debug()->Iterate(v);
5490 if (isolate_->deoptimizer_data() != NULL) {
5491 isolate_->deoptimizer_data()->Iterate(v);
5494 v->Synchronize(VisitorSynchronization::kDebug);
5495 isolate_->compilation_cache()->Iterate(v);
5496 v->Synchronize(VisitorSynchronization::kCompilationCache);
5498 // Iterate over local handles in handle scopes.
5499 isolate_->handle_scope_implementer()->Iterate(v);
5500 v->Synchronize(VisitorSynchronization::kHandleScope);
5502 // Iterate over the builtin code objects and code stubs in the
5503 // heap. Note that it is not necessary to iterate over code objects
5504 // on scavenge collections.
5505 if (mode != VISIT_ALL_IN_SCAVENGE) {
5506 isolate_->builtins()->IterateBuiltins(v);
5508 v->Synchronize(VisitorSynchronization::kBuiltins);
5510 // Iterate over global handles.
5512 case VISIT_ONLY_STRONG:
5513 isolate_->global_handles()->IterateStrongRoots(v);
5515 case VISIT_ALL_IN_SCAVENGE:
5516 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5518 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5520 isolate_->global_handles()->IterateAllRoots(v);
5523 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5525 // Iterate over pointers being held by inactive threads.
5526 isolate_->thread_manager()->Iterate(v);
5527 v->Synchronize(VisitorSynchronization::kThreadManager);
5529 // Iterate over the pointers the Serialization/Deserialization code is
5531 // During garbage collection this keeps the partial snapshot cache alive.
5532 // During deserialization of the startup snapshot this creates the partial
5533 // snapshot cache and deserializes the objects it refers to. During
5534 // serialization this does nothing, since the partial snapshot cache is
5535 // empty. However the next thing we do is create the partial snapshot,
5536 // filling up the partial snapshot cache with objects it needs as we go.
5537 SerializerDeserializer::Iterate(v);
5538 // We don't do a v->Synchronize call here, because in debug mode that will
5539 // output a flag to the snapshot. However at this point the serializer and
5540 // deserializer are deliberately a little unsynchronized (see above) so the
5541 // checking of the sync flag in the snapshot would fail.
5545 // TODO(1236194): Since the heap size is configurable on the command line
5546 // and through the API, we should gracefully handle the case that the heap
5547 // size is not big enough to fit all the initial objects.
5548 bool Heap::ConfigureHeap(int max_semispace_size,
5549 intptr_t max_old_gen_size,
5550 intptr_t max_executable_size) {
5551 if (HasBeenSetUp()) return false;
5553 if (max_semispace_size > 0) {
5554 if (max_semispace_size < Page::kPageSize) {
5555 max_semispace_size = Page::kPageSize;
5556 if (FLAG_trace_gc) {
5557 PrintF("Max semispace size cannot be less than %dkbytes\n",
5558 Page::kPageSize >> 10);
5561 max_semispace_size_ = max_semispace_size;
5564 if (Snapshot::IsEnabled()) {
5565 // If we are using a snapshot we always reserve the default amount
5566 // of memory for each semispace because code in the snapshot has
5567 // write-barrier code that relies on the size and alignment of new
5568 // space. We therefore cannot use a larger max semispace size
5569 // than the default reserved semispace size.
5570 if (max_semispace_size_ > reserved_semispace_size_) {
5571 max_semispace_size_ = reserved_semispace_size_;
5572 if (FLAG_trace_gc) {
5573 PrintF("Max semispace size cannot be more than %dkbytes\n",
5574 reserved_semispace_size_ >> 10);
5578 // If we are not using snapshots we reserve space for the actual
5579 // max semispace size.
5580 reserved_semispace_size_ = max_semispace_size_;
5583 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5584 if (max_executable_size > 0) {
5585 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5588 // The max executable size must be less than or equal to the max old
5590 if (max_executable_size_ > max_old_generation_size_) {
5591 max_executable_size_ = max_old_generation_size_;
5594 // The new space size must be a power of two to support single-bit testing
5596 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5597 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5598 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5599 external_allocation_limit_ = 10 * max_semispace_size_;
5601 // The old generation is paged and needs at least one page for each space.
5602 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5603 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5605 RoundUp(max_old_generation_size_,
5613 bool Heap::ConfigureHeapDefault() {
5614 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5615 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5616 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5620 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5621 *stats->start_marker = HeapStats::kStartMarker;
5622 *stats->end_marker = HeapStats::kEndMarker;
5623 *stats->new_space_size = new_space_.SizeAsInt();
5624 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5625 *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5626 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5627 *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5628 *stats->old_data_space_capacity = old_data_space_->Capacity();
5629 *stats->code_space_size = code_space_->SizeOfObjects();
5630 *stats->code_space_capacity = code_space_->Capacity();
5631 *stats->map_space_size = map_space_->SizeOfObjects();
5632 *stats->map_space_capacity = map_space_->Capacity();
5633 *stats->cell_space_size = cell_space_->SizeOfObjects();
5634 *stats->cell_space_capacity = cell_space_->Capacity();
5635 *stats->lo_space_size = lo_space_->Size();
5636 isolate_->global_handles()->RecordStats(stats);
5637 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5638 *stats->memory_allocator_capacity =
5639 isolate()->memory_allocator()->Size() +
5640 isolate()->memory_allocator()->Available();
5641 *stats->os_error = OS::GetLastError();
5642 isolate()->memory_allocator()->Available();
5643 if (take_snapshot) {
5644 HeapIterator iterator;
5645 for (HeapObject* obj = iterator.next();
5647 obj = iterator.next()) {
5648 InstanceType type = obj->map()->instance_type();
5649 ASSERT(0 <= type && type <= LAST_TYPE);
5650 stats->objects_per_type[type]++;
5651 stats->size_per_type[type] += obj->Size();
5657 intptr_t Heap::PromotedSpaceSize() {
5658 return old_pointer_space_->Size()
5659 + old_data_space_->Size()
5660 + code_space_->Size()
5661 + map_space_->Size()
5662 + cell_space_->Size()
5663 + lo_space_->Size();
5667 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5668 return old_pointer_space_->SizeOfObjects()
5669 + old_data_space_->SizeOfObjects()
5670 + code_space_->SizeOfObjects()
5671 + map_space_->SizeOfObjects()
5672 + cell_space_->SizeOfObjects()
5673 + lo_space_->SizeOfObjects();
5677 int Heap::PromotedExternalMemorySize() {
5678 if (amount_of_external_allocated_memory_
5679 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5680 return amount_of_external_allocated_memory_
5681 - amount_of_external_allocated_memory_at_last_global_gc_;
5686 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5687 static const int kMarkTag = 2;
5690 class HeapDebugUtils {
5692 explicit HeapDebugUtils(Heap* heap)
5693 : search_for_any_global_(false),
5694 search_target_(NULL),
5695 found_target_(false),
5700 class MarkObjectVisitor : public ObjectVisitor {
5702 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5704 void VisitPointers(Object** start, Object** end) {
5705 // Copy all HeapObject pointers in [start, end)
5706 for (Object** p = start; p < end; p++) {
5707 if ((*p)->IsHeapObject())
5708 utils_->MarkObjectRecursively(p);
5712 HeapDebugUtils* utils_;
5715 void MarkObjectRecursively(Object** p) {
5716 if (!(*p)->IsHeapObject()) return;
5718 HeapObject* obj = HeapObject::cast(*p);
5720 Object* map = obj->map();
5722 if (!map->IsHeapObject()) return; // visited before
5724 if (found_target_) return; // stop if target found
5725 object_stack_.Add(obj);
5726 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5727 (!search_for_any_global_ && (obj == search_target_))) {
5728 found_target_ = true;
5733 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5735 Address map_addr = map_p->address();
5737 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
5739 MarkObjectRecursively(&map);
5741 MarkObjectVisitor mark_visitor(this);
5743 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5746 if (!found_target_) // don't pop if found the target
5747 object_stack_.RemoveLast();
5751 class UnmarkObjectVisitor : public ObjectVisitor {
5753 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5755 void VisitPointers(Object** start, Object** end) {
5756 // Copy all HeapObject pointers in [start, end)
5757 for (Object** p = start; p < end; p++) {
5758 if ((*p)->IsHeapObject())
5759 utils_->UnmarkObjectRecursively(p);
5763 HeapDebugUtils* utils_;
5767 void UnmarkObjectRecursively(Object** p) {
5768 if (!(*p)->IsHeapObject()) return;
5770 HeapObject* obj = HeapObject::cast(*p);
5772 Object* map = obj->map();
5774 if (map->IsHeapObject()) return; // unmarked already
5776 Address map_addr = reinterpret_cast<Address>(map);
5778 map_addr -= kMarkTag;
5780 ASSERT_TAG_ALIGNED(map_addr);
5782 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5784 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
5786 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5788 UnmarkObjectVisitor unmark_visitor(this);
5790 obj->IterateBody(Map::cast(map_p)->instance_type(),
5791 obj->SizeFromMap(Map::cast(map_p)),
5796 void MarkRootObjectRecursively(Object** root) {
5797 if (search_for_any_global_) {
5798 ASSERT(search_target_ == NULL);
5800 ASSERT(search_target_->IsHeapObject());
5802 found_target_ = false;
5803 object_stack_.Clear();
5805 MarkObjectRecursively(root);
5806 UnmarkObjectRecursively(root);
5808 if (found_target_) {
5809 PrintF("=====================================\n");
5810 PrintF("==== Path to object ====\n");
5811 PrintF("=====================================\n\n");
5813 ASSERT(!object_stack_.is_empty());
5814 for (int i = 0; i < object_stack_.length(); i++) {
5815 if (i > 0) PrintF("\n |\n |\n V\n\n");
5816 Object* obj = object_stack_[i];
5819 PrintF("=====================================\n");
5823 // Helper class for visiting HeapObjects recursively.
5824 class MarkRootVisitor: public ObjectVisitor {
5826 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5828 void VisitPointers(Object** start, Object** end) {
5829 // Visit all HeapObject pointers in [start, end)
5830 for (Object** p = start; p < end; p++) {
5831 if ((*p)->IsHeapObject())
5832 utils_->MarkRootObjectRecursively(p);
5836 HeapDebugUtils* utils_;
5839 bool search_for_any_global_;
5840 Object* search_target_;
5842 List<Object*> object_stack_;
5850 bool Heap::SetUp(bool create_heap_objects) {
5852 allocation_timeout_ = FLAG_gc_interval;
5853 debug_utils_ = new HeapDebugUtils(this);
5856 // Initialize heap spaces and initial maps and objects. Whenever something
5857 // goes wrong, just return false. The caller should check the results and
5858 // call Heap::TearDown() to release allocated memory.
5860 // If the heap is not yet configured (e.g. through the API), configure it.
5861 // Configuration is based on the flags new-space-size (really the semispace
5862 // size) and old-space-size if set or the initial values of semispace_size_
5863 // and old_generation_size_ otherwise.
5865 if (!ConfigureHeapDefault()) return false;
5868 gc_initializer_mutex.Pointer()->Lock();
5869 static bool initialized_gc = false;
5870 if (!initialized_gc) {
5871 initialized_gc = true;
5872 InitializeScavengingVisitorsTables();
5873 NewSpaceScavenger::Initialize();
5874 MarkCompactCollector::Initialize();
5876 gc_initializer_mutex.Pointer()->Unlock();
5878 MarkMapPointersAsEncoded(false);
5880 // Set up memory allocator.
5881 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
5884 // Set up new space.
5885 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
5889 // Initialize old pointer space.
5890 old_pointer_space_ =
5892 max_old_generation_size_,
5895 if (old_pointer_space_ == NULL) return false;
5896 if (!old_pointer_space_->SetUp()) return false;
5898 // Initialize old data space.
5901 max_old_generation_size_,
5904 if (old_data_space_ == NULL) return false;
5905 if (!old_data_space_->SetUp()) return false;
5907 // Initialize the code space, set its maximum capacity to the old
5908 // generation size. It needs executable memory.
5909 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5910 // virtual address space, so that they can call each other with near calls.
5911 if (code_range_size_ > 0) {
5912 if (!isolate_->code_range()->SetUp(code_range_size_)) {
5918 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
5919 if (code_space_ == NULL) return false;
5920 if (!code_space_->SetUp()) return false;
5922 // Initialize map space.
5923 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
5924 if (map_space_ == NULL) return false;
5925 if (!map_space_->SetUp()) return false;
5927 // Initialize global property cell space.
5928 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
5929 if (cell_space_ == NULL) return false;
5930 if (!cell_space_->SetUp()) return false;
5932 // The large object code space may contain code or data. We set the memory
5933 // to be non-executable here for safety, but this means we need to enable it
5934 // explicitly when allocating large code objects.
5935 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
5936 if (lo_space_ == NULL) return false;
5937 if (!lo_space_->SetUp()) return false;
5939 // Set up the seed that is used to randomize the string hash function.
5940 ASSERT(hash_seed() == 0);
5941 if (FLAG_randomize_hashes) {
5942 if (FLAG_hash_seed == 0) {
5944 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
5946 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5950 if (create_heap_objects) {
5951 // Create initial maps.
5952 if (!CreateInitialMaps()) return false;
5953 if (!CreateApiObjects()) return false;
5955 // Create initial objects
5956 if (!CreateInitialObjects()) return false;
5958 global_contexts_list_ = undefined_value();
5961 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5962 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
5964 store_buffer()->SetUp();
5970 void Heap::SetStackLimits() {
5971 ASSERT(isolate_ != NULL);
5972 ASSERT(isolate_ == isolate());
5973 // On 64 bit machines, pointers are generally out of range of Smis. We write
5974 // something that looks like an out of range Smi to the GC.
5976 // Set up the special root array entries containing the stack limits.
5977 // These are actually addresses, but the tag makes the GC ignore it.
5978 roots_[kStackLimitRootIndex] =
5979 reinterpret_cast<Object*>(
5980 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
5981 roots_[kRealStackLimitRootIndex] =
5982 reinterpret_cast<Object*>(
5983 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
5987 void Heap::TearDown() {
5988 if (FLAG_print_cumulative_gc_stat) {
5990 PrintF("gc_count=%d ", gc_count_);
5991 PrintF("mark_sweep_count=%d ", ms_count_);
5992 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5993 PrintF("min_in_mutator=%d ", get_min_in_mutator());
5994 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
5995 get_max_alive_after_gc());
5999 isolate_->global_handles()->TearDown();
6001 external_string_table_.TearDown();
6003 new_space_.TearDown();
6005 if (old_pointer_space_ != NULL) {
6006 old_pointer_space_->TearDown();
6007 delete old_pointer_space_;
6008 old_pointer_space_ = NULL;
6011 if (old_data_space_ != NULL) {
6012 old_data_space_->TearDown();
6013 delete old_data_space_;
6014 old_data_space_ = NULL;
6017 if (code_space_ != NULL) {
6018 code_space_->TearDown();
6023 if (map_space_ != NULL) {
6024 map_space_->TearDown();
6029 if (cell_space_ != NULL) {
6030 cell_space_->TearDown();
6035 if (lo_space_ != NULL) {
6036 lo_space_->TearDown();
6041 store_buffer()->TearDown();
6042 incremental_marking()->TearDown();
6044 isolate_->memory_allocator()->TearDown();
6047 delete debug_utils_;
6048 debug_utils_ = NULL;
6053 void Heap::Shrink() {
6054 // Try to shrink all paged spaces.
6056 for (PagedSpace* space = spaces.next();
6058 space = spaces.next()) {
6059 space->ReleaseAllUnusedPages();
6064 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6065 ASSERT(callback != NULL);
6066 GCPrologueCallbackPair pair(callback, gc_type);
6067 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6068 return gc_prologue_callbacks_.Add(pair);
6072 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6073 ASSERT(callback != NULL);
6074 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6075 if (gc_prologue_callbacks_[i].callback == callback) {
6076 gc_prologue_callbacks_.Remove(i);
6084 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6085 ASSERT(callback != NULL);
6086 GCEpilogueCallbackPair pair(callback, gc_type);
6087 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6088 return gc_epilogue_callbacks_.Add(pair);
6092 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6093 ASSERT(callback != NULL);
6094 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6095 if (gc_epilogue_callbacks_[i].callback == callback) {
6096 gc_epilogue_callbacks_.Remove(i);
6106 class PrintHandleVisitor: public ObjectVisitor {
6108 void VisitPointers(Object** start, Object** end) {
6109 for (Object** p = start; p < end; p++)
6110 PrintF(" handle %p to %p\n",
6111 reinterpret_cast<void*>(p),
6112 reinterpret_cast<void*>(*p));
6116 void Heap::PrintHandles() {
6117 PrintF("Handles:\n");
6118 PrintHandleVisitor v;
6119 isolate_->handle_scope_implementer()->Iterate(&v);
6125 Space* AllSpaces::next() {
6126 switch (counter_++) {
6128 return HEAP->new_space();
6129 case OLD_POINTER_SPACE:
6130 return HEAP->old_pointer_space();
6131 case OLD_DATA_SPACE:
6132 return HEAP->old_data_space();
6134 return HEAP->code_space();
6136 return HEAP->map_space();
6138 return HEAP->cell_space();
6140 return HEAP->lo_space();
6147 PagedSpace* PagedSpaces::next() {
6148 switch (counter_++) {
6149 case OLD_POINTER_SPACE:
6150 return HEAP->old_pointer_space();
6151 case OLD_DATA_SPACE:
6152 return HEAP->old_data_space();
6154 return HEAP->code_space();
6156 return HEAP->map_space();
6158 return HEAP->cell_space();
6166 OldSpace* OldSpaces::next() {
6167 switch (counter_++) {
6168 case OLD_POINTER_SPACE:
6169 return HEAP->old_pointer_space();
6170 case OLD_DATA_SPACE:
6171 return HEAP->old_data_space();
6173 return HEAP->code_space();
6180 SpaceIterator::SpaceIterator()
6181 : current_space_(FIRST_SPACE),
6187 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6188 : current_space_(FIRST_SPACE),
6190 size_func_(size_func) {
6194 SpaceIterator::~SpaceIterator() {
6195 // Delete active iterator if any.
6200 bool SpaceIterator::has_next() {
6201 // Iterate until no more spaces.
6202 return current_space_ != LAST_SPACE;
6206 ObjectIterator* SpaceIterator::next() {
6207 if (iterator_ != NULL) {
6210 // Move to the next space
6212 if (current_space_ > LAST_SPACE) {
6217 // Return iterator for the new current space.
6218 return CreateIterator();
6222 // Create an iterator for the space to iterate.
6223 ObjectIterator* SpaceIterator::CreateIterator() {
6224 ASSERT(iterator_ == NULL);
6226 switch (current_space_) {
6228 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6230 case OLD_POINTER_SPACE:
6231 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6233 case OLD_DATA_SPACE:
6234 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6237 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6240 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6243 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6246 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6250 // Return the newly allocated iterator;
6251 ASSERT(iterator_ != NULL);
6256 class HeapObjectsFilter {
6258 virtual ~HeapObjectsFilter() {}
6259 virtual bool SkipObject(HeapObject* object) = 0;
6263 class UnreachableObjectsFilter : public HeapObjectsFilter {
6265 UnreachableObjectsFilter() {
6266 MarkReachableObjects();
6269 ~UnreachableObjectsFilter() {
6270 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6273 bool SkipObject(HeapObject* object) {
6274 MarkBit mark_bit = Marking::MarkBitFrom(object);
6275 return !mark_bit.Get();
6279 class MarkingVisitor : public ObjectVisitor {
6281 MarkingVisitor() : marking_stack_(10) {}
6283 void VisitPointers(Object** start, Object** end) {
6284 for (Object** p = start; p < end; p++) {
6285 if (!(*p)->IsHeapObject()) continue;
6286 HeapObject* obj = HeapObject::cast(*p);
6287 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6288 if (!mark_bit.Get()) {
6290 marking_stack_.Add(obj);
6295 void TransitiveClosure() {
6296 while (!marking_stack_.is_empty()) {
6297 HeapObject* obj = marking_stack_.RemoveLast();
6303 List<HeapObject*> marking_stack_;
6306 void MarkReachableObjects() {
6307 Heap* heap = Isolate::Current()->heap();
6308 MarkingVisitor visitor;
6309 heap->IterateRoots(&visitor, VISIT_ALL);
6310 visitor.TransitiveClosure();
6313 AssertNoAllocation no_alloc;
6317 HeapIterator::HeapIterator()
6318 : filtering_(HeapIterator::kNoFiltering),
6324 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6325 : filtering_(filtering),
6331 HeapIterator::~HeapIterator() {
6336 void HeapIterator::Init() {
6337 // Start the iteration.
6338 space_iterator_ = new SpaceIterator;
6339 switch (filtering_) {
6340 case kFilterUnreachable:
6341 filter_ = new UnreachableObjectsFilter;
6346 object_iterator_ = space_iterator_->next();
6350 void HeapIterator::Shutdown() {
6352 // Assert that in filtering mode we have iterated through all
6353 // objects. Otherwise, heap will be left in an inconsistent state.
6354 if (filtering_ != kNoFiltering) {
6355 ASSERT(object_iterator_ == NULL);
6358 // Make sure the last iterator is deallocated.
6359 delete space_iterator_;
6360 space_iterator_ = NULL;
6361 object_iterator_ = NULL;
6367 HeapObject* HeapIterator::next() {
6368 if (filter_ == NULL) return NextObject();
6370 HeapObject* obj = NextObject();
6371 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6376 HeapObject* HeapIterator::NextObject() {
6377 // No iterator means we are done.
6378 if (object_iterator_ == NULL) return NULL;
6380 if (HeapObject* obj = object_iterator_->next_object()) {
6381 // If the current iterator has more objects we are fine.
6384 // Go though the spaces looking for one that has objects.
6385 while (space_iterator_->has_next()) {
6386 object_iterator_ = space_iterator_->next();
6387 if (HeapObject* obj = object_iterator_->next_object()) {
6392 // Done with the last space.
6393 object_iterator_ = NULL;
6398 void HeapIterator::reset() {
6399 // Restart the iterator.
6405 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6407 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6409 class PathTracer::MarkVisitor: public ObjectVisitor {
6411 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6412 void VisitPointers(Object** start, Object** end) {
6413 // Scan all HeapObject pointers in [start, end)
6414 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6415 if ((*p)->IsHeapObject())
6416 tracer_->MarkRecursively(p, this);
6421 PathTracer* tracer_;
6425 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6427 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6428 void VisitPointers(Object** start, Object** end) {
6429 // Scan all HeapObject pointers in [start, end)
6430 for (Object** p = start; p < end; p++) {
6431 if ((*p)->IsHeapObject())
6432 tracer_->UnmarkRecursively(p, this);
6437 PathTracer* tracer_;
6441 void PathTracer::VisitPointers(Object** start, Object** end) {
6442 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6443 // Visit all HeapObject pointers in [start, end)
6444 for (Object** p = start; !done && (p < end); p++) {
6445 if ((*p)->IsHeapObject()) {
6447 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6453 void PathTracer::Reset() {
6454 found_target_ = false;
6455 object_stack_.Clear();
6459 void PathTracer::TracePathFrom(Object** root) {
6460 ASSERT((search_target_ == kAnyGlobalObject) ||
6461 search_target_->IsHeapObject());
6462 found_target_in_trace_ = false;
6463 object_stack_.Clear();
6465 MarkVisitor mark_visitor(this);
6466 MarkRecursively(root, &mark_visitor);
6468 UnmarkVisitor unmark_visitor(this);
6469 UnmarkRecursively(root, &unmark_visitor);
6475 static bool SafeIsGlobalContext(HeapObject* obj) {
6476 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6480 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6481 if (!(*p)->IsHeapObject()) return;
6483 HeapObject* obj = HeapObject::cast(*p);
6485 Object* map = obj->map();
6487 if (!map->IsHeapObject()) return; // visited before
6489 if (found_target_in_trace_) return; // stop if target found
6490 object_stack_.Add(obj);
6491 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6492 (obj == search_target_)) {
6493 found_target_in_trace_ = true;
6494 found_target_ = true;
6498 bool is_global_context = SafeIsGlobalContext(obj);
6501 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6503 Address map_addr = map_p->address();
6505 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6507 // Scan the object body.
6508 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6509 // This is specialized to scan Context's properly.
6510 Object** start = reinterpret_cast<Object**>(obj->address() +
6511 Context::kHeaderSize);
6512 Object** end = reinterpret_cast<Object**>(obj->address() +
6513 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6514 mark_visitor->VisitPointers(start, end);
6516 obj->IterateBody(map_p->instance_type(),
6517 obj->SizeFromMap(map_p),
6521 // Scan the map after the body because the body is a lot more interesting
6522 // when doing leak detection.
6523 MarkRecursively(&map, mark_visitor);
6525 if (!found_target_in_trace_) // don't pop if found the target
6526 object_stack_.RemoveLast();
6530 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6531 if (!(*p)->IsHeapObject()) return;
6533 HeapObject* obj = HeapObject::cast(*p);
6535 Object* map = obj->map();
6537 if (map->IsHeapObject()) return; // unmarked already
6539 Address map_addr = reinterpret_cast<Address>(map);
6541 map_addr -= kMarkTag;
6543 ASSERT_TAG_ALIGNED(map_addr);
6545 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6547 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6549 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6551 obj->IterateBody(Map::cast(map_p)->instance_type(),
6552 obj->SizeFromMap(Map::cast(map_p)),
6557 void PathTracer::ProcessResults() {
6558 if (found_target_) {
6559 PrintF("=====================================\n");
6560 PrintF("==== Path to object ====\n");
6561 PrintF("=====================================\n\n");
6563 ASSERT(!object_stack_.is_empty());
6564 for (int i = 0; i < object_stack_.length(); i++) {
6565 if (i > 0) PrintF("\n |\n |\n V\n\n");
6566 Object* obj = object_stack_[i];
6573 PrintF("=====================================\n");
6576 #endif // DEBUG || LIVE_OBJECT_LIST
6580 // Triggers a depth-first traversal of reachable objects from roots
6581 // and finds a path to a specific heap object and prints it.
6582 void Heap::TracePathToObject(Object* target) {
6583 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6584 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6588 // Triggers a depth-first traversal of reachable objects from roots
6589 // and finds a path to any global object and prints it. Useful for
6590 // determining the source for leaks of global objects.
6591 void Heap::TracePathToGlobal() {
6592 PathTracer tracer(PathTracer::kAnyGlobalObject,
6593 PathTracer::FIND_ALL,
6595 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6600 static intptr_t CountTotalHolesSize() {
6601 intptr_t holes_size = 0;
6603 for (OldSpace* space = spaces.next();
6605 space = spaces.next()) {
6606 holes_size += space->Waste() + space->Available();
6612 GCTracer::GCTracer(Heap* heap,
6613 const char* gc_reason,
6614 const char* collector_reason)
6616 start_object_size_(0),
6617 start_memory_size_(0),
6620 allocated_since_last_gc_(0),
6621 spent_in_mutator_(0),
6622 promoted_objects_size_(0),
6624 gc_reason_(gc_reason),
6625 collector_reason_(collector_reason) {
6626 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6627 start_time_ = OS::TimeCurrentMillis();
6628 start_object_size_ = heap_->SizeOfObjects();
6629 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6631 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6635 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6637 allocated_since_last_gc_ =
6638 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6640 if (heap_->last_gc_end_timestamp_ > 0) {
6641 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6644 steps_count_ = heap_->incremental_marking()->steps_count();
6645 steps_took_ = heap_->incremental_marking()->steps_took();
6646 longest_step_ = heap_->incremental_marking()->longest_step();
6647 steps_count_since_last_gc_ =
6648 heap_->incremental_marking()->steps_count_since_last_gc();
6649 steps_took_since_last_gc_ =
6650 heap_->incremental_marking()->steps_took_since_last_gc();
6654 GCTracer::~GCTracer() {
6655 // Printf ONE line iff flag is set.
6656 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6658 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6660 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6661 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6663 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6665 // Update cumulative GC statistics if required.
6666 if (FLAG_print_cumulative_gc_stat) {
6667 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6668 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6669 heap_->alive_after_last_gc_);
6671 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6672 static_cast<int>(spent_in_mutator_));
6676 PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6678 if (!FLAG_trace_gc_nvp) {
6679 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6681 double end_memory_size_mb =
6682 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6684 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6686 static_cast<double>(start_object_size_) / MB,
6687 static_cast<double>(start_memory_size_) / MB,
6688 SizeOfHeapObjects(),
6689 end_memory_size_mb);
6691 if (external_time > 0) PrintF("%d / ", external_time);
6692 PrintF("%d ms", time);
6693 if (steps_count_ > 0) {
6694 if (collector_ == SCAVENGER) {
6695 PrintF(" (+ %d ms in %d steps since last GC)",
6696 static_cast<int>(steps_took_since_last_gc_),
6697 steps_count_since_last_gc_);
6699 PrintF(" (+ %d ms in %d steps since start of marking, "
6700 "biggest step %f ms)",
6701 static_cast<int>(steps_took_),
6707 if (gc_reason_ != NULL) {
6708 PrintF(" [%s]", gc_reason_);
6711 if (collector_reason_ != NULL) {
6712 PrintF(" [%s]", collector_reason_);
6717 PrintF("pause=%d ", time);
6718 PrintF("mutator=%d ",
6719 static_cast<int>(spent_in_mutator_));
6722 switch (collector_) {
6726 case MARK_COMPACTOR:
6734 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6735 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6736 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6737 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6738 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6739 PrintF("new_new=%d ",
6740 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6741 PrintF("root_new=%d ",
6742 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6743 PrintF("old_new=%d ",
6744 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6745 PrintF("compaction_ptrs=%d ",
6746 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6747 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6748 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6749 PrintF("misc_compaction=%d ",
6750 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
6752 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
6753 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6754 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6755 in_free_list_or_wasted_before_gc_);
6756 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6758 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6759 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6761 if (collector_ == SCAVENGER) {
6762 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6763 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6765 PrintF("stepscount=%d ", steps_count_);
6766 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6772 heap_->PrintShortHeapStatistics();
6776 const char* GCTracer::CollectorString() {
6777 switch (collector_) {
6780 case MARK_COMPACTOR:
6781 return "Mark-sweep";
6783 return "Unknown GC";
6787 int KeyedLookupCache::Hash(Map* map, String* name) {
6788 // Uses only lower 32 bits if pointers are larger.
6789 uintptr_t addr_hash =
6790 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6791 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6795 int KeyedLookupCache::Lookup(Map* map, String* name) {
6796 int index = (Hash(map, name) & kHashMask);
6797 for (int i = 0; i < kEntriesPerBucket; i++) {
6798 Key& key = keys_[index + i];
6799 if ((key.map == map) && key.name->Equals(name)) {
6800 return field_offsets_[index + i];
6807 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6809 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
6810 int index = (Hash(map, symbol) & kHashMask);
6811 // After a GC there will be free slots, so we use them in order (this may
6812 // help to get the most frequently used one in position 0).
6813 for (int i = 0; i< kEntriesPerBucket; i++) {
6814 Key& key = keys_[index];
6815 Object* free_entry_indicator = NULL;
6816 if (key.map == free_entry_indicator) {
6819 field_offsets_[index + i] = field_offset;
6823 // No free entry found in this bucket, so we move them all down one and
6824 // put the new entry at position zero.
6825 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6826 Key& key = keys_[index + i];
6827 Key& key2 = keys_[index + i - 1];
6829 field_offsets_[index + i] = field_offsets_[index + i - 1];
6832 // Write the new first entry.
6833 Key& key = keys_[index];
6836 field_offsets_[index] = field_offset;
6841 void KeyedLookupCache::Clear() {
6842 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6846 void DescriptorLookupCache::Clear() {
6847 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6852 void Heap::GarbageCollectionGreedyCheck() {
6853 ASSERT(FLAG_gc_greedy);
6854 if (isolate_->bootstrapper()->IsActive()) return;
6855 if (disallow_allocation_failure()) return;
6856 CollectGarbage(NEW_SPACE);
6861 TranscendentalCache::SubCache::SubCache(Type t)
6863 isolate_(Isolate::Current()) {
6864 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6865 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6866 for (int i = 0; i < kCacheSize; i++) {
6867 elements_[i].in[0] = in0;
6868 elements_[i].in[1] = in1;
6869 elements_[i].output = NULL;
6874 void TranscendentalCache::Clear() {
6875 for (int i = 0; i < kNumberOfCaches; i++) {
6876 if (caches_[i] != NULL) {
6884 void ExternalStringTable::CleanUp() {
6886 for (int i = 0; i < new_space_strings_.length(); ++i) {
6887 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6890 if (heap_->InNewSpace(new_space_strings_[i])) {
6891 new_space_strings_[last++] = new_space_strings_[i];
6893 old_space_strings_.Add(new_space_strings_[i]);
6896 new_space_strings_.Rewind(last);
6898 for (int i = 0; i < old_space_strings_.length(); ++i) {
6899 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6902 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
6903 old_space_strings_[last++] = old_space_strings_[i];
6905 old_space_strings_.Rewind(last);
6906 if (FLAG_verify_heap) {
6912 void ExternalStringTable::TearDown() {
6913 new_space_strings_.Free();
6914 old_space_strings_.Free();
6918 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6919 chunk->set_next_chunk(chunks_queued_for_free_);
6920 chunks_queued_for_free_ = chunk;
6924 void Heap::FreeQueuedChunks() {
6925 if (chunks_queued_for_free_ == NULL) return;
6928 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6929 next = chunk->next_chunk();
6930 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6932 if (chunk->owner()->identity() == LO_SPACE) {
6933 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6934 // If FromAnyPointerAddress encounters a slot that belongs to a large
6935 // chunk queued for deletion it will fail to find the chunk because
6936 // it try to perform a search in the list of pages owned by of the large
6937 // object space and queued chunks were detached from that list.
6938 // To work around this we split large chunk into normal kPageSize aligned
6939 // pieces and initialize size, owner and flags field of every piece.
6940 // If FromAnyPointerAddress encounters a slot that belongs to one of
6941 // these smaller pieces it will treat it as a slot on a normal Page.
6942 Address chunk_end = chunk->address() + chunk->size();
6943 MemoryChunk* inner = MemoryChunk::FromAddress(
6944 chunk->address() + Page::kPageSize);
6945 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
6946 while (inner <= inner_last) {
6947 // Size of a large chunk is always a multiple of
6948 // OS::AllocateAlignment() so there is always
6949 // enough space for a fake MemoryChunk header.
6950 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
6951 // Guard against overflow.
6952 if (area_end < inner->address()) area_end = chunk_end;
6953 inner->SetArea(inner->address(), area_end);
6954 inner->set_size(Page::kPageSize);
6955 inner->set_owner(lo_space());
6956 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6957 inner = MemoryChunk::FromAddress(
6958 inner->address() + Page::kPageSize);
6962 isolate_->heap()->store_buffer()->Compact();
6963 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6964 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6965 next = chunk->next_chunk();
6966 isolate_->memory_allocator()->Free(chunk);
6968 chunks_queued_for_free_ = NULL;
6972 void Heap::RememberUnmappedPage(Address page, bool compacted) {
6973 uintptr_t p = reinterpret_cast<uintptr_t>(page);
6974 // Tag the page pointer to make it findable in the dump file.
6976 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
6978 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
6980 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
6981 reinterpret_cast<Address>(p);
6982 remembered_unmapped_pages_index_++;
6983 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
6986 } } // namespace v8::internal