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"
64 static Mutex* gc_initializer_mutex = OS::CreateMutex();
69 // semispace_size_ should be a power of 2 and old_generation_size_ should be
70 // a multiple of Page::kPageSize.
72 #define LUMP_OF_MEMORY (128 * KB)
74 #elif defined(V8_TARGET_ARCH_X64)
75 #define LUMP_OF_MEMORY (2 * MB)
76 code_range_size_(512*MB),
78 #define LUMP_OF_MEMORY MB
81 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
82 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
83 initial_semispace_size_(Page::kPageSize),
84 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
85 max_executable_size_(128l * LUMP_OF_MEMORY),
87 // Variables set based on semispace_size_ and old_generation_size_ in
88 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
89 // Will be 4 * reserved_semispace_size_ to ensure that young
90 // generation can be aligned to its size.
91 survived_since_last_expansion_(0),
93 always_allocate_scope_depth_(0),
94 linear_allocation_scope_depth_(0),
95 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 unflattened_strings_length_(0),
110 allocation_allowed_(true),
111 allocation_timeout_(0),
112 disallow_allocation_failure_(false),
115 new_space_high_promotion_mode_active_(false),
116 old_gen_promotion_limit_(kMinimumPromotionLimit),
117 old_gen_allocation_limit_(kMinimumAllocationLimit),
118 old_gen_limit_factor_(1),
119 size_of_old_gen_at_last_old_space_gc_(0),
120 external_allocation_limit_(0),
121 amount_of_external_allocated_memory_(0),
122 amount_of_external_allocated_memory_at_last_global_gc_(0),
123 old_gen_exhausted_(false),
124 store_buffer_rebuilder_(store_buffer()),
125 hidden_symbol_(NULL),
126 global_gc_prologue_callback_(NULL),
127 global_gc_epilogue_callback_(NULL),
128 gc_safe_size_of_old_object_(NULL),
129 total_regexp_code_generated_(0),
131 young_survivors_after_last_gc_(0),
132 high_survival_rate_period_length_(0),
134 previous_survival_rate_trend_(Heap::STABLE),
135 survival_rate_trend_(Heap::STABLE),
137 max_alive_after_gc_(0),
138 min_in_mutator_(kMaxInt),
139 alive_after_last_gc_(0),
140 last_gc_end_timestamp_(0.0),
143 incremental_marking_(this),
144 number_idle_notifications_(0),
145 last_idle_notification_gc_count_(0),
146 last_idle_notification_gc_count_init_(false),
147 idle_notification_will_schedule_next_gc_(false),
148 mark_sweeps_since_idle_round_started_(0),
149 ms_count_at_last_idle_notification_(0),
150 gc_count_at_last_idle_gc_(0),
151 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
152 promotion_queue_(this),
154 chunks_queued_for_free_(NULL) {
155 // Allow build-time customization of the max semispace size. Building
156 // V8 with snapshots and a non-default max semispace size is much
157 // easier if you can define it as part of the build environment.
158 #if defined(V8_MAX_SEMISPACE_SIZE)
159 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
162 intptr_t max_virtual = OS::MaxVirtualMemory();
164 if (max_virtual > 0) {
165 if (code_range_size_ > 0) {
166 // Reserve no more than 1/8 of the memory for the code range.
167 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
171 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
172 global_contexts_list_ = NULL;
173 mark_compact_collector_.heap_ = this;
174 external_string_table_.heap_ = this;
178 intptr_t Heap::Capacity() {
179 if (!HasBeenSetUp()) return 0;
181 return new_space_.Capacity() +
182 old_pointer_space_->Capacity() +
183 old_data_space_->Capacity() +
184 code_space_->Capacity() +
185 map_space_->Capacity() +
186 cell_space_->Capacity();
190 intptr_t Heap::CommittedMemory() {
191 if (!HasBeenSetUp()) return 0;
193 return new_space_.CommittedMemory() +
194 old_pointer_space_->CommittedMemory() +
195 old_data_space_->CommittedMemory() +
196 code_space_->CommittedMemory() +
197 map_space_->CommittedMemory() +
198 cell_space_->CommittedMemory() +
202 intptr_t Heap::CommittedMemoryExecutable() {
203 if (!HasBeenSetUp()) return 0;
205 return isolate()->memory_allocator()->SizeExecutable();
209 intptr_t Heap::Available() {
210 if (!HasBeenSetUp()) return 0;
212 return new_space_.Available() +
213 old_pointer_space_->Available() +
214 old_data_space_->Available() +
215 code_space_->Available() +
216 map_space_->Available() +
217 cell_space_->Available();
221 bool Heap::HasBeenSetUp() {
222 return old_pointer_space_ != NULL &&
223 old_data_space_ != NULL &&
224 code_space_ != NULL &&
225 map_space_ != NULL &&
226 cell_space_ != NULL &&
231 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
232 if (IntrusiveMarking::IsMarked(object)) {
233 return IntrusiveMarking::SizeOfMarkedObject(object);
235 return object->SizeFromMap(object->map());
239 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
240 const char** reason) {
241 // Is global GC requested?
242 if (space != NEW_SPACE || FLAG_gc_global) {
243 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
244 *reason = "GC in old space requested";
245 return MARK_COMPACTOR;
248 // Is enough data promoted to justify a global GC?
249 if (OldGenerationPromotionLimitReached()) {
250 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
251 *reason = "promotion limit reached";
252 return MARK_COMPACTOR;
255 // Have allocation in OLD and LO failed?
256 if (old_gen_exhausted_) {
257 isolate_->counters()->
258 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
259 *reason = "old generations exhausted";
260 return MARK_COMPACTOR;
263 // Is there enough space left in OLD to guarantee that a scavenge can
266 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
267 // for object promotion. It counts only the bytes that the memory
268 // allocator has not yet allocated from the OS and assigned to any space,
269 // and does not count available bytes already in the old space or code
270 // space. Undercounting is safe---we may get an unrequested full GC when
271 // a scavenge would have succeeded.
272 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
273 isolate_->counters()->
274 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
275 *reason = "scavenge might not succeed";
276 return MARK_COMPACTOR;
285 // TODO(1238405): Combine the infrastructure for --heap-stats and
286 // --log-gc to avoid the complicated preprocessor and flag testing.
287 void Heap::ReportStatisticsBeforeGC() {
288 // Heap::ReportHeapStatistics will also log NewSpace statistics when
289 // compiled --log-gc is set. The following logic is used to avoid
292 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
293 if (FLAG_heap_stats) {
294 ReportHeapStatistics("Before GC");
295 } else if (FLAG_log_gc) {
296 new_space_.ReportStatistics();
298 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
301 new_space_.CollectStatistics();
302 new_space_.ReportStatistics();
303 new_space_.ClearHistograms();
309 void Heap::PrintShortHeapStatistics() {
310 if (!FLAG_trace_gc_verbose) return;
311 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
312 ", available: %8" V8_PTR_PREFIX "d\n",
313 isolate_->memory_allocator()->Size(),
314 isolate_->memory_allocator()->Available());
315 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
316 ", available: %8" V8_PTR_PREFIX "d\n",
317 Heap::new_space_.Size(),
318 new_space_.Available());
319 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
320 ", available: %8" V8_PTR_PREFIX "d"
321 ", waste: %8" V8_PTR_PREFIX "d\n",
322 old_pointer_space_->Size(),
323 old_pointer_space_->Available(),
324 old_pointer_space_->Waste());
325 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
326 ", available: %8" V8_PTR_PREFIX "d"
327 ", waste: %8" V8_PTR_PREFIX "d\n",
328 old_data_space_->Size(),
329 old_data_space_->Available(),
330 old_data_space_->Waste());
331 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
332 ", available: %8" V8_PTR_PREFIX "d"
333 ", waste: %8" V8_PTR_PREFIX "d\n",
335 code_space_->Available(),
336 code_space_->Waste());
337 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
338 ", available: %8" V8_PTR_PREFIX "d"
339 ", waste: %8" V8_PTR_PREFIX "d\n",
341 map_space_->Available(),
342 map_space_->Waste());
343 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
344 ", available: %8" V8_PTR_PREFIX "d"
345 ", waste: %8" V8_PTR_PREFIX "d\n",
347 cell_space_->Available(),
348 cell_space_->Waste());
349 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
350 ", available: %8" V8_PTR_PREFIX "d\n",
352 lo_space_->Available());
356 // TODO(1238405): Combine the infrastructure for --heap-stats and
357 // --log-gc to avoid the complicated preprocessor and flag testing.
358 void Heap::ReportStatisticsAfterGC() {
359 // Similar to the before GC, we use some complicated logic to ensure that
360 // NewSpace statistics are logged exactly once when --log-gc is turned on.
362 if (FLAG_heap_stats) {
363 new_space_.CollectStatistics();
364 ReportHeapStatistics("After GC");
365 } else if (FLAG_log_gc) {
366 new_space_.ReportStatistics();
369 if (FLAG_log_gc) new_space_.ReportStatistics();
374 void Heap::GarbageCollectionPrologue() {
375 isolate_->transcendental_cache()->Clear();
376 ClearJSFunctionResultCaches();
378 unflattened_strings_length_ = 0;
380 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
381 allow_allocation(false);
383 if (FLAG_verify_heap) {
387 if (FLAG_gc_verbose) Print();
391 ReportStatisticsBeforeGC();
394 LiveObjectList::GCPrologue();
395 store_buffer()->GCPrologue();
398 intptr_t Heap::SizeOfObjects() {
401 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
402 total += space->SizeOfObjects();
407 void Heap::GarbageCollectionEpilogue() {
408 store_buffer()->GCEpilogue();
409 LiveObjectList::GCEpilogue();
411 allow_allocation(true);
414 if (FLAG_verify_heap) {
418 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
419 if (FLAG_print_handles) PrintHandles();
420 if (FLAG_gc_verbose) Print();
421 if (FLAG_code_stats) ReportCodeStatistics("After GC");
424 isolate_->counters()->alive_after_last_gc()->Set(
425 static_cast<int>(SizeOfObjects()));
427 isolate_->counters()->symbol_table_capacity()->Set(
428 symbol_table()->Capacity());
429 isolate_->counters()->number_of_symbols()->Set(
430 symbol_table()->NumberOfElements());
432 ReportStatisticsAfterGC();
434 #ifdef ENABLE_DEBUGGER_SUPPORT
435 isolate_->debug()->AfterGarbageCollection();
436 #endif // ENABLE_DEBUGGER_SUPPORT
440 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
441 // Since we are ignoring the return value, the exact choice of space does
442 // not matter, so long as we do not specify NEW_SPACE, which would not
444 mark_compact_collector_.SetFlags(flags);
445 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
446 mark_compact_collector_.SetFlags(kNoGCFlags);
450 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
451 // Since we are ignoring the return value, the exact choice of space does
452 // not matter, so long as we do not specify NEW_SPACE, which would not
454 // Major GC would invoke weak handle callbacks on weakly reachable
455 // handles, but won't collect weakly reachable objects until next
456 // major GC. Therefore if we collect aggressively and weak handle callback
457 // has been invoked, we rerun major GC to release objects which become
459 // Note: as weak callbacks can execute arbitrary code, we cannot
460 // hope that eventually there will be no weak callbacks invocations.
461 // Therefore stop recollecting after several attempts.
462 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
463 kReduceMemoryFootprintMask);
464 isolate_->compilation_cache()->Clear();
465 const int kMaxNumberOfAttempts = 7;
466 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
467 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
471 mark_compact_collector()->SetFlags(kNoGCFlags);
475 incremental_marking()->UncommitMarkingDeque();
479 bool Heap::CollectGarbage(AllocationSpace space,
480 GarbageCollector collector,
481 const char* gc_reason,
482 const char* collector_reason) {
483 // The VM is in the GC state until exiting this function.
484 VMState state(isolate_, GC);
487 // Reset the allocation timeout to the GC interval, but make sure to
488 // allow at least a few allocations after a collection. The reason
489 // for this is that we have a lot of allocation sequences and we
490 // assume that a garbage collection will allow the subsequent
491 // allocation attempts to go through.
492 allocation_timeout_ = Max(6, FLAG_gc_interval);
495 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
496 if (FLAG_trace_incremental_marking) {
497 PrintF("[IncrementalMarking] Scavenge during marking.\n");
501 if (collector == MARK_COMPACTOR &&
502 !mark_compact_collector()->PreciseSweepingRequired() &&
503 !incremental_marking()->IsStopped() &&
504 !incremental_marking()->should_hurry() &&
505 FLAG_incremental_marking_steps) {
506 if (FLAG_trace_incremental_marking) {
507 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
509 collector = SCAVENGER;
510 collector_reason = "incremental marking delaying mark-sweep";
513 bool next_gc_likely_to_collect_more = false;
515 { GCTracer tracer(this, gc_reason, collector_reason);
516 GarbageCollectionPrologue();
517 // The GC count was incremented in the prologue. Tell the tracer about
519 tracer.set_gc_count(gc_count_);
521 // Tell the tracer which collector we've selected.
522 tracer.set_collector(collector);
524 HistogramTimer* rate = (collector == SCAVENGER)
525 ? isolate_->counters()->gc_scavenger()
526 : isolate_->counters()->gc_compactor();
528 next_gc_likely_to_collect_more =
529 PerformGarbageCollection(collector, &tracer);
532 GarbageCollectionEpilogue();
535 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
536 if (incremental_marking()->IsStopped()) {
537 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
538 incremental_marking()->Start();
542 return next_gc_likely_to_collect_more;
546 void Heap::PerformScavenge() {
547 GCTracer tracer(this, NULL, NULL);
548 if (incremental_marking()->IsStopped()) {
549 PerformGarbageCollection(SCAVENGER, &tracer);
551 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
557 // Helper class for verifying the symbol table.
558 class SymbolTableVerifier : public ObjectVisitor {
560 void VisitPointers(Object** start, Object** end) {
561 // Visit all HeapObject pointers in [start, end).
562 for (Object** p = start; p < end; p++) {
563 if ((*p)->IsHeapObject()) {
564 // Check that the symbol is actually a symbol.
565 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
573 static void VerifySymbolTable() {
575 SymbolTableVerifier verifier;
576 HEAP->symbol_table()->IterateElements(&verifier);
581 void Heap::ReserveSpace(
583 int pointer_space_size,
588 int large_object_size) {
589 NewSpace* new_space = Heap::new_space();
590 PagedSpace* old_pointer_space = Heap::old_pointer_space();
591 PagedSpace* old_data_space = Heap::old_data_space();
592 PagedSpace* code_space = Heap::code_space();
593 PagedSpace* map_space = Heap::map_space();
594 PagedSpace* cell_space = Heap::cell_space();
595 LargeObjectSpace* lo_space = Heap::lo_space();
596 bool gc_performed = true;
598 static const int kThreshold = 20;
599 while (gc_performed && counter++ < kThreshold) {
600 gc_performed = false;
601 if (!new_space->ReserveSpace(new_space_size)) {
602 Heap::CollectGarbage(NEW_SPACE,
603 "failed to reserve space in the new space");
606 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
607 Heap::CollectGarbage(OLD_POINTER_SPACE,
608 "failed to reserve space in the old pointer space");
611 if (!(old_data_space->ReserveSpace(data_space_size))) {
612 Heap::CollectGarbage(OLD_DATA_SPACE,
613 "failed to reserve space in the old data space");
616 if (!(code_space->ReserveSpace(code_space_size))) {
617 Heap::CollectGarbage(CODE_SPACE,
618 "failed to reserve space in the code space");
621 if (!(map_space->ReserveSpace(map_space_size))) {
622 Heap::CollectGarbage(MAP_SPACE,
623 "failed to reserve space in the map space");
626 if (!(cell_space->ReserveSpace(cell_space_size))) {
627 Heap::CollectGarbage(CELL_SPACE,
628 "failed to reserve space in the cell space");
631 // We add a slack-factor of 2 in order to have space for a series of
632 // large-object allocations that are only just larger than the page size.
633 large_object_size *= 2;
634 // The ReserveSpace method on the large object space checks how much
635 // we can expand the old generation. This includes expansion caused by
636 // allocation in the other spaces.
637 large_object_size += cell_space_size + map_space_size + code_space_size +
638 data_space_size + pointer_space_size;
639 if (!(lo_space->ReserveSpace(large_object_size))) {
640 Heap::CollectGarbage(LO_SPACE,
641 "failed to reserve space in the large object space");
647 // Failed to reserve the space after several attempts.
648 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
653 void Heap::EnsureFromSpaceIsCommitted() {
654 if (new_space_.CommitFromSpaceIfNeeded()) return;
656 // Committing memory to from space failed.
657 // Try shrinking and try again.
659 if (new_space_.CommitFromSpaceIfNeeded()) return;
661 // Committing memory to from space failed again.
662 // Memory is exhausted and we will die.
663 V8::FatalProcessOutOfMemory("Committing semi space failed.");
667 void Heap::ClearJSFunctionResultCaches() {
668 if (isolate_->bootstrapper()->IsActive()) return;
670 Object* context = global_contexts_list_;
671 while (!context->IsUndefined()) {
672 // Get the caches for this context. GC can happen when the context
673 // is not fully initialized, so the caches can be undefined.
674 Object* caches_or_undefined =
675 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
676 if (!caches_or_undefined->IsUndefined()) {
677 FixedArray* caches = FixedArray::cast(caches_or_undefined);
679 int length = caches->length();
680 for (int i = 0; i < length; i++) {
681 JSFunctionResultCache::cast(caches->get(i))->Clear();
684 // Get the next context:
685 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
691 void Heap::ClearNormalizedMapCaches() {
692 if (isolate_->bootstrapper()->IsActive() &&
693 !incremental_marking()->IsMarking()) {
697 Object* context = global_contexts_list_;
698 while (!context->IsUndefined()) {
699 // GC can happen when the context is not fully initialized,
700 // so the cache can be undefined.
702 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
703 if (!cache->IsUndefined()) {
704 NormalizedMapCache::cast(cache)->Clear();
706 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
711 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
712 double survival_rate =
713 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
714 start_new_space_size;
716 if (survival_rate > kYoungSurvivalRateHighThreshold) {
717 high_survival_rate_period_length_++;
719 high_survival_rate_period_length_ = 0;
722 if (survival_rate < kYoungSurvivalRateLowThreshold) {
723 low_survival_rate_period_length_++;
725 low_survival_rate_period_length_ = 0;
728 double survival_rate_diff = survival_rate_ - survival_rate;
730 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
731 set_survival_rate_trend(DECREASING);
732 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
733 set_survival_rate_trend(INCREASING);
735 set_survival_rate_trend(STABLE);
738 survival_rate_ = survival_rate;
741 bool Heap::PerformGarbageCollection(GarbageCollector collector,
743 bool next_gc_likely_to_collect_more = false;
745 if (collector != SCAVENGER) {
746 PROFILE(isolate_, CodeMovingGCEvent());
749 if (FLAG_verify_heap) {
752 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
753 ASSERT(!allocation_allowed_);
754 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
755 global_gc_prologue_callback_();
759 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
761 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
762 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
763 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
767 EnsureFromSpaceIsCommitted();
769 int start_new_space_size = Heap::new_space()->SizeAsInt();
771 if (IsHighSurvivalRate()) {
772 // We speed up the incremental marker if it is running so that it
773 // does not fall behind the rate of promotion, which would cause a
774 // constantly growing old space.
775 incremental_marking()->NotifyOfHighPromotionRate();
778 if (collector == MARK_COMPACTOR) {
779 // Perform mark-sweep with optional compaction.
782 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
783 IsStableOrIncreasingSurvivalTrend();
785 UpdateSurvivalRateTrend(start_new_space_size);
787 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSize();
789 if (high_survival_rate_during_scavenges &&
790 IsStableOrIncreasingSurvivalTrend()) {
791 // Stable high survival rates of young objects both during partial and
792 // full collection indicate that mutator is either building or modifying
793 // a structure with a long lifetime.
794 // In this case we aggressively raise old generation memory limits to
795 // postpone subsequent mark-sweep collection and thus trade memory
796 // space for the mutation speed.
797 old_gen_limit_factor_ = 2;
799 old_gen_limit_factor_ = 1;
802 old_gen_promotion_limit_ =
803 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
804 old_gen_allocation_limit_ =
805 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
807 old_gen_exhausted_ = false;
813 UpdateSurvivalRateTrend(start_new_space_size);
816 if (!new_space_high_promotion_mode_active_ &&
817 new_space_.Capacity() == new_space_.MaximumCapacity() &&
818 IsStableOrIncreasingSurvivalTrend() &&
819 IsHighSurvivalRate()) {
820 // Stable high survival rates even though young generation is at
821 // maximum capacity indicates that most objects will be promoted.
822 // To decrease scavenger pauses and final mark-sweep pauses, we
823 // have to limit maximal capacity of the young generation.
824 new_space_high_promotion_mode_active_ = true;
826 PrintF("Limited new space size due to high promotion rate: %d MB\n",
827 new_space_.InitialCapacity() / MB);
829 } else if (new_space_high_promotion_mode_active_ &&
830 IsStableOrDecreasingSurvivalTrend() &&
831 IsLowSurvivalRate()) {
832 // Decreasing low survival rates might indicate that the above high
833 // promotion mode is over and we should allow the young generation
835 new_space_high_promotion_mode_active_ = false;
837 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
838 new_space_.MaximumCapacity() / MB);
842 if (new_space_high_promotion_mode_active_ &&
843 new_space_.Capacity() > new_space_.InitialCapacity()) {
847 isolate_->counters()->objs_since_last_young()->Set(0);
849 gc_post_processing_depth_++;
850 { DisableAssertNoAllocation allow_allocation;
851 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
852 next_gc_likely_to_collect_more =
853 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
855 gc_post_processing_depth_--;
857 // Update relocatables.
858 Relocatable::PostGarbageCollectionProcessing();
860 if (collector == MARK_COMPACTOR) {
861 // Register the amount of external allocated memory.
862 amount_of_external_allocated_memory_at_last_global_gc_ =
863 amount_of_external_allocated_memory_;
866 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
867 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
868 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
869 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
873 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
874 ASSERT(!allocation_allowed_);
875 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
876 global_gc_epilogue_callback_();
878 if (FLAG_verify_heap) {
882 return next_gc_likely_to_collect_more;
886 void Heap::MarkCompact(GCTracer* tracer) {
887 gc_state_ = MARK_COMPACT;
888 LOG(isolate_, ResourceEvent("markcompact", "begin"));
890 mark_compact_collector_.Prepare(tracer);
893 tracer->set_full_gc_count(ms_count_);
895 MarkCompactPrologue();
897 mark_compact_collector_.CollectGarbage();
899 LOG(isolate_, ResourceEvent("markcompact", "end"));
901 gc_state_ = NOT_IN_GC;
903 isolate_->counters()->objs_since_last_full()->Set(0);
905 contexts_disposed_ = 0;
907 isolate_->set_context_exit_happened(false);
911 void Heap::MarkCompactPrologue() {
912 // At any old GC clear the keyed lookup cache to enable collection of unused
914 isolate_->keyed_lookup_cache()->Clear();
915 isolate_->context_slot_cache()->Clear();
916 isolate_->descriptor_lookup_cache()->Clear();
917 StringSplitCache::Clear(string_split_cache());
919 isolate_->compilation_cache()->MarkCompactPrologue();
921 CompletelyClearInstanceofCache();
923 FlushNumberStringCache();
924 if (FLAG_cleanup_code_caches_at_gc) {
925 polymorphic_code_cache()->set_cache(undefined_value());
928 ClearNormalizedMapCaches();
932 Object* Heap::FindCodeObject(Address a) {
933 return isolate()->inner_pointer_to_code_cache()->
934 GcSafeFindCodeForInnerPointer(a);
938 // Helper class for copying HeapObjects
939 class ScavengeVisitor: public ObjectVisitor {
941 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
943 void VisitPointer(Object** p) { ScavengePointer(p); }
945 void VisitPointers(Object** start, Object** end) {
946 // Copy all HeapObject pointers in [start, end)
947 for (Object** p = start; p < end; p++) ScavengePointer(p);
951 void ScavengePointer(Object** p) {
953 if (!heap_->InNewSpace(object)) return;
954 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
955 reinterpret_cast<HeapObject*>(object));
963 // Visitor class to verify pointers in code or data space do not point into
965 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
967 void VisitPointers(Object** start, Object**end) {
968 for (Object** current = start; current < end; current++) {
969 if ((*current)->IsHeapObject()) {
970 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
977 static void VerifyNonPointerSpacePointers() {
978 // Verify that there are no pointers to new space in spaces where we
979 // do not expect them.
980 VerifyNonPointerSpacePointersVisitor v;
981 HeapObjectIterator code_it(HEAP->code_space());
982 for (HeapObject* object = code_it.Next();
983 object != NULL; object = code_it.Next())
986 // The old data space was normally swept conservatively so that the iterator
987 // doesn't work, so we normally skip the next bit.
988 if (!HEAP->old_data_space()->was_swept_conservatively()) {
989 HeapObjectIterator data_it(HEAP->old_data_space());
990 for (HeapObject* object = data_it.Next();
991 object != NULL; object = data_it.Next())
998 void Heap::CheckNewSpaceExpansionCriteria() {
999 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1000 survived_since_last_expansion_ > new_space_.Capacity() &&
1001 !new_space_high_promotion_mode_active_) {
1002 // Grow the size of new space if there is room to grow, enough data
1003 // has survived scavenge since the last expansion and we are not in
1004 // high promotion mode.
1006 survived_since_last_expansion_ = 0;
1011 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1012 return heap->InNewSpace(*p) &&
1013 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1017 void Heap::ScavengeStoreBufferCallback(
1020 StoreBufferEvent event) {
1021 heap->store_buffer_rebuilder_.Callback(page, event);
1025 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1026 if (event == kStoreBufferStartScanningPagesEvent) {
1027 start_of_current_page_ = NULL;
1028 current_page_ = NULL;
1029 } else if (event == kStoreBufferScanningPageEvent) {
1030 if (current_page_ != NULL) {
1031 // If this page already overflowed the store buffer during this iteration.
1032 if (current_page_->scan_on_scavenge()) {
1033 // Then we should wipe out the entries that have been added for it.
1034 store_buffer_->SetTop(start_of_current_page_);
1035 } else if (store_buffer_->Top() - start_of_current_page_ >=
1036 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1037 // Did we find too many pointers in the previous page? The heuristic is
1038 // that no page can take more then 1/5 the remaining slots in the store
1040 current_page_->set_scan_on_scavenge(true);
1041 store_buffer_->SetTop(start_of_current_page_);
1043 // In this case the page we scanned took a reasonable number of slots in
1044 // the store buffer. It has now been rehabilitated and is no longer
1045 // marked scan_on_scavenge.
1046 ASSERT(!current_page_->scan_on_scavenge());
1049 start_of_current_page_ = store_buffer_->Top();
1050 current_page_ = page;
1051 } else if (event == kStoreBufferFullEvent) {
1052 // The current page overflowed the store buffer again. Wipe out its entries
1053 // in the store buffer and mark it scan-on-scavenge again. This may happen
1054 // several times while scanning.
1055 if (current_page_ == NULL) {
1056 // Store Buffer overflowed while scanning promoted objects. These are not
1057 // in any particular page, though they are likely to be clustered by the
1058 // allocation routines.
1059 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1061 // Store Buffer overflowed while scanning a particular old space page for
1062 // pointers to new space.
1063 ASSERT(current_page_ == page);
1064 ASSERT(page != NULL);
1065 current_page_->set_scan_on_scavenge(true);
1066 ASSERT(start_of_current_page_ != store_buffer_->Top());
1067 store_buffer_->SetTop(start_of_current_page_);
1075 void PromotionQueue::Initialize() {
1076 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1077 // entries (where each is a pair of intptr_t). This allows us to simplify
1078 // the test fpr when to switch pages.
1079 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1081 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1083 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1084 emergency_stack_ = NULL;
1089 void PromotionQueue::RelocateQueueHead() {
1090 ASSERT(emergency_stack_ == NULL);
1092 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1093 intptr_t* head_start = rear_;
1094 intptr_t* head_end =
1095 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1098 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1100 emergency_stack_ = new List<Entry>(2 * entries_count);
1102 while (head_start != head_end) {
1103 int size = static_cast<int>(*(head_start++));
1104 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1105 emergency_stack_->Add(Entry(obj, size));
1111 void Heap::Scavenge() {
1113 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1116 gc_state_ = SCAVENGE;
1118 // Implements Cheney's copying algorithm
1119 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1121 // Clear descriptor cache.
1122 isolate_->descriptor_lookup_cache()->Clear();
1124 // Used for updating survived_since_last_expansion_ at function end.
1125 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1127 CheckNewSpaceExpansionCriteria();
1129 SelectScavengingVisitorsTable();
1131 incremental_marking()->PrepareForScavenge();
1133 AdvanceSweepers(static_cast<int>(new_space_.Size()));
1135 // Flip the semispaces. After flipping, to space is empty, from space has
1138 new_space_.ResetAllocationInfo();
1140 // We need to sweep newly copied objects which can be either in the
1141 // to space or promoted to the old generation. For to-space
1142 // objects, we treat the bottom of the to space as a queue. Newly
1143 // copied and unswept objects lie between a 'front' mark and the
1144 // allocation pointer.
1146 // Promoted objects can go into various old-generation spaces, and
1147 // can be allocated internally in the spaces (from the free list).
1148 // We treat the top of the to space as a queue of addresses of
1149 // promoted objects. The addresses of newly promoted and unswept
1150 // objects lie between a 'front' mark and a 'rear' mark that is
1151 // updated as a side effect of promoting an object.
1153 // There is guaranteed to be enough room at the top of the to space
1154 // for the addresses of promoted objects: every object promoted
1155 // frees up its size in bytes from the top of the new space, and
1156 // objects are at least one pointer in size.
1157 Address new_space_front = new_space_.ToSpaceStart();
1158 promotion_queue_.Initialize();
1161 store_buffer()->Clean();
1164 ScavengeVisitor scavenge_visitor(this);
1166 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1168 // Copy objects reachable from the old generation.
1170 StoreBufferRebuildScope scope(this,
1172 &ScavengeStoreBufferCallback);
1173 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1176 // Copy objects reachable from cells by scavenging cell values directly.
1177 HeapObjectIterator cell_iterator(cell_space_);
1178 for (HeapObject* cell = cell_iterator.Next();
1179 cell != NULL; cell = cell_iterator.Next()) {
1180 if (cell->IsJSGlobalPropertyCell()) {
1181 Address value_address =
1182 reinterpret_cast<Address>(cell) +
1183 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1184 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1188 // Scavenge object reachable from the global contexts list directly.
1189 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1191 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1192 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1193 &IsUnscavengedHeapObject);
1194 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1196 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1198 UpdateNewSpaceReferencesInExternalStringTable(
1199 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1201 promotion_queue_.Destroy();
1203 LiveObjectList::UpdateReferencesForScavengeGC();
1204 if (!FLAG_watch_ic_patching) {
1205 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1207 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1209 ASSERT(new_space_front == new_space_.top());
1212 new_space_.set_age_mark(new_space_.top());
1214 new_space_.LowerInlineAllocationLimit(
1215 new_space_.inline_allocation_limit_step());
1217 // Update how much has survived scavenge.
1218 IncrementYoungSurvivorsCounter(static_cast<int>(
1219 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1221 LOG(isolate_, ResourceEvent("scavenge", "end"));
1223 gc_state_ = NOT_IN_GC;
1225 scavenges_since_last_idle_round_++;
1229 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1231 MapWord first_word = HeapObject::cast(*p)->map_word();
1233 if (!first_word.IsForwardingAddress()) {
1234 // Unreachable external string can be finalized.
1235 heap->FinalizeExternalString(String::cast(*p));
1239 // String is still reachable.
1240 return String::cast(first_word.ToForwardingAddress());
1244 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1245 ExternalStringTableUpdaterCallback updater_func) {
1246 if (FLAG_verify_heap) {
1247 external_string_table_.Verify();
1250 if (external_string_table_.new_space_strings_.is_empty()) return;
1252 Object** start = &external_string_table_.new_space_strings_[0];
1253 Object** end = start + external_string_table_.new_space_strings_.length();
1254 Object** last = start;
1256 for (Object** p = start; p < end; ++p) {
1257 ASSERT(InFromSpace(*p));
1258 String* target = updater_func(this, p);
1260 if (target == NULL) continue;
1262 ASSERT(target->IsExternalString());
1264 if (InNewSpace(target)) {
1265 // String is still in new space. Update the table entry.
1269 // String got promoted. Move it to the old string list.
1270 external_string_table_.AddOldString(target);
1274 ASSERT(last <= end);
1275 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1279 void Heap::UpdateReferencesInExternalStringTable(
1280 ExternalStringTableUpdaterCallback updater_func) {
1282 // Update old space string references.
1283 if (external_string_table_.old_space_strings_.length() > 0) {
1284 Object** start = &external_string_table_.old_space_strings_[0];
1285 Object** end = start + external_string_table_.old_space_strings_.length();
1286 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1289 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1293 static Object* ProcessFunctionWeakReferences(Heap* heap,
1295 WeakObjectRetainer* retainer) {
1296 Object* undefined = heap->undefined_value();
1297 Object* head = undefined;
1298 JSFunction* tail = NULL;
1299 Object* candidate = function;
1300 while (candidate != undefined) {
1301 // Check whether to keep the candidate in the list.
1302 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1303 Object* retain = retainer->RetainAs(candidate);
1304 if (retain != NULL) {
1305 if (head == undefined) {
1306 // First element in the list.
1309 // Subsequent elements in the list.
1310 ASSERT(tail != NULL);
1311 tail->set_next_function_link(retain);
1313 // Retained function is new tail.
1314 candidate_function = reinterpret_cast<JSFunction*>(retain);
1315 tail = candidate_function;
1317 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1319 if (retain == undefined) break;
1322 // Move to next element in the list.
1323 candidate = candidate_function->next_function_link();
1326 // Terminate the list if there is one or more elements.
1328 tail->set_next_function_link(undefined);
1335 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1336 Object* undefined = undefined_value();
1337 Object* head = undefined;
1338 Context* tail = NULL;
1339 Object* candidate = global_contexts_list_;
1340 while (candidate != undefined) {
1341 // Check whether to keep the candidate in the list.
1342 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1343 Object* retain = retainer->RetainAs(candidate);
1344 if (retain != NULL) {
1345 if (head == undefined) {
1346 // First element in the list.
1349 // Subsequent elements in the list.
1350 ASSERT(tail != NULL);
1351 tail->set_unchecked(this,
1352 Context::NEXT_CONTEXT_LINK,
1354 UPDATE_WRITE_BARRIER);
1356 // Retained context is new tail.
1357 candidate_context = reinterpret_cast<Context*>(retain);
1358 tail = candidate_context;
1360 if (retain == undefined) break;
1362 // Process the weak list of optimized functions for the context.
1363 Object* function_list_head =
1364 ProcessFunctionWeakReferences(
1366 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1368 candidate_context->set_unchecked(this,
1369 Context::OPTIMIZED_FUNCTIONS_LIST,
1371 UPDATE_WRITE_BARRIER);
1374 // Move to next element in the list.
1375 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1378 // Terminate the list if there is one or more elements.
1380 tail->set_unchecked(this,
1381 Context::NEXT_CONTEXT_LINK,
1382 Heap::undefined_value(),
1383 UPDATE_WRITE_BARRIER);
1386 // Update the head of the list of contexts.
1387 global_contexts_list_ = head;
1391 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1392 AssertNoAllocation no_allocation;
1394 class VisitorAdapter : public ObjectVisitor {
1396 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1397 : visitor_(visitor) {}
1398 virtual void VisitPointers(Object** start, Object** end) {
1399 for (Object** p = start; p < end; p++) {
1400 if ((*p)->IsExternalString()) {
1401 visitor_->VisitExternalString(Utils::ToLocal(
1402 Handle<String>(String::cast(*p))));
1407 v8::ExternalResourceVisitor* visitor_;
1408 } visitor_adapter(visitor);
1409 external_string_table_.Iterate(&visitor_adapter);
1413 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1415 static inline void VisitPointer(Heap* heap, Object** p) {
1416 Object* object = *p;
1417 if (!heap->InNewSpace(object)) return;
1418 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1419 reinterpret_cast<HeapObject*>(object));
1424 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1425 Address new_space_front) {
1427 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1428 // The addresses new_space_front and new_space_.top() define a
1429 // queue of unprocessed copied objects. Process them until the
1431 while (new_space_front != new_space_.top()) {
1432 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1433 HeapObject* object = HeapObject::FromAddress(new_space_front);
1435 NewSpaceScavenger::IterateBody(object->map(), object);
1438 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1442 // Promote and process all the to-be-promoted objects.
1444 StoreBufferRebuildScope scope(this,
1446 &ScavengeStoreBufferCallback);
1447 while (!promotion_queue()->is_empty()) {
1450 promotion_queue()->remove(&target, &size);
1452 // Promoted object might be already partially visited
1453 // during old space pointer iteration. Thus we search specificly
1454 // for pointers to from semispace instead of looking for pointers
1456 ASSERT(!target->IsMap());
1457 IterateAndMarkPointersToFromSpace(target->address(),
1458 target->address() + size,
1463 // Take another spin if there are now unswept objects in new space
1464 // (there are currently no more unswept promoted objects).
1465 } while (new_space_front != new_space_.top());
1467 return new_space_front;
1471 enum LoggingAndProfiling {
1472 LOGGING_AND_PROFILING_ENABLED,
1473 LOGGING_AND_PROFILING_DISABLED
1477 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1480 template<MarksHandling marks_handling,
1481 LoggingAndProfiling logging_and_profiling_mode>
1482 class ScavengingVisitor : public StaticVisitorBase {
1484 static void Initialize() {
1485 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1486 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1487 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1488 table_.Register(kVisitByteArray, &EvacuateByteArray);
1489 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1490 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1492 table_.Register(kVisitGlobalContext,
1493 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1494 template VisitSpecialized<Context::kSize>);
1496 table_.Register(kVisitConsString,
1497 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1498 template VisitSpecialized<ConsString::kSize>);
1500 table_.Register(kVisitSlicedString,
1501 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1502 template VisitSpecialized<SlicedString::kSize>);
1504 table_.Register(kVisitSharedFunctionInfo,
1505 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1506 template VisitSpecialized<SharedFunctionInfo::kSize>);
1508 table_.Register(kVisitJSWeakMap,
1509 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1512 table_.Register(kVisitJSRegExp,
1513 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1516 if (marks_handling == IGNORE_MARKS) {
1517 table_.Register(kVisitJSFunction,
1518 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1519 template VisitSpecialized<JSFunction::kSize>);
1521 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1524 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1526 kVisitDataObjectGeneric>();
1528 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1530 kVisitJSObjectGeneric>();
1532 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1534 kVisitStructGeneric>();
1537 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1542 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1543 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1545 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1546 bool should_record = false;
1548 should_record = FLAG_heap_stats;
1550 should_record = should_record || FLAG_log_gc;
1551 if (should_record) {
1552 if (heap->new_space()->Contains(obj)) {
1553 heap->new_space()->RecordAllocation(obj);
1555 heap->new_space()->RecordPromotion(obj);
1560 // Helper function used by CopyObject to copy a source object to an
1561 // allocated target object and update the forwarding pointer in the source
1562 // object. Returns the target object.
1563 INLINE(static void MigrateObject(Heap* heap,
1567 // Copy the content of source to target.
1568 heap->CopyBlock(target->address(), source->address(), size);
1570 // Set the forwarding address.
1571 source->set_map_word(MapWord::FromForwardingAddress(target));
1573 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1574 // Update NewSpace stats if necessary.
1575 RecordCopiedObject(heap, target);
1576 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1577 Isolate* isolate = heap->isolate();
1578 if (isolate->logger()->is_logging() ||
1579 CpuProfiler::is_profiling(isolate)) {
1580 if (target->IsSharedFunctionInfo()) {
1581 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1582 source->address(), target->address()));
1587 if (marks_handling == TRANSFER_MARKS) {
1588 if (Marking::TransferColor(source, target)) {
1589 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1594 template<ObjectContents object_contents, SizeRestriction size_restriction>
1595 static inline void EvacuateObject(Map* map,
1599 SLOW_ASSERT((size_restriction != SMALL) ||
1600 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1601 SLOW_ASSERT(object->Size() == object_size);
1603 Heap* heap = map->GetHeap();
1604 if (heap->ShouldBePromoted(object->address(), object_size)) {
1605 MaybeObject* maybe_result;
1607 if ((size_restriction != SMALL) &&
1608 (object_size > Page::kMaxNonCodeHeapObjectSize)) {
1609 maybe_result = heap->lo_space()->AllocateRaw(object_size,
1612 if (object_contents == DATA_OBJECT) {
1613 maybe_result = heap->old_data_space()->AllocateRaw(object_size);
1615 maybe_result = heap->old_pointer_space()->AllocateRaw(object_size);
1619 Object* result = NULL; // Initialization to please compiler.
1620 if (maybe_result->ToObject(&result)) {
1621 HeapObject* target = HeapObject::cast(result);
1623 // Order is important: slot might be inside of the target if target
1624 // was allocated over a dead object and slot comes from the store
1627 MigrateObject(heap, object, target, object_size);
1629 if (object_contents == POINTER_OBJECT) {
1630 heap->promotion_queue()->insert(target, object_size);
1633 heap->tracer()->increment_promoted_objects_size(object_size);
1637 MaybeObject* allocation = heap->new_space()->AllocateRaw(object_size);
1638 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1639 Object* result = allocation->ToObjectUnchecked();
1640 HeapObject* target = HeapObject::cast(result);
1642 // Order is important: slot might be inside of the target if target
1643 // was allocated over a dead object and slot comes from the store
1646 MigrateObject(heap, object, target, object_size);
1651 static inline void EvacuateJSFunction(Map* map,
1653 HeapObject* object) {
1654 ObjectEvacuationStrategy<POINTER_OBJECT>::
1655 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1657 HeapObject* target = *slot;
1658 MarkBit mark_bit = Marking::MarkBitFrom(target);
1659 if (Marking::IsBlack(mark_bit)) {
1660 // This object is black and it might not be rescanned by marker.
1661 // We should explicitly record code entry slot for compaction because
1662 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1663 // miss it as it is not HeapObject-tagged.
1664 Address code_entry_slot =
1665 target->address() + JSFunction::kCodeEntryOffset;
1666 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1667 map->GetHeap()->mark_compact_collector()->
1668 RecordCodeEntrySlot(code_entry_slot, code);
1673 static inline void EvacuateFixedArray(Map* map,
1675 HeapObject* object) {
1676 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1677 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1684 static inline void EvacuateFixedDoubleArray(Map* map,
1686 HeapObject* object) {
1687 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1688 int object_size = FixedDoubleArray::SizeFor(length);
1689 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map,
1696 static inline void EvacuateByteArray(Map* map,
1698 HeapObject* object) {
1699 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1700 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1704 static inline void EvacuateSeqAsciiString(Map* map,
1706 HeapObject* object) {
1707 int object_size = SeqAsciiString::cast(object)->
1708 SeqAsciiStringSize(map->instance_type());
1709 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1713 static inline void EvacuateSeqTwoByteString(Map* map,
1715 HeapObject* object) {
1716 int object_size = SeqTwoByteString::cast(object)->
1717 SeqTwoByteStringSize(map->instance_type());
1718 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1722 static inline bool IsShortcutCandidate(int type) {
1723 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1726 static inline void EvacuateShortcutCandidate(Map* map,
1728 HeapObject* object) {
1729 ASSERT(IsShortcutCandidate(map->instance_type()));
1731 Heap* heap = map->GetHeap();
1733 if (marks_handling == IGNORE_MARKS &&
1734 ConsString::cast(object)->unchecked_second() ==
1735 heap->empty_string()) {
1737 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1741 if (!heap->InNewSpace(first)) {
1742 object->set_map_word(MapWord::FromForwardingAddress(first));
1746 MapWord first_word = first->map_word();
1747 if (first_word.IsForwardingAddress()) {
1748 HeapObject* target = first_word.ToForwardingAddress();
1751 object->set_map_word(MapWord::FromForwardingAddress(target));
1755 heap->DoScavengeObject(first->map(), slot, first);
1756 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1760 int object_size = ConsString::kSize;
1761 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
1764 template<ObjectContents object_contents>
1765 class ObjectEvacuationStrategy {
1767 template<int object_size>
1768 static inline void VisitSpecialized(Map* map,
1770 HeapObject* object) {
1771 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1774 static inline void Visit(Map* map,
1776 HeapObject* object) {
1777 int object_size = map->instance_size();
1778 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1782 static VisitorDispatchTable<ScavengingCallback> table_;
1786 template<MarksHandling marks_handling,
1787 LoggingAndProfiling logging_and_profiling_mode>
1788 VisitorDispatchTable<ScavengingCallback>
1789 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1792 static void InitializeScavengingVisitorsTables() {
1793 ScavengingVisitor<TRANSFER_MARKS,
1794 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1795 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1796 ScavengingVisitor<TRANSFER_MARKS,
1797 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1798 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1802 void Heap::SelectScavengingVisitorsTable() {
1803 bool logging_and_profiling =
1804 isolate()->logger()->is_logging() ||
1805 CpuProfiler::is_profiling(isolate()) ||
1806 (isolate()->heap_profiler() != NULL &&
1807 isolate()->heap_profiler()->is_profiling());
1809 if (!incremental_marking()->IsMarking()) {
1810 if (!logging_and_profiling) {
1811 scavenging_visitors_table_.CopyFrom(
1812 ScavengingVisitor<IGNORE_MARKS,
1813 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1815 scavenging_visitors_table_.CopyFrom(
1816 ScavengingVisitor<IGNORE_MARKS,
1817 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1820 if (!logging_and_profiling) {
1821 scavenging_visitors_table_.CopyFrom(
1822 ScavengingVisitor<TRANSFER_MARKS,
1823 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1825 scavenging_visitors_table_.CopyFrom(
1826 ScavengingVisitor<TRANSFER_MARKS,
1827 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1830 if (incremental_marking()->IsCompacting()) {
1831 // When compacting forbid short-circuiting of cons-strings.
1832 // Scavenging code relies on the fact that new space object
1833 // can't be evacuated into evacuation candidate but
1834 // short-circuiting violates this assumption.
1835 scavenging_visitors_table_.Register(
1836 StaticVisitorBase::kVisitShortcutCandidate,
1837 scavenging_visitors_table_.GetVisitorById(
1838 StaticVisitorBase::kVisitConsString));
1844 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1845 SLOW_ASSERT(HEAP->InFromSpace(object));
1846 MapWord first_word = object->map_word();
1847 SLOW_ASSERT(!first_word.IsForwardingAddress());
1848 Map* map = first_word.ToMap();
1849 map->GetHeap()->DoScavengeObject(map, p, object);
1853 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1854 int instance_size) {
1856 { MaybeObject* maybe_result = AllocateRawMap();
1857 if (!maybe_result->ToObject(&result)) return maybe_result;
1860 // Map::cast cannot be used due to uninitialized map field.
1861 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1862 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1863 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1864 reinterpret_cast<Map*>(result)->set_visitor_id(
1865 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1866 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
1867 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
1868 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1869 reinterpret_cast<Map*>(result)->set_bit_field(0);
1870 reinterpret_cast<Map*>(result)->set_bit_field2(0);
1875 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
1877 ElementsKind elements_kind) {
1879 { MaybeObject* maybe_result = AllocateRawMap();
1880 if (!maybe_result->ToObject(&result)) return maybe_result;
1883 Map* map = reinterpret_cast<Map*>(result);
1884 map->set_map_no_write_barrier(meta_map());
1885 map->set_instance_type(instance_type);
1886 map->set_visitor_id(
1887 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1888 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
1889 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
1890 map->set_instance_size(instance_size);
1891 map->set_inobject_properties(0);
1892 map->set_pre_allocated_property_fields(0);
1893 map->init_instance_descriptors();
1894 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1895 map->set_prototype_transitions(empty_fixed_array(), SKIP_WRITE_BARRIER);
1896 map->set_unused_property_fields(0);
1897 map->set_bit_field(0);
1898 map->set_bit_field2(1 << Map::kIsExtensible);
1899 map->set_elements_kind(elements_kind);
1901 // If the map object is aligned fill the padding area with Smi 0 objects.
1902 if (Map::kPadStart < Map::kSize) {
1903 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1905 Map::kSize - Map::kPadStart);
1911 MaybeObject* Heap::AllocateCodeCache() {
1913 { MaybeObject* maybe_result = AllocateStruct(CODE_CACHE_TYPE);
1914 if (!maybe_result->ToObject(&result)) return maybe_result;
1916 CodeCache* code_cache = CodeCache::cast(result);
1917 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
1918 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
1923 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
1924 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
1928 MaybeObject* Heap::AllocateAccessorPair() {
1930 { MaybeObject* maybe_result = AllocateStruct(ACCESSOR_PAIR_TYPE);
1931 if (!maybe_result->ToObject(&result)) return maybe_result;
1933 AccessorPair* accessors = AccessorPair::cast(result);
1934 // Later we will have to distinguish between undefined and the hole...
1935 // accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
1936 // accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
1941 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
1942 TypeFeedbackInfo* info;
1943 { MaybeObject* maybe_result = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
1944 if (!maybe_result->To(&info)) return maybe_result;
1946 info->set_ic_total_count(0);
1947 info->set_ic_with_typeinfo_count(0);
1948 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
1949 SKIP_WRITE_BARRIER);
1954 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
1955 AliasedArgumentsEntry* entry;
1956 { MaybeObject* maybe_result = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
1957 if (!maybe_result->To(&entry)) return maybe_result;
1959 entry->set_aliased_context_slot(aliased_context_slot);
1964 const Heap::StringTypeTable Heap::string_type_table[] = {
1965 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1966 {type, size, k##camel_name##MapRootIndex},
1967 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1968 #undef STRING_TYPE_ELEMENT
1972 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1973 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1974 {contents, k##name##RootIndex},
1975 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1976 #undef CONSTANT_SYMBOL_ELEMENT
1980 const Heap::StructTable Heap::struct_table[] = {
1981 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1982 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1983 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1984 #undef STRUCT_TABLE_ELEMENT
1988 bool Heap::CreateInitialMaps() {
1990 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1991 if (!maybe_obj->ToObject(&obj)) return false;
1993 // Map::cast cannot be used due to uninitialized map field.
1994 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1995 set_meta_map(new_meta_map);
1996 new_meta_map->set_map(new_meta_map);
1998 { MaybeObject* maybe_obj =
1999 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2000 if (!maybe_obj->ToObject(&obj)) return false;
2002 set_fixed_array_map(Map::cast(obj));
2004 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2005 if (!maybe_obj->ToObject(&obj)) return false;
2007 set_oddball_map(Map::cast(obj));
2009 // Allocate the empty array.
2010 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2011 if (!maybe_obj->ToObject(&obj)) return false;
2013 set_empty_fixed_array(FixedArray::cast(obj));
2015 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2016 if (!maybe_obj->ToObject(&obj)) return false;
2018 set_null_value(Oddball::cast(obj));
2019 Oddball::cast(obj)->set_kind(Oddball::kNull);
2021 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2022 if (!maybe_obj->ToObject(&obj)) return false;
2024 set_undefined_value(Oddball::cast(obj));
2025 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2026 ASSERT(!InNewSpace(undefined_value()));
2028 // Allocate the empty descriptor array.
2029 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2030 if (!maybe_obj->ToObject(&obj)) return false;
2032 set_empty_descriptor_array(DescriptorArray::cast(obj));
2034 // Fix the instance_descriptors for the existing maps.
2035 meta_map()->init_instance_descriptors();
2036 meta_map()->set_code_cache(empty_fixed_array());
2037 meta_map()->set_prototype_transitions(empty_fixed_array());
2039 fixed_array_map()->init_instance_descriptors();
2040 fixed_array_map()->set_code_cache(empty_fixed_array());
2041 fixed_array_map()->set_prototype_transitions(empty_fixed_array());
2043 oddball_map()->init_instance_descriptors();
2044 oddball_map()->set_code_cache(empty_fixed_array());
2045 oddball_map()->set_prototype_transitions(empty_fixed_array());
2047 // Fix prototype object for existing maps.
2048 meta_map()->set_prototype(null_value());
2049 meta_map()->set_constructor(null_value());
2051 fixed_array_map()->set_prototype(null_value());
2052 fixed_array_map()->set_constructor(null_value());
2054 oddball_map()->set_prototype(null_value());
2055 oddball_map()->set_constructor(null_value());
2057 { MaybeObject* maybe_obj =
2058 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2059 if (!maybe_obj->ToObject(&obj)) return false;
2061 set_fixed_cow_array_map(Map::cast(obj));
2062 ASSERT(fixed_array_map() != fixed_cow_array_map());
2064 { MaybeObject* maybe_obj =
2065 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2066 if (!maybe_obj->ToObject(&obj)) return false;
2068 set_scope_info_map(Map::cast(obj));
2070 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2071 if (!maybe_obj->ToObject(&obj)) return false;
2073 set_heap_number_map(Map::cast(obj));
2075 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2076 if (!maybe_obj->ToObject(&obj)) return false;
2078 set_foreign_map(Map::cast(obj));
2080 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2081 const StringTypeTable& entry = string_type_table[i];
2082 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2083 if (!maybe_obj->ToObject(&obj)) return false;
2085 roots_[entry.index] = Map::cast(obj);
2088 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2089 if (!maybe_obj->ToObject(&obj)) return false;
2091 set_undetectable_string_map(Map::cast(obj));
2092 Map::cast(obj)->set_is_undetectable();
2094 { MaybeObject* maybe_obj =
2095 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2096 if (!maybe_obj->ToObject(&obj)) return false;
2098 set_undetectable_ascii_string_map(Map::cast(obj));
2099 Map::cast(obj)->set_is_undetectable();
2101 { MaybeObject* maybe_obj =
2102 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2103 if (!maybe_obj->ToObject(&obj)) return false;
2105 set_fixed_double_array_map(Map::cast(obj));
2107 { MaybeObject* maybe_obj =
2108 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2109 if (!maybe_obj->ToObject(&obj)) return false;
2111 set_byte_array_map(Map::cast(obj));
2113 { MaybeObject* maybe_obj =
2114 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2115 if (!maybe_obj->ToObject(&obj)) return false;
2117 set_free_space_map(Map::cast(obj));
2119 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2120 if (!maybe_obj->ToObject(&obj)) return false;
2122 set_empty_byte_array(ByteArray::cast(obj));
2124 { MaybeObject* maybe_obj =
2125 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2126 if (!maybe_obj->ToObject(&obj)) return false;
2128 set_external_pixel_array_map(Map::cast(obj));
2130 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2131 ExternalArray::kAlignedSize);
2132 if (!maybe_obj->ToObject(&obj)) return false;
2134 set_external_byte_array_map(Map::cast(obj));
2136 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2137 ExternalArray::kAlignedSize);
2138 if (!maybe_obj->ToObject(&obj)) return false;
2140 set_external_unsigned_byte_array_map(Map::cast(obj));
2142 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2143 ExternalArray::kAlignedSize);
2144 if (!maybe_obj->ToObject(&obj)) return false;
2146 set_external_short_array_map(Map::cast(obj));
2148 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2149 ExternalArray::kAlignedSize);
2150 if (!maybe_obj->ToObject(&obj)) return false;
2152 set_external_unsigned_short_array_map(Map::cast(obj));
2154 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2155 ExternalArray::kAlignedSize);
2156 if (!maybe_obj->ToObject(&obj)) return false;
2158 set_external_int_array_map(Map::cast(obj));
2160 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2161 ExternalArray::kAlignedSize);
2162 if (!maybe_obj->ToObject(&obj)) return false;
2164 set_external_unsigned_int_array_map(Map::cast(obj));
2166 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2167 ExternalArray::kAlignedSize);
2168 if (!maybe_obj->ToObject(&obj)) return false;
2170 set_external_float_array_map(Map::cast(obj));
2172 { MaybeObject* maybe_obj =
2173 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2174 if (!maybe_obj->ToObject(&obj)) return false;
2176 set_non_strict_arguments_elements_map(Map::cast(obj));
2178 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2179 ExternalArray::kAlignedSize);
2180 if (!maybe_obj->ToObject(&obj)) return false;
2182 set_external_double_array_map(Map::cast(obj));
2184 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2185 if (!maybe_obj->ToObject(&obj)) return false;
2187 set_code_map(Map::cast(obj));
2189 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2190 JSGlobalPropertyCell::kSize);
2191 if (!maybe_obj->ToObject(&obj)) return false;
2193 set_global_property_cell_map(Map::cast(obj));
2195 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2196 if (!maybe_obj->ToObject(&obj)) return false;
2198 set_one_pointer_filler_map(Map::cast(obj));
2200 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2201 if (!maybe_obj->ToObject(&obj)) return false;
2203 set_two_pointer_filler_map(Map::cast(obj));
2205 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2206 const StructTable& entry = struct_table[i];
2207 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2208 if (!maybe_obj->ToObject(&obj)) return false;
2210 roots_[entry.index] = Map::cast(obj);
2213 { MaybeObject* maybe_obj =
2214 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2215 if (!maybe_obj->ToObject(&obj)) return false;
2217 set_hash_table_map(Map::cast(obj));
2219 { MaybeObject* maybe_obj =
2220 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2221 if (!maybe_obj->ToObject(&obj)) return false;
2223 set_function_context_map(Map::cast(obj));
2225 { MaybeObject* maybe_obj =
2226 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2227 if (!maybe_obj->ToObject(&obj)) return false;
2229 set_catch_context_map(Map::cast(obj));
2231 { MaybeObject* maybe_obj =
2232 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2233 if (!maybe_obj->ToObject(&obj)) return false;
2235 set_with_context_map(Map::cast(obj));
2237 { MaybeObject* maybe_obj =
2238 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2239 if (!maybe_obj->ToObject(&obj)) return false;
2241 set_block_context_map(Map::cast(obj));
2243 { MaybeObject* maybe_obj =
2244 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2245 if (!maybe_obj->ToObject(&obj)) return false;
2247 set_module_context_map(Map::cast(obj));
2249 { MaybeObject* maybe_obj =
2250 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2251 if (!maybe_obj->ToObject(&obj)) return false;
2253 Map* global_context_map = Map::cast(obj);
2254 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2255 set_global_context_map(global_context_map);
2257 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2258 SharedFunctionInfo::kAlignedSize);
2259 if (!maybe_obj->ToObject(&obj)) return false;
2261 set_shared_function_info_map(Map::cast(obj));
2263 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2264 JSMessageObject::kSize);
2265 if (!maybe_obj->ToObject(&obj)) return false;
2267 set_message_object_map(Map::cast(obj));
2269 ASSERT(!InNewSpace(empty_fixed_array()));
2274 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2275 // Statically ensure that it is safe to allocate heap numbers in paged
2277 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2278 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2281 { MaybeObject* maybe_result =
2282 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2283 if (!maybe_result->ToObject(&result)) return maybe_result;
2286 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2287 HeapNumber::cast(result)->set_value(value);
2292 MaybeObject* Heap::AllocateHeapNumber(double value) {
2293 // Use general version, if we're forced to always allocate.
2294 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2296 // This version of AllocateHeapNumber is optimized for
2297 // allocation in new space.
2298 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2299 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2301 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2302 if (!maybe_result->ToObject(&result)) return maybe_result;
2304 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2305 HeapNumber::cast(result)->set_value(value);
2310 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2312 { MaybeObject* maybe_result = AllocateRawCell();
2313 if (!maybe_result->ToObject(&result)) return maybe_result;
2315 HeapObject::cast(result)->set_map_no_write_barrier(
2316 global_property_cell_map());
2317 JSGlobalPropertyCell::cast(result)->set_value(value);
2322 MaybeObject* Heap::CreateOddball(const char* to_string,
2326 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2327 if (!maybe_result->ToObject(&result)) return maybe_result;
2329 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2333 bool Heap::CreateApiObjects() {
2336 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2337 if (!maybe_obj->ToObject(&obj)) return false;
2339 // Don't use Smi-only elements optimizations for objects with the neander
2340 // map. There are too many cases where element values are set directly with a
2341 // bottleneck to trap the Smi-only -> fast elements transition, and there
2342 // appears to be no benefit for optimize this case.
2343 Map* new_neander_map = Map::cast(obj);
2344 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2345 set_neander_map(new_neander_map);
2347 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2348 if (!maybe_obj->ToObject(&obj)) return false;
2351 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2352 if (!maybe_elements->ToObject(&elements)) return false;
2354 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2355 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2356 set_message_listeners(JSObject::cast(obj));
2362 void Heap::CreateJSEntryStub() {
2364 set_js_entry_code(*stub.GetCode());
2368 void Heap::CreateJSConstructEntryStub() {
2369 JSConstructEntryStub stub;
2370 set_js_construct_entry_code(*stub.GetCode());
2374 void Heap::CreateFixedStubs() {
2375 // Here we create roots for fixed stubs. They are needed at GC
2376 // for cooking and uncooking (check out frames.cc).
2377 // The eliminates the need for doing dictionary lookup in the
2378 // stub cache for these stubs.
2380 // gcc-4.4 has problem generating correct code of following snippet:
2381 // { JSEntryStub stub;
2382 // js_entry_code_ = *stub.GetCode();
2384 // { JSConstructEntryStub stub;
2385 // js_construct_entry_code_ = *stub.GetCode();
2387 // To workaround the problem, make separate functions without inlining.
2388 Heap::CreateJSEntryStub();
2389 Heap::CreateJSConstructEntryStub();
2391 // Create stubs that should be there, so we don't unexpectedly have to
2392 // create them if we need them during the creation of another stub.
2393 // Stub creation mixes raw pointers and handles in an unsafe manner so
2394 // we cannot create stubs while we are creating stubs.
2395 CodeStub::GenerateStubsAheadOfTime();
2399 bool Heap::CreateInitialObjects() {
2402 // The -0 value must be set before NumberFromDouble works.
2403 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2404 if (!maybe_obj->ToObject(&obj)) return false;
2406 set_minus_zero_value(HeapNumber::cast(obj));
2407 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2409 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2410 if (!maybe_obj->ToObject(&obj)) return false;
2412 set_nan_value(HeapNumber::cast(obj));
2414 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2415 if (!maybe_obj->ToObject(&obj)) return false;
2417 set_infinity_value(HeapNumber::cast(obj));
2419 // The hole has not been created yet, but we want to put something
2420 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2421 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2423 // Allocate initial symbol table.
2424 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2425 if (!maybe_obj->ToObject(&obj)) return false;
2427 // Don't use set_symbol_table() due to asserts.
2428 roots_[kSymbolTableRootIndex] = obj;
2430 // Finish initializing oddballs after creating symboltable.
2431 { MaybeObject* maybe_obj =
2432 undefined_value()->Initialize("undefined",
2434 Oddball::kUndefined);
2435 if (!maybe_obj->ToObject(&obj)) return false;
2438 // Initialize the null_value.
2439 { MaybeObject* maybe_obj =
2440 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2441 if (!maybe_obj->ToObject(&obj)) return false;
2444 { MaybeObject* maybe_obj = CreateOddball("true",
2447 if (!maybe_obj->ToObject(&obj)) return false;
2449 set_true_value(Oddball::cast(obj));
2451 { MaybeObject* maybe_obj = CreateOddball("false",
2454 if (!maybe_obj->ToObject(&obj)) return false;
2456 set_false_value(Oddball::cast(obj));
2458 { MaybeObject* maybe_obj = CreateOddball("hole",
2461 if (!maybe_obj->ToObject(&obj)) return false;
2463 set_the_hole_value(Oddball::cast(obj));
2465 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2467 Oddball::kArgumentMarker);
2468 if (!maybe_obj->ToObject(&obj)) return false;
2470 set_arguments_marker(Oddball::cast(obj));
2472 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2475 if (!maybe_obj->ToObject(&obj)) return false;
2477 set_no_interceptor_result_sentinel(obj);
2479 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2482 if (!maybe_obj->ToObject(&obj)) return false;
2484 set_termination_exception(obj);
2486 { MaybeObject* maybe_obj = CreateOddball("frame_alignment_marker",
2489 if (!maybe_obj->ToObject(&obj)) return false;
2491 set_frame_alignment_marker(Oddball::cast(obj));
2492 STATIC_ASSERT(Oddball::kLeastHiddenOddballNumber == -5);
2494 // Allocate the empty string.
2495 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2496 if (!maybe_obj->ToObject(&obj)) return false;
2498 set_empty_string(String::cast(obj));
2500 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2501 { MaybeObject* maybe_obj =
2502 LookupAsciiSymbol(constant_symbol_table[i].contents);
2503 if (!maybe_obj->ToObject(&obj)) return false;
2505 roots_[constant_symbol_table[i].index] = String::cast(obj);
2508 // Allocate the hidden symbol which is used to identify the hidden properties
2509 // in JSObjects. The hash code has a special value so that it will not match
2510 // the empty string when searching for the property. It cannot be part of the
2511 // loop above because it needs to be allocated manually with the special
2512 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2513 // that it will always be at the first entry in property descriptors.
2514 { MaybeObject* maybe_obj =
2515 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2516 if (!maybe_obj->ToObject(&obj)) return false;
2518 hidden_symbol_ = String::cast(obj);
2520 // Allocate the foreign for __proto__.
2521 { MaybeObject* maybe_obj =
2522 AllocateForeign((Address) &Accessors::ObjectPrototype);
2523 if (!maybe_obj->ToObject(&obj)) return false;
2525 set_prototype_accessors(Foreign::cast(obj));
2527 // Allocate the code_stubs dictionary. The initial size is set to avoid
2528 // expanding the dictionary during bootstrapping.
2529 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2530 if (!maybe_obj->ToObject(&obj)) return false;
2532 set_code_stubs(UnseededNumberDictionary::cast(obj));
2535 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2536 // is set to avoid expanding the dictionary during bootstrapping.
2537 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2538 if (!maybe_obj->ToObject(&obj)) return false;
2540 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2542 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2543 if (!maybe_obj->ToObject(&obj)) return false;
2545 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2547 set_instanceof_cache_function(Smi::FromInt(0));
2548 set_instanceof_cache_map(Smi::FromInt(0));
2549 set_instanceof_cache_answer(Smi::FromInt(0));
2553 // Allocate the dictionary of intrinsic function names.
2554 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2555 if (!maybe_obj->ToObject(&obj)) return false;
2557 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2559 if (!maybe_obj->ToObject(&obj)) return false;
2561 set_intrinsic_function_names(StringDictionary::cast(obj));
2563 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2564 if (!maybe_obj->ToObject(&obj)) return false;
2566 set_number_string_cache(FixedArray::cast(obj));
2568 // Allocate cache for single character ASCII strings.
2569 { MaybeObject* maybe_obj =
2570 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2571 if (!maybe_obj->ToObject(&obj)) return false;
2573 set_single_character_string_cache(FixedArray::cast(obj));
2575 // Allocate cache for string split.
2576 { MaybeObject* maybe_obj =
2577 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2578 if (!maybe_obj->ToObject(&obj)) return false;
2580 set_string_split_cache(FixedArray::cast(obj));
2582 // Allocate cache for external strings pointing to native source code.
2583 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2584 if (!maybe_obj->ToObject(&obj)) return false;
2586 set_natives_source_cache(FixedArray::cast(obj));
2588 // Handling of script id generation is in FACTORY->NewScript.
2589 set_last_script_id(undefined_value());
2591 // Initialize keyed lookup cache.
2592 isolate_->keyed_lookup_cache()->Clear();
2594 // Initialize context slot cache.
2595 isolate_->context_slot_cache()->Clear();
2597 // Initialize descriptor cache.
2598 isolate_->descriptor_lookup_cache()->Clear();
2600 // Initialize compilation cache.
2601 isolate_->compilation_cache()->Clear();
2607 Object* StringSplitCache::Lookup(
2608 FixedArray* cache, String* string, String* pattern) {
2609 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2610 uint32_t hash = string->Hash();
2611 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2612 ~(kArrayEntriesPerCacheEntry - 1));
2613 if (cache->get(index + kStringOffset) == string &&
2614 cache->get(index + kPatternOffset) == pattern) {
2615 return cache->get(index + kArrayOffset);
2617 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2618 if (cache->get(index + kStringOffset) == string &&
2619 cache->get(index + kPatternOffset) == pattern) {
2620 return cache->get(index + kArrayOffset);
2622 return Smi::FromInt(0);
2626 void StringSplitCache::Enter(Heap* heap,
2630 FixedArray* array) {
2631 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2632 uint32_t hash = string->Hash();
2633 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2634 ~(kArrayEntriesPerCacheEntry - 1));
2635 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2636 cache->set(index + kStringOffset, string);
2637 cache->set(index + kPatternOffset, pattern);
2638 cache->set(index + kArrayOffset, array);
2641 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2642 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2643 cache->set(index2 + kStringOffset, string);
2644 cache->set(index2 + kPatternOffset, pattern);
2645 cache->set(index2 + kArrayOffset, array);
2647 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2648 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2649 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2650 cache->set(index + kStringOffset, string);
2651 cache->set(index + kPatternOffset, pattern);
2652 cache->set(index + kArrayOffset, array);
2655 if (array->length() < 100) { // Limit how many new symbols we want to make.
2656 for (int i = 0; i < array->length(); i++) {
2657 String* str = String::cast(array->get(i));
2659 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2660 if (maybe_symbol->ToObject(&symbol)) {
2661 array->set(i, symbol);
2665 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2669 void StringSplitCache::Clear(FixedArray* cache) {
2670 for (int i = 0; i < kStringSplitCacheSize; i++) {
2671 cache->set(i, Smi::FromInt(0));
2676 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2677 MaybeObject* maybe_obj =
2678 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2683 int Heap::FullSizeNumberStringCacheLength() {
2684 // Compute the size of the number string cache based on the max newspace size.
2685 // The number string cache has a minimum size based on twice the initial cache
2686 // size to ensure that it is bigger after being made 'full size'.
2687 int number_string_cache_size = max_semispace_size_ / 512;
2688 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2689 Min(0x4000, number_string_cache_size));
2690 // There is a string and a number per entry so the length is twice the number
2692 return number_string_cache_size * 2;
2696 void Heap::AllocateFullSizeNumberStringCache() {
2697 // The idea is to have a small number string cache in the snapshot to keep
2698 // boot-time memory usage down. If we expand the number string cache already
2699 // while creating the snapshot then that didn't work out.
2700 ASSERT(!Serializer::enabled());
2701 MaybeObject* maybe_obj =
2702 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2704 if (maybe_obj->ToObject(&new_cache)) {
2705 // We don't bother to repopulate the cache with entries from the old cache.
2706 // It will be repopulated soon enough with new strings.
2707 set_number_string_cache(FixedArray::cast(new_cache));
2709 // If allocation fails then we just return without doing anything. It is only
2710 // a cache, so best effort is OK here.
2714 void Heap::FlushNumberStringCache() {
2715 // Flush the number to string cache.
2716 int len = number_string_cache()->length();
2717 for (int i = 0; i < len; i++) {
2718 number_string_cache()->set_undefined(this, i);
2723 static inline int double_get_hash(double d) {
2724 DoubleRepresentation rep(d);
2725 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2729 static inline int smi_get_hash(Smi* smi) {
2730 return smi->value();
2734 Object* Heap::GetNumberStringCache(Object* number) {
2736 int mask = (number_string_cache()->length() >> 1) - 1;
2737 if (number->IsSmi()) {
2738 hash = smi_get_hash(Smi::cast(number)) & mask;
2740 hash = double_get_hash(number->Number()) & mask;
2742 Object* key = number_string_cache()->get(hash * 2);
2743 if (key == number) {
2744 return String::cast(number_string_cache()->get(hash * 2 + 1));
2745 } else if (key->IsHeapNumber() &&
2746 number->IsHeapNumber() &&
2747 key->Number() == number->Number()) {
2748 return String::cast(number_string_cache()->get(hash * 2 + 1));
2750 return undefined_value();
2754 void Heap::SetNumberStringCache(Object* number, String* string) {
2756 int mask = (number_string_cache()->length() >> 1) - 1;
2757 if (number->IsSmi()) {
2758 hash = smi_get_hash(Smi::cast(number)) & mask;
2760 hash = double_get_hash(number->Number()) & mask;
2762 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2763 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2764 // The first time we have a hash collision, we move to the full sized
2765 // number string cache.
2766 AllocateFullSizeNumberStringCache();
2769 number_string_cache()->set(hash * 2, number);
2770 number_string_cache()->set(hash * 2 + 1, string);
2774 MaybeObject* Heap::NumberToString(Object* number,
2775 bool check_number_string_cache) {
2776 isolate_->counters()->number_to_string_runtime()->Increment();
2777 if (check_number_string_cache) {
2778 Object* cached = GetNumberStringCache(number);
2779 if (cached != undefined_value()) {
2785 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2787 if (number->IsSmi()) {
2788 int num = Smi::cast(number)->value();
2789 str = IntToCString(num, buffer);
2791 double num = HeapNumber::cast(number)->value();
2792 str = DoubleToCString(num, buffer);
2796 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2797 if (maybe_js_string->ToObject(&js_string)) {
2798 SetNumberStringCache(number, String::cast(js_string));
2800 return maybe_js_string;
2804 MaybeObject* Heap::Uint32ToString(uint32_t value,
2805 bool check_number_string_cache) {
2807 MaybeObject* maybe = NumberFromUint32(value);
2808 if (!maybe->To<Object>(&number)) return maybe;
2809 return NumberToString(number, check_number_string_cache);
2813 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2814 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2818 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2819 ExternalArrayType array_type) {
2820 switch (array_type) {
2821 case kExternalByteArray:
2822 return kExternalByteArrayMapRootIndex;
2823 case kExternalUnsignedByteArray:
2824 return kExternalUnsignedByteArrayMapRootIndex;
2825 case kExternalShortArray:
2826 return kExternalShortArrayMapRootIndex;
2827 case kExternalUnsignedShortArray:
2828 return kExternalUnsignedShortArrayMapRootIndex;
2829 case kExternalIntArray:
2830 return kExternalIntArrayMapRootIndex;
2831 case kExternalUnsignedIntArray:
2832 return kExternalUnsignedIntArrayMapRootIndex;
2833 case kExternalFloatArray:
2834 return kExternalFloatArrayMapRootIndex;
2835 case kExternalDoubleArray:
2836 return kExternalDoubleArrayMapRootIndex;
2837 case kExternalPixelArray:
2838 return kExternalPixelArrayMapRootIndex;
2841 return kUndefinedValueRootIndex;
2846 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2847 // We need to distinguish the minus zero value and this cannot be
2848 // done after conversion to int. Doing this by comparing bit
2849 // patterns is faster than using fpclassify() et al.
2850 static const DoubleRepresentation minus_zero(-0.0);
2852 DoubleRepresentation rep(value);
2853 if (rep.bits == minus_zero.bits) {
2854 return AllocateHeapNumber(-0.0, pretenure);
2857 int int_value = FastD2I(value);
2858 if (value == int_value && Smi::IsValid(int_value)) {
2859 return Smi::FromInt(int_value);
2862 // Materialize the value in the heap.
2863 return AllocateHeapNumber(value, pretenure);
2867 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2868 // Statically ensure that it is safe to allocate foreigns in paged spaces.
2869 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
2870 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2872 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2873 if (!maybe_result->To(&result)) return maybe_result;
2874 result->set_foreign_address(address);
2879 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
2880 SharedFunctionInfo* share;
2881 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2882 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
2884 // Set pointer fields.
2885 share->set_name(name);
2886 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
2887 share->set_code(illegal);
2888 share->set_scope_info(ScopeInfo::Empty());
2889 Code* construct_stub =
2890 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2891 share->set_construct_stub(construct_stub);
2892 share->set_instance_class_name(Object_symbol());
2893 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
2894 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
2895 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
2896 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
2897 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
2898 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
2899 share->set_deopt_counter(FLAG_deopt_every_n_times);
2900 share->set_profiler_ticks(0);
2901 share->set_ast_node_count(0);
2903 // Set integer fields (smi or int, depending on the architecture).
2904 share->set_length(0);
2905 share->set_formal_parameter_count(0);
2906 share->set_expected_nof_properties(0);
2907 share->set_num_literals(0);
2908 share->set_start_position_and_type(0);
2909 share->set_end_position(0);
2910 share->set_function_token_position(0);
2911 // All compiler hints default to false or 0.
2912 share->set_compiler_hints(0);
2913 share->set_this_property_assignments_count(0);
2914 share->set_opt_count(0);
2920 MaybeObject* Heap::AllocateJSMessageObject(String* type,
2925 Object* stack_trace,
2926 Object* stack_frames) {
2928 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2929 if (!maybe_result->ToObject(&result)) return maybe_result;
2931 JSMessageObject* message = JSMessageObject::cast(result);
2932 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2933 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
2934 message->set_type(type);
2935 message->set_arguments(arguments);
2936 message->set_start_position(start_position);
2937 message->set_end_position(end_position);
2938 message->set_script(script);
2939 message->set_stack_trace(stack_trace);
2940 message->set_stack_frames(stack_frames);
2946 // Returns true for a character in a range. Both limits are inclusive.
2947 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2948 // This makes uses of the the unsigned wraparound.
2949 return character - from <= to - from;
2953 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
2958 // Numeric strings have a different hash algorithm not known by
2959 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2960 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
2961 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
2963 // Now we know the length is 2, we might as well make use of that fact
2964 // when building the new string.
2965 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2966 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
2968 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
2969 if (!maybe_result->ToObject(&result)) return maybe_result;
2971 char* dest = SeqAsciiString::cast(result)->GetChars();
2977 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
2978 if (!maybe_result->ToObject(&result)) return maybe_result;
2980 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2988 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
2989 int first_length = first->length();
2990 if (first_length == 0) {
2994 int second_length = second->length();
2995 if (second_length == 0) {
2999 int length = first_length + second_length;
3001 // Optimization for 2-byte strings often used as keys in a decompression
3002 // dictionary. Check whether we already have the string in the symbol
3003 // table to prevent creation of many unneccesary strings.
3005 unsigned c1 = first->Get(0);
3006 unsigned c2 = second->Get(0);
3007 return MakeOrFindTwoCharacterString(this, c1, c2);
3010 bool first_is_ascii = first->IsAsciiRepresentation();
3011 bool second_is_ascii = second->IsAsciiRepresentation();
3012 bool is_ascii = first_is_ascii && second_is_ascii;
3014 // Make sure that an out of memory exception is thrown if the length
3015 // of the new cons string is too large.
3016 if (length > String::kMaxLength || length < 0) {
3017 isolate()->context()->mark_out_of_memory();
3018 return Failure::OutOfMemoryException();
3021 bool is_ascii_data_in_two_byte_string = false;
3023 // At least one of the strings uses two-byte representation so we
3024 // can't use the fast case code for short ASCII strings below, but
3025 // we can try to save memory if all chars actually fit in ASCII.
3026 is_ascii_data_in_two_byte_string =
3027 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3028 if (is_ascii_data_in_two_byte_string) {
3029 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3033 // If the resulting string is small make a flat string.
3034 if (length < ConsString::kMinLength) {
3035 // Note that neither of the two inputs can be a slice because:
3036 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3037 ASSERT(first->IsFlat());
3038 ASSERT(second->IsFlat());
3041 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3042 if (!maybe_result->ToObject(&result)) return maybe_result;
3044 // Copy the characters into the new object.
3045 char* dest = SeqAsciiString::cast(result)->GetChars();
3048 if (first->IsExternalString()) {
3049 src = ExternalAsciiString::cast(first)->GetChars();
3051 src = SeqAsciiString::cast(first)->GetChars();
3053 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3054 // Copy second part.
3055 if (second->IsExternalString()) {
3056 src = ExternalAsciiString::cast(second)->GetChars();
3058 src = SeqAsciiString::cast(second)->GetChars();
3060 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3063 if (is_ascii_data_in_two_byte_string) {
3065 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3066 if (!maybe_result->ToObject(&result)) return maybe_result;
3068 // Copy the characters into the new object.
3069 char* dest = SeqAsciiString::cast(result)->GetChars();
3070 String::WriteToFlat(first, dest, 0, first_length);
3071 String::WriteToFlat(second, dest + first_length, 0, second_length);
3072 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3077 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3078 if (!maybe_result->ToObject(&result)) return maybe_result;
3080 // Copy the characters into the new object.
3081 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3082 String::WriteToFlat(first, dest, 0, first_length);
3083 String::WriteToFlat(second, dest + first_length, 0, second_length);
3088 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3089 cons_ascii_string_map() : cons_string_map();
3092 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3093 if (!maybe_result->ToObject(&result)) return maybe_result;
3096 AssertNoAllocation no_gc;
3097 ConsString* cons_string = ConsString::cast(result);
3098 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3099 cons_string->set_length(length);
3100 cons_string->set_hash_field(String::kEmptyHashField);
3101 cons_string->set_first(first, mode);
3102 cons_string->set_second(second, mode);
3107 MaybeObject* Heap::AllocateSubString(String* buffer,
3110 PretenureFlag pretenure) {
3111 int length = end - start;
3113 return empty_string();
3114 } else if (length == 1) {
3115 return LookupSingleCharacterStringFromCode(buffer->Get(start));
3116 } else if (length == 2) {
3117 // Optimization for 2-byte strings often used as keys in a decompression
3118 // dictionary. Check whether we already have the string in the symbol
3119 // table to prevent creation of many unneccesary strings.
3120 unsigned c1 = buffer->Get(start);
3121 unsigned c2 = buffer->Get(start + 1);
3122 return MakeOrFindTwoCharacterString(this, c1, c2);
3125 // Make an attempt to flatten the buffer to reduce access time.
3126 buffer = buffer->TryFlattenGetString();
3128 if (!FLAG_string_slices ||
3129 !buffer->IsFlat() ||
3130 length < SlicedString::kMinLength ||
3131 pretenure == TENURED) {
3133 // WriteToFlat takes care of the case when an indirect string has a
3134 // different encoding from its underlying string. These encodings may
3135 // differ because of externalization.
3136 bool is_ascii = buffer->IsAsciiRepresentation();
3137 { MaybeObject* maybe_result = is_ascii
3138 ? AllocateRawAsciiString(length, pretenure)
3139 : AllocateRawTwoByteString(length, pretenure);
3140 if (!maybe_result->ToObject(&result)) return maybe_result;
3142 String* string_result = String::cast(result);
3143 // Copy the characters into the new object.
3145 ASSERT(string_result->IsAsciiRepresentation());
3146 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3147 String::WriteToFlat(buffer, dest, start, end);
3149 ASSERT(string_result->IsTwoByteRepresentation());
3150 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3151 String::WriteToFlat(buffer, dest, start, end);
3156 ASSERT(buffer->IsFlat());
3158 if (FLAG_verify_heap) {
3159 buffer->StringVerify();
3164 // When slicing an indirect string we use its encoding for a newly created
3165 // slice and don't check the encoding of the underlying string. This is safe
3166 // even if the encodings are different because of externalization. If an
3167 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3168 // codes of the underlying string must still fit into ASCII (because
3169 // externalization must not change char codes).
3170 { Map* map = buffer->IsAsciiRepresentation()
3171 ? sliced_ascii_string_map()
3172 : sliced_string_map();
3173 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3174 if (!maybe_result->ToObject(&result)) return maybe_result;
3177 AssertNoAllocation no_gc;
3178 SlicedString* sliced_string = SlicedString::cast(result);
3179 sliced_string->set_length(length);
3180 sliced_string->set_hash_field(String::kEmptyHashField);
3181 if (buffer->IsConsString()) {
3182 ConsString* cons = ConsString::cast(buffer);
3183 ASSERT(cons->second()->length() == 0);
3184 sliced_string->set_parent(cons->first());
3185 sliced_string->set_offset(start);
3186 } else if (buffer->IsSlicedString()) {
3187 // Prevent nesting sliced strings.
3188 SlicedString* parent_slice = SlicedString::cast(buffer);
3189 sliced_string->set_parent(parent_slice->parent());
3190 sliced_string->set_offset(start + parent_slice->offset());
3192 sliced_string->set_parent(buffer);
3193 sliced_string->set_offset(start);
3195 ASSERT(sliced_string->parent()->IsSeqString() ||
3196 sliced_string->parent()->IsExternalString());
3201 MaybeObject* Heap::AllocateExternalStringFromAscii(
3202 const ExternalAsciiString::Resource* resource) {
3203 size_t length = resource->length();
3204 if (length > static_cast<size_t>(String::kMaxLength)) {
3205 isolate()->context()->mark_out_of_memory();
3206 return Failure::OutOfMemoryException();
3209 Map* map = external_ascii_string_map();
3211 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3212 if (!maybe_result->ToObject(&result)) return maybe_result;
3215 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3216 external_string->set_length(static_cast<int>(length));
3217 external_string->set_hash_field(String::kEmptyHashField);
3218 external_string->set_resource(resource);
3224 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3225 const ExternalTwoByteString::Resource* resource) {
3226 size_t length = resource->length();
3227 if (length > static_cast<size_t>(String::kMaxLength)) {
3228 isolate()->context()->mark_out_of_memory();
3229 return Failure::OutOfMemoryException();
3232 // For small strings we check whether the resource contains only
3233 // ASCII characters. If yes, we use a different string map.
3234 static const size_t kAsciiCheckLengthLimit = 32;
3235 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3236 String::IsAscii(resource->data(), static_cast<int>(length));
3237 Map* map = is_ascii ?
3238 external_string_with_ascii_data_map() : external_string_map();
3240 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3241 if (!maybe_result->ToObject(&result)) return maybe_result;
3244 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3245 external_string->set_length(static_cast<int>(length));
3246 external_string->set_hash_field(String::kEmptyHashField);
3247 external_string->set_resource(resource);
3253 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3254 if (code <= String::kMaxAsciiCharCode) {
3255 Object* value = single_character_string_cache()->get(code);
3256 if (value != undefined_value()) return value;
3259 buffer[0] = static_cast<char>(code);
3261 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3263 if (!maybe_result->ToObject(&result)) return maybe_result;
3264 single_character_string_cache()->set(code, result);
3269 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3270 if (!maybe_result->ToObject(&result)) return maybe_result;
3272 String* answer = String::cast(result);
3273 answer->Set(0, code);
3278 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3279 if (length < 0 || length > ByteArray::kMaxLength) {
3280 return Failure::OutOfMemoryException();
3282 if (pretenure == NOT_TENURED) {
3283 return AllocateByteArray(length);
3285 int size = ByteArray::SizeFor(length);
3287 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3288 ? old_data_space_->AllocateRaw(size)
3289 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3290 if (!maybe_result->ToObject(&result)) return maybe_result;
3293 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3295 reinterpret_cast<ByteArray*>(result)->set_length(length);
3300 MaybeObject* Heap::AllocateByteArray(int length) {
3301 if (length < 0 || length > ByteArray::kMaxLength) {
3302 return Failure::OutOfMemoryException();
3304 int size = ByteArray::SizeFor(length);
3305 AllocationSpace space =
3306 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3308 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3309 if (!maybe_result->ToObject(&result)) return maybe_result;
3312 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3314 reinterpret_cast<ByteArray*>(result)->set_length(length);
3319 void Heap::CreateFillerObjectAt(Address addr, int size) {
3320 if (size == 0) return;
3321 HeapObject* filler = HeapObject::FromAddress(addr);
3322 if (size == kPointerSize) {
3323 filler->set_map_no_write_barrier(one_pointer_filler_map());
3324 } else if (size == 2 * kPointerSize) {
3325 filler->set_map_no_write_barrier(two_pointer_filler_map());
3327 filler->set_map_no_write_barrier(free_space_map());
3328 FreeSpace::cast(filler)->set_size(size);
3333 MaybeObject* Heap::AllocateExternalArray(int length,
3334 ExternalArrayType array_type,
3335 void* external_pointer,
3336 PretenureFlag pretenure) {
3337 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3339 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3342 if (!maybe_result->ToObject(&result)) return maybe_result;
3345 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3346 MapForExternalArrayType(array_type));
3347 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3348 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3355 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3357 Handle<Object> self_reference,
3359 // Allocate ByteArray before the Code object, so that we do not risk
3360 // leaving uninitialized Code object (and breaking the heap).
3361 ByteArray* reloc_info;
3362 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3363 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3366 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3367 int obj_size = Code::SizeFor(body_size);
3368 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3369 MaybeObject* maybe_result;
3370 // Large code objects and code objects which should stay at a fixed address
3371 // are allocated in large object space.
3372 if (obj_size > code_space()->AreaSize() || immovable) {
3373 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3375 maybe_result = code_space_->AllocateRaw(obj_size);
3379 if (!maybe_result->ToObject(&result)) return maybe_result;
3381 // Initialize the object
3382 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3383 Code* code = Code::cast(result);
3384 ASSERT(!isolate_->code_range()->exists() ||
3385 isolate_->code_range()->contains(code->address()));
3386 code->set_instruction_size(desc.instr_size);
3387 code->set_relocation_info(reloc_info);
3388 code->set_flags(flags);
3389 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3390 code->set_check_type(RECEIVER_MAP_CHECK);
3392 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3393 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3394 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3395 code->set_gc_metadata(Smi::FromInt(0));
3396 // Allow self references to created code object by patching the handle to
3397 // point to the newly allocated Code object.
3398 if (!self_reference.is_null()) {
3399 *(self_reference.location()) = code;
3401 // Migrate generated code.
3402 // The generated code can contain Object** values (typically from handles)
3403 // that are dereferenced during the copy to point directly to the actual heap
3404 // objects. These pointers can include references to the code object itself,
3405 // through the self_reference parameter.
3406 code->CopyFrom(desc);
3409 if (FLAG_verify_heap) {
3417 MaybeObject* Heap::CopyCode(Code* code) {
3418 // Allocate an object the same size as the code object.
3419 int obj_size = code->Size();
3420 MaybeObject* maybe_result;
3421 if (obj_size > code_space()->AreaSize()) {
3422 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3424 maybe_result = code_space_->AllocateRaw(obj_size);
3428 if (!maybe_result->ToObject(&result)) return maybe_result;
3430 // Copy code object.
3431 Address old_addr = code->address();
3432 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3433 CopyBlock(new_addr, old_addr, obj_size);
3434 // Relocate the copy.
3435 Code* new_code = Code::cast(result);
3436 ASSERT(!isolate_->code_range()->exists() ||
3437 isolate_->code_range()->contains(code->address()));
3438 new_code->Relocate(new_addr - old_addr);
3443 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3444 // Allocate ByteArray before the Code object, so that we do not risk
3445 // leaving uninitialized Code object (and breaking the heap).
3446 Object* reloc_info_array;
3447 { MaybeObject* maybe_reloc_info_array =
3448 AllocateByteArray(reloc_info.length(), TENURED);
3449 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3450 return maybe_reloc_info_array;
3454 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3456 int new_obj_size = Code::SizeFor(new_body_size);
3458 Address old_addr = code->address();
3460 size_t relocation_offset =
3461 static_cast<size_t>(code->instruction_end() - old_addr);
3463 MaybeObject* maybe_result;
3464 if (new_obj_size > code_space()->AreaSize()) {
3465 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3467 maybe_result = code_space_->AllocateRaw(new_obj_size);
3471 if (!maybe_result->ToObject(&result)) return maybe_result;
3473 // Copy code object.
3474 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3476 // Copy header and instructions.
3477 memcpy(new_addr, old_addr, relocation_offset);
3479 Code* new_code = Code::cast(result);
3480 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3482 // Copy patched rinfo.
3483 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3485 // Relocate the copy.
3486 ASSERT(!isolate_->code_range()->exists() ||
3487 isolate_->code_range()->contains(code->address()));
3488 new_code->Relocate(new_addr - old_addr);
3491 if (FLAG_verify_heap) {
3499 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3500 ASSERT(gc_state_ == NOT_IN_GC);
3501 ASSERT(map->instance_type() != MAP_TYPE);
3502 // If allocation failures are disallowed, we may allocate in a different
3503 // space when new space is full and the object is not a large object.
3504 AllocationSpace retry_space =
3505 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3507 { MaybeObject* maybe_result =
3508 AllocateRaw(map->instance_size(), space, retry_space);
3509 if (!maybe_result->ToObject(&result)) return maybe_result;
3511 // No need for write barrier since object is white and map is in old space.
3512 HeapObject::cast(result)->set_map_no_write_barrier(map);
3517 void Heap::InitializeFunction(JSFunction* function,
3518 SharedFunctionInfo* shared,
3519 Object* prototype) {
3520 ASSERT(!prototype->IsMap());
3521 function->initialize_properties();
3522 function->initialize_elements();
3523 function->set_shared(shared);
3524 function->set_code(shared->code());
3525 function->set_prototype_or_initial_map(prototype);
3526 function->set_context(undefined_value());
3527 function->set_literals_or_bindings(empty_fixed_array());
3528 function->set_next_function_link(undefined_value());
3532 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3533 // Allocate the prototype. Make sure to use the object function
3534 // from the function's context, since the function can be from a
3535 // different context.
3536 JSFunction* object_function =
3537 function->context()->global_context()->object_function();
3539 // Each function prototype gets a copy of the object function map.
3540 // This avoid unwanted sharing of maps between prototypes of different
3543 ASSERT(object_function->has_initial_map());
3544 { MaybeObject* maybe_map =
3545 object_function->initial_map()->CopyDropTransitions();
3546 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3549 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3550 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3552 // When creating the prototype for the function we must set its
3553 // constructor to the function.
3555 { MaybeObject* maybe_result =
3556 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3557 constructor_symbol(), function, DONT_ENUM);
3558 if (!maybe_result->ToObject(&result)) return maybe_result;
3564 MaybeObject* Heap::AllocateFunction(Map* function_map,
3565 SharedFunctionInfo* shared,
3567 PretenureFlag pretenure) {
3568 AllocationSpace space =
3569 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3571 { MaybeObject* maybe_result = Allocate(function_map, space);
3572 if (!maybe_result->ToObject(&result)) return maybe_result;
3574 InitializeFunction(JSFunction::cast(result), shared, prototype);
3579 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3580 // To get fast allocation and map sharing for arguments objects we
3581 // allocate them based on an arguments boilerplate.
3583 JSObject* boilerplate;
3584 int arguments_object_size;
3585 bool strict_mode_callee = callee->IsJSFunction() &&
3586 !JSFunction::cast(callee)->shared()->is_classic_mode();
3587 if (strict_mode_callee) {
3589 isolate()->context()->global_context()->
3590 strict_mode_arguments_boilerplate();
3591 arguments_object_size = kArgumentsObjectSizeStrict;
3594 isolate()->context()->global_context()->arguments_boilerplate();
3595 arguments_object_size = kArgumentsObjectSize;
3598 // This calls Copy directly rather than using Heap::AllocateRaw so we
3599 // duplicate the check here.
3600 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3602 // Check that the size of the boilerplate matches our
3603 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3604 // on the size being a known constant.
3605 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3607 // Do the allocation.
3609 { MaybeObject* maybe_result =
3610 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3611 if (!maybe_result->ToObject(&result)) return maybe_result;
3614 // Copy the content. The arguments boilerplate doesn't have any
3615 // fields that point to new space so it's safe to skip the write
3617 CopyBlock(HeapObject::cast(result)->address(),
3618 boilerplate->address(),
3619 JSObject::kHeaderSize);
3621 // Set the length property.
3622 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3623 Smi::FromInt(length),
3624 SKIP_WRITE_BARRIER);
3625 // Set the callee property for non-strict mode arguments object only.
3626 if (!strict_mode_callee) {
3627 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3631 // Check the state of the object
3632 ASSERT(JSObject::cast(result)->HasFastProperties());
3633 ASSERT(JSObject::cast(result)->HasFastElements());
3639 static bool HasDuplicates(DescriptorArray* descriptors) {
3640 int count = descriptors->number_of_descriptors();
3642 String* prev_key = descriptors->GetKey(0);
3643 for (int i = 1; i != count; i++) {
3644 String* current_key = descriptors->GetKey(i);
3645 if (prev_key == current_key) return true;
3646 prev_key = current_key;
3653 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3654 ASSERT(!fun->has_initial_map());
3656 // First create a new map with the size and number of in-object properties
3657 // suggested by the function.
3658 int instance_size = fun->shared()->CalculateInstanceSize();
3659 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3661 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3662 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3665 // Fetch or allocate prototype.
3667 if (fun->has_instance_prototype()) {
3668 prototype = fun->instance_prototype();
3670 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3671 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3674 Map* map = Map::cast(map_obj);
3675 map->set_inobject_properties(in_object_properties);
3676 map->set_unused_property_fields(in_object_properties);
3677 map->set_prototype(prototype);
3678 ASSERT(map->has_fast_elements());
3680 // If the function has only simple this property assignments add
3681 // field descriptors for these to the initial map as the object
3682 // cannot be constructed without having these properties. Guard by
3683 // the inline_new flag so we only change the map if we generate a
3684 // specialized construct stub.
3685 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3686 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3687 int count = fun->shared()->this_property_assignments_count();
3688 if (count > in_object_properties) {
3689 // Inline constructor can only handle inobject properties.
3690 fun->shared()->ForbidInlineConstructor();
3692 DescriptorArray* descriptors;
3693 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
3694 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
3695 return maybe_descriptors_obj;
3698 DescriptorArray::WhitenessWitness witness(descriptors);
3699 for (int i = 0; i < count; i++) {
3700 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3701 ASSERT(name->IsSymbol());
3702 FieldDescriptor field(name, i, NONE);
3703 field.SetEnumerationIndex(i);
3704 descriptors->Set(i, &field, witness);
3706 descriptors->SetNextEnumerationIndex(count);
3707 descriptors->SortUnchecked(witness);
3709 // The descriptors may contain duplicates because the compiler does not
3710 // guarantee the uniqueness of property names (it would have required
3711 // quadratic time). Once the descriptors are sorted we can check for
3712 // duplicates in linear time.
3713 if (HasDuplicates(descriptors)) {
3714 fun->shared()->ForbidInlineConstructor();
3716 map->set_instance_descriptors(descriptors);
3717 map->set_pre_allocated_property_fields(count);
3718 map->set_unused_property_fields(in_object_properties - count);
3723 fun->shared()->StartInobjectSlackTracking(map);
3729 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3730 FixedArray* properties,
3732 obj->set_properties(properties);
3733 obj->initialize_elements();
3734 // TODO(1240798): Initialize the object's body using valid initial values
3735 // according to the object's initial map. For example, if the map's
3736 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3737 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3738 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3739 // verification code has to cope with (temporarily) invalid objects. See
3740 // for example, JSArray::JSArrayVerify).
3742 // We cannot always fill with one_pointer_filler_map because objects
3743 // created from API functions expect their internal fields to be initialized
3744 // with undefined_value.
3745 // Pre-allocated fields need to be initialized with undefined_value as well
3746 // so that object accesses before the constructor completes (e.g. in the
3747 // debugger) will not cause a crash.
3748 if (map->constructor()->IsJSFunction() &&
3749 JSFunction::cast(map->constructor())->shared()->
3750 IsInobjectSlackTrackingInProgress()) {
3751 // We might want to shrink the object later.
3752 ASSERT(obj->GetInternalFieldCount() == 0);
3753 filler = Heap::one_pointer_filler_map();
3755 filler = Heap::undefined_value();
3757 obj->InitializeBody(map, Heap::undefined_value(), filler);
3761 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3762 // JSFunctions should be allocated using AllocateFunction to be
3763 // properly initialized.
3764 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3766 // Both types of global objects should be allocated using
3767 // AllocateGlobalObject to be properly initialized.
3768 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3769 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3771 // Allocate the backing storage for the properties.
3773 map->pre_allocated_property_fields() +
3774 map->unused_property_fields() -
3775 map->inobject_properties();
3776 ASSERT(prop_size >= 0);
3778 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3779 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3782 // Allocate the JSObject.
3783 AllocationSpace space =
3784 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3785 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
3787 { MaybeObject* maybe_obj = Allocate(map, space);
3788 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3791 // Initialize the JSObject.
3792 InitializeJSObjectFromMap(JSObject::cast(obj),
3793 FixedArray::cast(properties),
3795 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3796 JSObject::cast(obj)->HasFastElements());
3801 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3802 PretenureFlag pretenure) {
3803 // Allocate the initial map if absent.
3804 if (!constructor->has_initial_map()) {
3805 Object* initial_map;
3806 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3807 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3809 constructor->set_initial_map(Map::cast(initial_map));
3810 Map::cast(initial_map)->set_constructor(constructor);
3812 // Allocate the object based on the constructors initial map.
3813 MaybeObject* result = AllocateJSObjectFromMap(
3814 constructor->initial_map(), pretenure);
3816 // Make sure result is NOT a global object if valid.
3817 Object* non_failure;
3818 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3824 MaybeObject* Heap::AllocateJSArrayAndStorage(
3825 ElementsKind elements_kind,
3828 ArrayStorageAllocationMode mode,
3829 PretenureFlag pretenure) {
3830 ASSERT(capacity >= length);
3831 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3833 if (!maybe_array->To(&array)) return maybe_array;
3835 if (capacity == 0) {
3836 array->set_length(Smi::FromInt(0));
3837 array->set_elements(empty_fixed_array());
3841 FixedArrayBase* elms;
3842 MaybeObject* maybe_elms = NULL;
3843 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3844 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3845 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3847 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3848 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3851 ASSERT(elements_kind == FAST_ELEMENTS ||
3852 elements_kind == FAST_SMI_ONLY_ELEMENTS);
3853 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3854 maybe_elms = AllocateUninitializedFixedArray(capacity);
3856 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3857 maybe_elms = AllocateFixedArrayWithHoles(capacity);
3860 if (!maybe_elms->To(&elms)) return maybe_elms;
3862 array->set_elements(elms);
3863 array->set_length(Smi::FromInt(length));
3868 MaybeObject* Heap::AllocateJSArrayWithElements(
3869 FixedArrayBase* elements,
3870 ElementsKind elements_kind,
3871 PretenureFlag pretenure) {
3872 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3874 if (!maybe_array->To(&array)) return maybe_array;
3876 array->set_elements(elements);
3877 array->set_length(Smi::FromInt(elements->length()));
3882 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
3884 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3885 // maps. Will probably depend on the identity of the handler object, too.
3887 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
3888 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3889 map->set_prototype(prototype);
3891 // Allocate the proxy object.
3893 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3894 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
3895 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3896 result->set_handler(handler);
3897 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
3902 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
3904 Object* construct_trap,
3905 Object* prototype) {
3907 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
3908 // maps. Will probably depend on the identity of the handler object, too.
3910 MaybeObject* maybe_map_obj =
3911 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
3912 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
3913 map->set_prototype(prototype);
3915 // Allocate the proxy object.
3916 JSFunctionProxy* result;
3917 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3918 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
3919 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
3920 result->set_handler(handler);
3921 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
3922 result->set_call_trap(call_trap);
3923 result->set_construct_trap(construct_trap);
3928 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
3929 ASSERT(constructor->has_initial_map());
3930 Map* map = constructor->initial_map();
3932 // Make sure no field properties are described in the initial map.
3933 // This guarantees us that normalizing the properties does not
3934 // require us to change property values to JSGlobalPropertyCells.
3935 ASSERT(map->NextFreePropertyIndex() == 0);
3937 // Make sure we don't have a ton of pre-allocated slots in the
3938 // global objects. They will be unused once we normalize the object.
3939 ASSERT(map->unused_property_fields() == 0);
3940 ASSERT(map->inobject_properties() == 0);
3942 // Initial size of the backing store to avoid resize of the storage during
3943 // bootstrapping. The size differs between the JS global object ad the
3945 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3947 // Allocate a dictionary object for backing storage.
3949 { MaybeObject* maybe_obj =
3950 StringDictionary::Allocate(
3951 map->NumberOfDescribedProperties() * 2 + initial_size);
3952 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3954 StringDictionary* dictionary = StringDictionary::cast(obj);
3956 // The global object might be created from an object template with accessors.
3957 // Fill these accessors into the dictionary.
3958 DescriptorArray* descs = map->instance_descriptors();
3959 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3960 PropertyDetails details(descs->GetDetails(i));
3961 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3963 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3964 Object* value = descs->GetCallbacksObject(i);
3965 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
3966 if (!maybe_value->ToObject(&value)) return maybe_value;
3970 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3971 if (!maybe_result->ToObject(&result)) return maybe_result;
3973 dictionary = StringDictionary::cast(result);
3976 // Allocate the global object and initialize it with the backing store.
3977 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3978 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3980 JSObject* global = JSObject::cast(obj);
3981 InitializeJSObjectFromMap(global, dictionary, map);
3983 // Create a new map for the global object.
3984 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3985 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3987 Map* new_map = Map::cast(obj);
3989 // Set up the global object as a normalized object.
3990 global->set_map(new_map);
3991 global->map()->clear_instance_descriptors();
3992 global->set_properties(dictionary);
3994 // Make sure result is a global object with properties in dictionary.
3995 ASSERT(global->IsGlobalObject());
3996 ASSERT(!global->HasFastProperties());
4001 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4002 // Never used to copy functions. If functions need to be copied we
4003 // have to be careful to clear the literals array.
4004 SLOW_ASSERT(!source->IsJSFunction());
4007 Map* map = source->map();
4008 int object_size = map->instance_size();
4011 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4013 // If we're forced to always allocate, we use the general allocation
4014 // functions which may leave us with an object in old space.
4015 if (always_allocate()) {
4016 { MaybeObject* maybe_clone =
4017 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4018 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4020 Address clone_address = HeapObject::cast(clone)->address();
4021 CopyBlock(clone_address,
4024 // Update write barrier for all fields that lie beyond the header.
4025 RecordWrites(clone_address,
4026 JSObject::kHeaderSize,
4027 (object_size - JSObject::kHeaderSize) / kPointerSize);
4029 wb_mode = SKIP_WRITE_BARRIER;
4030 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4031 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4033 SLOW_ASSERT(InNewSpace(clone));
4034 // Since we know the clone is allocated in new space, we can copy
4035 // the contents without worrying about updating the write barrier.
4036 CopyBlock(HeapObject::cast(clone)->address(),
4042 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4043 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4044 FixedArray* properties = FixedArray::cast(source->properties());
4045 // Update elements if necessary.
4046 if (elements->length() > 0) {
4048 { MaybeObject* maybe_elem;
4049 if (elements->map() == fixed_cow_array_map()) {
4050 maybe_elem = FixedArray::cast(elements);
4051 } else if (source->HasFastDoubleElements()) {
4052 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4054 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4056 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4058 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4060 // Update properties if necessary.
4061 if (properties->length() > 0) {
4063 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4064 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4066 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4068 // Return the new clone.
4073 MaybeObject* Heap::ReinitializeJSReceiver(
4074 JSReceiver* object, InstanceType type, int size) {
4075 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4077 // Allocate fresh map.
4078 // TODO(rossberg): Once we optimize proxies, cache these maps.
4080 MaybeObject* maybe = AllocateMap(type, size);
4081 if (!maybe->To<Map>(&map)) return maybe;
4083 // Check that the receiver has at least the size of the fresh object.
4084 int size_difference = object->map()->instance_size() - map->instance_size();
4085 ASSERT(size_difference >= 0);
4087 map->set_prototype(object->map()->prototype());
4089 // Allocate the backing storage for the properties.
4090 int prop_size = map->unused_property_fields() - map->inobject_properties();
4092 maybe = AllocateFixedArray(prop_size, TENURED);
4093 if (!maybe->ToObject(&properties)) return maybe;
4095 // Functions require some allocation, which might fail here.
4096 SharedFunctionInfo* shared = NULL;
4097 if (type == JS_FUNCTION_TYPE) {
4099 maybe = LookupAsciiSymbol("<freezing call trap>");
4100 if (!maybe->To<String>(&name)) return maybe;
4101 maybe = AllocateSharedFunctionInfo(name);
4102 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4105 // Because of possible retries of this function after failure,
4106 // we must NOT fail after this point, where we have changed the type!
4108 // Reset the map for the object.
4109 object->set_map(map);
4110 JSObject* jsobj = JSObject::cast(object);
4112 // Reinitialize the object from the constructor map.
4113 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4115 // Functions require some minimal initialization.
4116 if (type == JS_FUNCTION_TYPE) {
4117 map->set_function_with_prototype(true);
4118 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4119 JSFunction::cast(object)->set_context(
4120 isolate()->context()->global_context());
4123 // Put in filler if the new object is smaller than the old.
4124 if (size_difference > 0) {
4125 CreateFillerObjectAt(
4126 object->address() + map->instance_size(), size_difference);
4133 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4134 JSGlobalProxy* object) {
4135 ASSERT(constructor->has_initial_map());
4136 Map* map = constructor->initial_map();
4138 // Check that the already allocated object has the same size and type as
4139 // objects allocated using the constructor.
4140 ASSERT(map->instance_size() == object->map()->instance_size());
4141 ASSERT(map->instance_type() == object->map()->instance_type());
4143 // Allocate the backing storage for the properties.
4144 int prop_size = map->unused_property_fields() - map->inobject_properties();
4146 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4147 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4150 // Reset the map for the object.
4151 object->set_map(constructor->initial_map());
4153 // Reinitialize the object from the constructor map.
4154 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4159 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4160 PretenureFlag pretenure) {
4161 if (string.length() == 1) {
4162 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4165 { MaybeObject* maybe_result =
4166 AllocateRawAsciiString(string.length(), pretenure);
4167 if (!maybe_result->ToObject(&result)) return maybe_result;
4170 // Copy the characters into the new object.
4171 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4172 for (int i = 0; i < string.length(); i++) {
4173 string_result->SeqAsciiStringSet(i, string[i]);
4179 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4180 PretenureFlag pretenure) {
4181 // V8 only supports characters in the Basic Multilingual Plane.
4182 const uc32 kMaxSupportedChar = 0xFFFF;
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()) {
4195 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4196 if (!maybe_result->ToObject(&result)) return maybe_result;
4199 // Convert and copy the characters into the new object.
4200 String* string_result = String::cast(result);
4201 decoder->Reset(string.start(), string.length());
4202 for (int i = 0; i < chars; i++) {
4203 uc32 r = decoder->GetNext();
4204 if (r > kMaxSupportedChar) { r = unibrow::Utf8::kBadChar; }
4205 string_result->Set(i, r);
4211 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4212 PretenureFlag pretenure) {
4213 // Check if the string is an ASCII string.
4214 MaybeObject* maybe_result;
4215 if (String::IsAscii(string.start(), string.length())) {
4216 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4217 } else { // It's not an ASCII string.
4218 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4221 if (!maybe_result->ToObject(&result)) return maybe_result;
4223 // Copy the characters into the new object, which may be either ASCII or
4225 String* string_result = String::cast(result);
4226 for (int i = 0; i < string.length(); i++) {
4227 string_result->Set(i, string[i]);
4233 Map* Heap::SymbolMapForString(String* string) {
4234 // If the string is in new space it cannot be used as a symbol.
4235 if (InNewSpace(string)) return NULL;
4237 // Find the corresponding symbol map for strings.
4238 switch (string->map()->instance_type()) {
4239 case STRING_TYPE: return symbol_map();
4240 case ASCII_STRING_TYPE: return ascii_symbol_map();
4241 case CONS_STRING_TYPE: return cons_symbol_map();
4242 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4243 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4244 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4245 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4246 return external_symbol_with_ascii_data_map();
4247 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4248 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4249 return short_external_ascii_symbol_map();
4250 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4251 return short_external_symbol_with_ascii_data_map();
4252 default: return NULL; // No match found.
4257 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4259 uint32_t hash_field) {
4261 // Ensure the chars matches the number of characters in the buffer.
4262 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
4263 // Determine whether the string is ASCII.
4264 bool is_ascii = true;
4265 while (buffer->has_more()) {
4266 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4273 // Compute map and object size.
4278 if (chars > SeqAsciiString::kMaxLength) {
4279 return Failure::OutOfMemoryException();
4281 map = ascii_symbol_map();
4282 size = SeqAsciiString::SizeFor(chars);
4284 if (chars > SeqTwoByteString::kMaxLength) {
4285 return Failure::OutOfMemoryException();
4288 size = SeqTwoByteString::SizeFor(chars);
4293 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4294 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4295 : old_data_space_->AllocateRaw(size);
4296 if (!maybe_result->ToObject(&result)) return maybe_result;
4299 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4300 // Set length and hash fields of the allocated string.
4301 String* answer = String::cast(result);
4302 answer->set_length(chars);
4303 answer->set_hash_field(hash_field);
4305 ASSERT_EQ(size, answer->Size());
4307 // Fill in the characters.
4308 for (int i = 0; i < chars; i++) {
4309 answer->Set(i, buffer->GetNext());
4315 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4316 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4317 return Failure::OutOfMemoryException();
4320 int size = SeqAsciiString::SizeFor(length);
4321 ASSERT(size <= SeqAsciiString::kMaxSize);
4323 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4324 AllocationSpace retry_space = OLD_DATA_SPACE;
4326 if (space == NEW_SPACE) {
4327 if (size > kMaxObjectSizeInNewSpace) {
4328 // Allocate in large object space, retry space will be ignored.
4330 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4331 // Allocate in new space, retry in large object space.
4332 retry_space = LO_SPACE;
4334 } else if (space == OLD_DATA_SPACE &&
4335 size > Page::kMaxNonCodeHeapObjectSize) {
4339 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4340 if (!maybe_result->ToObject(&result)) return maybe_result;
4343 // Partially initialize the object.
4344 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4345 String::cast(result)->set_length(length);
4346 String::cast(result)->set_hash_field(String::kEmptyHashField);
4347 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4352 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4353 PretenureFlag pretenure) {
4354 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4355 return Failure::OutOfMemoryException();
4357 int size = SeqTwoByteString::SizeFor(length);
4358 ASSERT(size <= SeqTwoByteString::kMaxSize);
4359 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4360 AllocationSpace retry_space = OLD_DATA_SPACE;
4362 if (space == NEW_SPACE) {
4363 if (size > kMaxObjectSizeInNewSpace) {
4364 // Allocate in large object space, retry space will be ignored.
4366 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4367 // Allocate in new space, retry in large object space.
4368 retry_space = LO_SPACE;
4370 } else if (space == OLD_DATA_SPACE &&
4371 size > Page::kMaxNonCodeHeapObjectSize) {
4375 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4376 if (!maybe_result->ToObject(&result)) return maybe_result;
4379 // Partially initialize the object.
4380 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4381 String::cast(result)->set_length(length);
4382 String::cast(result)->set_hash_field(String::kEmptyHashField);
4383 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4388 MaybeObject* Heap::AllocateJSArray(
4389 ElementsKind elements_kind,
4390 PretenureFlag pretenure) {
4391 Context* global_context = isolate()->context()->global_context();
4392 JSFunction* array_function = global_context->array_function();
4393 Map* map = array_function->initial_map();
4394 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4395 map = Map::cast(global_context->double_js_array_map());
4396 } else if (elements_kind == FAST_ELEMENTS || !FLAG_smi_only_arrays) {
4397 map = Map::cast(global_context->object_js_array_map());
4399 ASSERT(elements_kind == FAST_SMI_ONLY_ELEMENTS);
4400 ASSERT(map == global_context->smi_js_array_map());
4403 return AllocateJSObjectFromMap(map, pretenure);
4407 MaybeObject* Heap::AllocateEmptyFixedArray() {
4408 int size = FixedArray::SizeFor(0);
4410 { MaybeObject* maybe_result =
4411 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4412 if (!maybe_result->ToObject(&result)) return maybe_result;
4414 // Initialize the object.
4415 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4417 reinterpret_cast<FixedArray*>(result)->set_length(0);
4422 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4423 if (length < 0 || length > FixedArray::kMaxLength) {
4424 return Failure::OutOfMemoryException();
4427 // Use the general function if we're forced to always allocate.
4428 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4429 // Allocate the raw data for a fixed array.
4430 int size = FixedArray::SizeFor(length);
4431 return size <= kMaxObjectSizeInNewSpace
4432 ? new_space_.AllocateRaw(size)
4433 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4437 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4438 int len = src->length();
4440 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4441 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4443 if (InNewSpace(obj)) {
4444 HeapObject* dst = HeapObject::cast(obj);
4445 dst->set_map_no_write_barrier(map);
4446 CopyBlock(dst->address() + kPointerSize,
4447 src->address() + kPointerSize,
4448 FixedArray::SizeFor(len) - kPointerSize);
4451 HeapObject::cast(obj)->set_map_no_write_barrier(map);
4452 FixedArray* result = FixedArray::cast(obj);
4453 result->set_length(len);
4456 AssertNoAllocation no_gc;
4457 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4458 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4463 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4465 int len = src->length();
4467 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4468 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4470 HeapObject* dst = HeapObject::cast(obj);
4471 dst->set_map_no_write_barrier(map);
4473 dst->address() + FixedDoubleArray::kLengthOffset,
4474 src->address() + FixedDoubleArray::kLengthOffset,
4475 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4480 MaybeObject* Heap::AllocateFixedArray(int length) {
4481 ASSERT(length >= 0);
4482 if (length == 0) return empty_fixed_array();
4484 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4485 if (!maybe_result->ToObject(&result)) return maybe_result;
4487 // Initialize header.
4488 FixedArray* array = reinterpret_cast<FixedArray*>(result);
4489 array->set_map_no_write_barrier(fixed_array_map());
4490 array->set_length(length);
4492 ASSERT(!InNewSpace(undefined_value()));
4493 MemsetPointer(array->data_start(), undefined_value(), length);
4498 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4499 if (length < 0 || length > FixedArray::kMaxLength) {
4500 return Failure::OutOfMemoryException();
4503 AllocationSpace space =
4504 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4505 int size = FixedArray::SizeFor(length);
4506 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4507 // Too big for new space.
4509 } else if (space == OLD_POINTER_SPACE &&
4510 size > Page::kMaxNonCodeHeapObjectSize) {
4511 // Too big for old pointer space.
4515 AllocationSpace retry_space =
4516 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4518 return AllocateRaw(size, space, retry_space);
4522 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4525 PretenureFlag pretenure,
4527 ASSERT(length >= 0);
4528 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4529 if (length == 0) return heap->empty_fixed_array();
4531 ASSERT(!heap->InNewSpace(filler));
4533 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4534 if (!maybe_result->ToObject(&result)) return maybe_result;
4537 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4538 FixedArray* array = FixedArray::cast(result);
4539 array->set_length(length);
4540 MemsetPointer(array->data_start(), filler, length);
4545 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4546 return AllocateFixedArrayWithFiller(this,
4553 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4554 PretenureFlag pretenure) {
4555 return AllocateFixedArrayWithFiller(this,
4562 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4563 if (length == 0) return empty_fixed_array();
4566 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4567 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4570 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4572 FixedArray::cast(obj)->set_length(length);
4577 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4578 int size = FixedDoubleArray::SizeFor(0);
4580 { MaybeObject* maybe_result =
4581 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4582 if (!maybe_result->ToObject(&result)) return maybe_result;
4584 // Initialize the object.
4585 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4586 fixed_double_array_map());
4587 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4592 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4594 PretenureFlag pretenure) {
4595 if (length == 0) return empty_fixed_array();
4597 Object* elements_object;
4598 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4599 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4600 FixedDoubleArray* elements =
4601 reinterpret_cast<FixedDoubleArray*>(elements_object);
4603 elements->set_map_no_write_barrier(fixed_double_array_map());
4604 elements->set_length(length);
4609 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4611 PretenureFlag pretenure) {
4612 if (length == 0) return empty_fixed_array();
4614 Object* elements_object;
4615 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4616 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4617 FixedDoubleArray* elements =
4618 reinterpret_cast<FixedDoubleArray*>(elements_object);
4620 for (int i = 0; i < length; ++i) {
4621 elements->set_the_hole(i);
4624 elements->set_map_no_write_barrier(fixed_double_array_map());
4625 elements->set_length(length);
4630 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4631 PretenureFlag pretenure) {
4632 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4633 return Failure::OutOfMemoryException();
4636 AllocationSpace space =
4637 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4638 int size = FixedDoubleArray::SizeFor(length);
4639 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4640 // Too big for new space.
4642 } else if (space == OLD_DATA_SPACE &&
4643 size > Page::kMaxNonCodeHeapObjectSize) {
4644 // Too big for old data space.
4648 AllocationSpace retry_space =
4649 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4651 return AllocateRaw(size, space, retry_space);
4655 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4657 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4658 if (!maybe_result->ToObject(&result)) return maybe_result;
4660 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4662 ASSERT(result->IsHashTable());
4667 MaybeObject* Heap::AllocateGlobalContext() {
4669 { MaybeObject* maybe_result =
4670 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4671 if (!maybe_result->ToObject(&result)) return maybe_result;
4673 Context* context = reinterpret_cast<Context*>(result);
4674 context->set_map_no_write_barrier(global_context_map());
4675 context->set_smi_js_array_map(undefined_value());
4676 context->set_double_js_array_map(undefined_value());
4677 context->set_object_js_array_map(undefined_value());
4678 ASSERT(context->IsGlobalContext());
4679 ASSERT(result->IsContext());
4684 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4685 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4687 { MaybeObject* maybe_result = AllocateFixedArray(length);
4688 if (!maybe_result->ToObject(&result)) return maybe_result;
4690 Context* context = reinterpret_cast<Context*>(result);
4691 context->set_map_no_write_barrier(function_context_map());
4692 context->set_closure(function);
4693 context->set_previous(function->context());
4694 context->set_extension(NULL);
4695 context->set_global(function->context()->global());
4700 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4703 Object* thrown_object) {
4704 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4706 { MaybeObject* maybe_result =
4707 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4708 if (!maybe_result->ToObject(&result)) return maybe_result;
4710 Context* context = reinterpret_cast<Context*>(result);
4711 context->set_map_no_write_barrier(catch_context_map());
4712 context->set_closure(function);
4713 context->set_previous(previous);
4714 context->set_extension(name);
4715 context->set_global(previous->global());
4716 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4721 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4723 JSObject* extension) {
4725 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4726 if (!maybe_result->ToObject(&result)) return maybe_result;
4728 Context* context = reinterpret_cast<Context*>(result);
4729 context->set_map_no_write_barrier(with_context_map());
4730 context->set_closure(function);
4731 context->set_previous(previous);
4732 context->set_extension(extension);
4733 context->set_global(previous->global());
4738 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4740 ScopeInfo* scope_info) {
4742 { MaybeObject* maybe_result =
4743 AllocateFixedArrayWithHoles(scope_info->ContextLength());
4744 if (!maybe_result->ToObject(&result)) return maybe_result;
4746 Context* context = reinterpret_cast<Context*>(result);
4747 context->set_map_no_write_barrier(block_context_map());
4748 context->set_closure(function);
4749 context->set_previous(previous);
4750 context->set_extension(scope_info);
4751 context->set_global(previous->global());
4756 MaybeObject* Heap::AllocateScopeInfo(int length) {
4757 FixedArray* scope_info;
4758 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4759 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4760 scope_info->set_map_no_write_barrier(scope_info_map());
4765 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4768 #define MAKE_CASE(NAME, Name, name) \
4769 case NAME##_TYPE: map = name##_map(); break;
4770 STRUCT_LIST(MAKE_CASE)
4774 return Failure::InternalError();
4776 int size = map->instance_size();
4777 AllocationSpace space =
4778 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
4780 { MaybeObject* maybe_result = Allocate(map, space);
4781 if (!maybe_result->ToObject(&result)) return maybe_result;
4783 Struct::cast(result)->InitializeBody(size);
4788 bool Heap::IsHeapIterable() {
4789 return (!old_pointer_space()->was_swept_conservatively() &&
4790 !old_data_space()->was_swept_conservatively());
4794 void Heap::EnsureHeapIsIterable() {
4795 ASSERT(IsAllocationAllowed());
4796 if (!IsHeapIterable()) {
4797 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
4799 ASSERT(IsHeapIterable());
4803 bool Heap::IdleNotification(int hint) {
4804 if (hint >= 1000) return IdleGlobalGC();
4805 if (contexts_disposed_ > 0 || !FLAG_incremental_marking ||
4806 FLAG_expose_gc || Serializer::enabled()) {
4810 // By doing small chunks of GC work in each IdleNotification,
4811 // perform a round of incremental GCs and after that wait until
4812 // the mutator creates enough garbage to justify a new round.
4813 // An incremental GC progresses as follows:
4814 // 1. many incremental marking steps,
4815 // 2. one old space mark-sweep-compact,
4816 // 3. many lazy sweep steps.
4817 // Use mark-sweep-compact events to count incremental GCs in a round.
4819 intptr_t size_factor = Min(Max(hint, 30), 1000) / 10;
4820 // The size factor is in range [3..100].
4821 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
4823 if (incremental_marking()->IsStopped()) {
4824 if (!IsSweepingComplete() &&
4825 !AdvanceSweepers(static_cast<int>(step_size))) {
4830 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4831 if (EnoughGarbageSinceLastIdleRound()) {
4838 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
4839 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
4840 ms_count_at_last_idle_notification_ = ms_count_;
4842 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
4847 if (incremental_marking()->IsStopped()) {
4848 if (hint < 1000 && !WorthStartingGCWhenIdle()) {
4852 incremental_marking()->Start();
4855 // This flag prevents incremental marking from requesting GC via stack guard
4856 idle_notification_will_schedule_next_gc_ = true;
4857 incremental_marking()->Step(step_size);
4858 idle_notification_will_schedule_next_gc_ = false;
4860 if (incremental_marking()->IsComplete()) {
4861 bool uncommit = false;
4862 if (gc_count_at_last_idle_gc_ == gc_count_) {
4863 // No GC since the last full GC, the mutator is probably not active.
4864 isolate_->compilation_cache()->Clear();
4867 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4868 gc_count_at_last_idle_gc_ = gc_count_;
4870 new_space_.Shrink();
4871 UncommitFromSpace();
4878 bool Heap::IdleGlobalGC() {
4879 static const int kIdlesBeforeScavenge = 4;
4880 static const int kIdlesBeforeMarkSweep = 7;
4881 static const int kIdlesBeforeMarkCompact = 8;
4882 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
4883 static const unsigned int kGCsBetweenCleanup = 4;
4885 if (!last_idle_notification_gc_count_init_) {
4886 last_idle_notification_gc_count_ = gc_count_;
4887 last_idle_notification_gc_count_init_ = true;
4890 bool uncommit = true;
4891 bool finished = false;
4893 // Reset the number of idle notifications received when a number of
4894 // GCs have taken place. This allows another round of cleanup based
4895 // on idle notifications if enough work has been carried out to
4896 // provoke a number of garbage collections.
4897 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
4898 number_idle_notifications_ =
4899 Min(number_idle_notifications_ + 1, kMaxIdleCount);
4901 number_idle_notifications_ = 0;
4902 last_idle_notification_gc_count_ = gc_count_;
4905 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
4906 if (contexts_disposed_ > 0) {
4907 HistogramTimerScope scope(isolate_->counters()->gc_context());
4908 CollectAllGarbage(kReduceMemoryFootprintMask,
4909 "idle notification: contexts disposed");
4911 CollectGarbage(NEW_SPACE, "idle notification");
4913 new_space_.Shrink();
4914 last_idle_notification_gc_count_ = gc_count_;
4915 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
4916 // Before doing the mark-sweep collections we clear the
4917 // compilation cache to avoid hanging on to source code and
4918 // generated code for cached functions.
4919 isolate_->compilation_cache()->Clear();
4921 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
4922 new_space_.Shrink();
4923 last_idle_notification_gc_count_ = gc_count_;
4925 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
4926 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
4927 new_space_.Shrink();
4928 last_idle_notification_gc_count_ = gc_count_;
4929 number_idle_notifications_ = 0;
4931 } else if (contexts_disposed_ > 0) {
4932 if (FLAG_expose_gc) {
4933 contexts_disposed_ = 0;
4935 HistogramTimerScope scope(isolate_->counters()->gc_context());
4936 CollectAllGarbage(kReduceMemoryFootprintMask,
4937 "idle notification: contexts disposed");
4938 last_idle_notification_gc_count_ = gc_count_;
4940 // If this is the first idle notification, we reset the
4941 // notification count to avoid letting idle notifications for
4942 // context disposal garbage collections start a potentially too
4943 // aggressive idle GC cycle.
4944 if (number_idle_notifications_ <= 1) {
4945 number_idle_notifications_ = 0;
4948 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
4949 // If we have received more than kIdlesBeforeMarkCompact idle
4950 // notifications we do not perform any cleanup because we don't
4951 // expect to gain much by doing so.
4955 // Make sure that we have no pending context disposals and
4956 // conditionally uncommit from space.
4957 // Take into account that we might have decided to delay full collection
4958 // because incremental marking is in progress.
4959 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
4960 if (uncommit) UncommitFromSpace();
4968 void Heap::Print() {
4969 if (!HasBeenSetUp()) return;
4970 isolate()->PrintStack();
4972 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4977 void Heap::ReportCodeStatistics(const char* title) {
4978 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
4979 PagedSpace::ResetCodeStatistics();
4980 // We do not look for code in new space, map space, or old space. If code
4981 // somehow ends up in those spaces, we would miss it here.
4982 code_space_->CollectCodeStatistics();
4983 lo_space_->CollectCodeStatistics();
4984 PagedSpace::ReportCodeStatistics();
4988 // This function expects that NewSpace's allocated objects histogram is
4989 // populated (via a call to CollectStatistics or else as a side effect of a
4990 // just-completed scavenge collection).
4991 void Heap::ReportHeapStatistics(const char* title) {
4993 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
4995 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
4996 old_gen_promotion_limit_);
4997 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
4998 old_gen_allocation_limit_);
4999 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5002 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5003 isolate_->global_handles()->PrintStats();
5006 PrintF("Heap statistics : ");
5007 isolate_->memory_allocator()->ReportStatistics();
5008 PrintF("To space : ");
5009 new_space_.ReportStatistics();
5010 PrintF("Old pointer space : ");
5011 old_pointer_space_->ReportStatistics();
5012 PrintF("Old data space : ");
5013 old_data_space_->ReportStatistics();
5014 PrintF("Code space : ");
5015 code_space_->ReportStatistics();
5016 PrintF("Map space : ");
5017 map_space_->ReportStatistics();
5018 PrintF("Cell space : ");
5019 cell_space_->ReportStatistics();
5020 PrintF("Large object space : ");
5021 lo_space_->ReportStatistics();
5022 PrintF(">>>>>> ========================================= >>>>>>\n");
5027 bool Heap::Contains(HeapObject* value) {
5028 return Contains(value->address());
5032 bool Heap::Contains(Address addr) {
5033 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5034 return HasBeenSetUp() &&
5035 (new_space_.ToSpaceContains(addr) ||
5036 old_pointer_space_->Contains(addr) ||
5037 old_data_space_->Contains(addr) ||
5038 code_space_->Contains(addr) ||
5039 map_space_->Contains(addr) ||
5040 cell_space_->Contains(addr) ||
5041 lo_space_->SlowContains(addr));
5045 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5046 return InSpace(value->address(), space);
5050 bool Heap::InSpace(Address addr, AllocationSpace space) {
5051 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5052 if (!HasBeenSetUp()) return false;
5056 return new_space_.ToSpaceContains(addr);
5057 case OLD_POINTER_SPACE:
5058 return old_pointer_space_->Contains(addr);
5059 case OLD_DATA_SPACE:
5060 return old_data_space_->Contains(addr);
5062 return code_space_->Contains(addr);
5064 return map_space_->Contains(addr);
5066 return cell_space_->Contains(addr);
5068 return lo_space_->SlowContains(addr);
5076 void Heap::Verify() {
5077 ASSERT(HasBeenSetUp());
5079 store_buffer()->Verify();
5081 VerifyPointersVisitor visitor;
5082 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5084 new_space_.Verify();
5086 old_pointer_space_->Verify(&visitor);
5087 map_space_->Verify(&visitor);
5089 VerifyPointersVisitor no_dirty_regions_visitor;
5090 old_data_space_->Verify(&no_dirty_regions_visitor);
5091 code_space_->Verify(&no_dirty_regions_visitor);
5092 cell_space_->Verify(&no_dirty_regions_visitor);
5094 lo_space_->Verify();
5096 VerifyNoAccessorPairSharing();
5100 void Heap::VerifyNoAccessorPairSharing() {
5101 // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5102 // that we mark only unmarked pairs, then we clear all marks, restoring the
5103 // initial state. We use the Smi tag of the AccessorPair's getter as the
5104 // marking bit, because we can never see a Smi as the getter.
5105 for (int phase = 0; phase < 2; phase++) {
5106 HeapObjectIterator iter(map_space());
5107 for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5109 DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5110 for (int i = 0; i < descs->number_of_descriptors(); i++) {
5111 if (descs->GetType(i) == CALLBACKS &&
5112 descs->GetValue(i)->IsAccessorPair()) {
5113 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5114 uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5115 uintptr_t after = (phase == 0) ?
5116 ((before & ~kSmiTagMask) | kSmiTag) :
5117 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5118 CHECK(before != after);
5119 accessors->set_getter(reinterpret_cast<Object*>(after));
5129 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5130 Object* symbol = NULL;
5132 { MaybeObject* maybe_new_table =
5133 symbol_table()->LookupSymbol(string, &symbol);
5134 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5136 // Can't use set_symbol_table because SymbolTable::cast knows that
5137 // SymbolTable is a singleton and checks for identity.
5138 roots_[kSymbolTableRootIndex] = new_table;
5139 ASSERT(symbol != NULL);
5144 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5145 Object* symbol = NULL;
5147 { MaybeObject* maybe_new_table =
5148 symbol_table()->LookupAsciiSymbol(string, &symbol);
5149 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5151 // Can't use set_symbol_table because SymbolTable::cast knows that
5152 // SymbolTable is a singleton and checks for identity.
5153 roots_[kSymbolTableRootIndex] = new_table;
5154 ASSERT(symbol != NULL);
5159 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5162 Object* symbol = NULL;
5164 { MaybeObject* maybe_new_table =
5165 symbol_table()->LookupSubStringAsciiSymbol(string,
5169 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5171 // Can't use set_symbol_table because SymbolTable::cast knows that
5172 // SymbolTable is a singleton and checks for identity.
5173 roots_[kSymbolTableRootIndex] = new_table;
5174 ASSERT(symbol != NULL);
5179 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5180 Object* symbol = NULL;
5182 { MaybeObject* maybe_new_table =
5183 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5184 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5186 // Can't use set_symbol_table because SymbolTable::cast knows that
5187 // SymbolTable is a singleton and checks for identity.
5188 roots_[kSymbolTableRootIndex] = new_table;
5189 ASSERT(symbol != NULL);
5194 MaybeObject* Heap::LookupSymbol(String* string) {
5195 if (string->IsSymbol()) return string;
5196 Object* symbol = NULL;
5198 { MaybeObject* maybe_new_table =
5199 symbol_table()->LookupString(string, &symbol);
5200 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5202 // Can't use set_symbol_table because SymbolTable::cast knows that
5203 // SymbolTable is a singleton and checks for identity.
5204 roots_[kSymbolTableRootIndex] = new_table;
5205 ASSERT(symbol != NULL);
5210 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5211 if (string->IsSymbol()) {
5215 return symbol_table()->LookupSymbolIfExists(string, symbol);
5220 void Heap::ZapFromSpace() {
5221 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5222 new_space_.FromSpaceEnd());
5223 while (it.has_next()) {
5224 NewSpacePage* page = it.next();
5225 for (Address cursor = page->area_start(), limit = page->area_end();
5227 cursor += kPointerSize) {
5228 Memory::Address_at(cursor) = kFromSpaceZapValue;
5235 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5237 ObjectSlotCallback callback) {
5238 Address slot_address = start;
5240 // We are not collecting slots on new space objects during mutation
5241 // thus we have to scan for pointers to evacuation candidates when we
5242 // promote objects. But we should not record any slots in non-black
5243 // objects. Grey object's slots would be rescanned.
5244 // White object might not survive until the end of collection
5245 // it would be a violation of the invariant to record it's slots.
5246 bool record_slots = false;
5247 if (incremental_marking()->IsCompacting()) {
5248 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5249 record_slots = Marking::IsBlack(mark_bit);
5252 while (slot_address < end) {
5253 Object** slot = reinterpret_cast<Object**>(slot_address);
5254 Object* object = *slot;
5255 // If the store buffer becomes overfull we mark pages as being exempt from
5256 // the store buffer. These pages are scanned to find pointers that point
5257 // to the new space. In that case we may hit newly promoted objects and
5258 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5259 if (object->IsHeapObject()) {
5260 if (Heap::InFromSpace(object)) {
5261 callback(reinterpret_cast<HeapObject**>(slot),
5262 HeapObject::cast(object));
5263 Object* new_object = *slot;
5264 if (InNewSpace(new_object)) {
5265 SLOW_ASSERT(Heap::InToSpace(new_object));
5266 SLOW_ASSERT(new_object->IsHeapObject());
5267 store_buffer_.EnterDirectlyIntoStoreBuffer(
5268 reinterpret_cast<Address>(slot));
5270 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5271 } else if (record_slots &&
5272 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5273 mark_compact_collector()->RecordSlot(slot, slot, object);
5276 slot_address += kPointerSize;
5282 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5285 bool IsAMapPointerAddress(Object** addr) {
5286 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5287 int mod = a % Map::kSize;
5288 return mod >= Map::kPointerFieldsBeginOffset &&
5289 mod < Map::kPointerFieldsEndOffset;
5293 bool EverythingsAPointer(Object** addr) {
5298 static void CheckStoreBuffer(Heap* heap,
5301 Object**** store_buffer_position,
5302 Object*** store_buffer_top,
5303 CheckStoreBufferFilter filter,
5304 Address special_garbage_start,
5305 Address special_garbage_end) {
5306 Map* free_space_map = heap->free_space_map();
5307 for ( ; current < limit; current++) {
5308 Object* o = *current;
5309 Address current_address = reinterpret_cast<Address>(current);
5311 if (o == free_space_map) {
5312 Address current_address = reinterpret_cast<Address>(current);
5313 FreeSpace* free_space =
5314 FreeSpace::cast(HeapObject::FromAddress(current_address));
5315 int skip = free_space->Size();
5316 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5318 current_address += skip - kPointerSize;
5319 current = reinterpret_cast<Object**>(current_address);
5322 // Skip the current linear allocation space between top and limit which is
5323 // unmarked with the free space map, but can contain junk.
5324 if (current_address == special_garbage_start &&
5325 special_garbage_end != special_garbage_start) {
5326 current_address = special_garbage_end - kPointerSize;
5327 current = reinterpret_cast<Object**>(current_address);
5330 if (!(*filter)(current)) continue;
5331 ASSERT(current_address < special_garbage_start ||
5332 current_address >= special_garbage_end);
5333 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5334 // We have to check that the pointer does not point into new space
5335 // without trying to cast it to a heap object since the hash field of
5336 // a string can contain values like 1 and 3 which are tagged null
5338 if (!heap->InNewSpace(o)) continue;
5339 while (**store_buffer_position < current &&
5340 *store_buffer_position < store_buffer_top) {
5341 (*store_buffer_position)++;
5343 if (**store_buffer_position != current ||
5344 *store_buffer_position == store_buffer_top) {
5345 Object** obj_start = current;
5346 while (!(*obj_start)->IsMap()) obj_start--;
5353 // Check that the store buffer contains all intergenerational pointers by
5354 // scanning a page and ensuring that all pointers to young space are in the
5356 void Heap::OldPointerSpaceCheckStoreBuffer() {
5357 OldSpace* space = old_pointer_space();
5358 PageIterator pages(space);
5360 store_buffer()->SortUniq();
5362 while (pages.has_next()) {
5363 Page* page = pages.next();
5364 Object** current = reinterpret_cast<Object**>(page->area_start());
5366 Address end = page->area_end();
5368 Object*** store_buffer_position = store_buffer()->Start();
5369 Object*** store_buffer_top = store_buffer()->Top();
5371 Object** limit = reinterpret_cast<Object**>(end);
5372 CheckStoreBuffer(this,
5375 &store_buffer_position,
5377 &EverythingsAPointer,
5384 void Heap::MapSpaceCheckStoreBuffer() {
5385 MapSpace* space = map_space();
5386 PageIterator pages(space);
5388 store_buffer()->SortUniq();
5390 while (pages.has_next()) {
5391 Page* page = pages.next();
5392 Object** current = reinterpret_cast<Object**>(page->area_start());
5394 Address end = page->area_end();
5396 Object*** store_buffer_position = store_buffer()->Start();
5397 Object*** store_buffer_top = store_buffer()->Top();
5399 Object** limit = reinterpret_cast<Object**>(end);
5400 CheckStoreBuffer(this,
5403 &store_buffer_position,
5405 &IsAMapPointerAddress,
5412 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5413 LargeObjectIterator it(lo_space());
5414 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5415 // We only have code, sequential strings, or fixed arrays in large
5416 // object space, and only fixed arrays can possibly contain pointers to
5417 // the young generation.
5418 if (object->IsFixedArray()) {
5419 Object*** store_buffer_position = store_buffer()->Start();
5420 Object*** store_buffer_top = store_buffer()->Top();
5421 Object** current = reinterpret_cast<Object**>(object->address());
5423 reinterpret_cast<Object**>(object->address() + object->Size());
5424 CheckStoreBuffer(this,
5427 &store_buffer_position,
5429 &EverythingsAPointer,
5438 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5439 IterateStrongRoots(v, mode);
5440 IterateWeakRoots(v, mode);
5444 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5445 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5446 v->Synchronize(VisitorSynchronization::kSymbolTable);
5447 if (mode != VISIT_ALL_IN_SCAVENGE &&
5448 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5449 // Scavenge collections have special processing for this.
5450 external_string_table_.Iterate(v);
5452 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5456 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5457 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5458 v->Synchronize(VisitorSynchronization::kStrongRootList);
5460 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5461 v->Synchronize(VisitorSynchronization::kSymbol);
5463 isolate_->bootstrapper()->Iterate(v);
5464 v->Synchronize(VisitorSynchronization::kBootstrapper);
5465 isolate_->Iterate(v);
5466 v->Synchronize(VisitorSynchronization::kTop);
5467 Relocatable::Iterate(v);
5468 v->Synchronize(VisitorSynchronization::kRelocatable);
5470 #ifdef ENABLE_DEBUGGER_SUPPORT
5471 isolate_->debug()->Iterate(v);
5472 if (isolate_->deoptimizer_data() != NULL) {
5473 isolate_->deoptimizer_data()->Iterate(v);
5476 v->Synchronize(VisitorSynchronization::kDebug);
5477 isolate_->compilation_cache()->Iterate(v);
5478 v->Synchronize(VisitorSynchronization::kCompilationCache);
5480 // Iterate over local handles in handle scopes.
5481 isolate_->handle_scope_implementer()->Iterate(v);
5482 v->Synchronize(VisitorSynchronization::kHandleScope);
5484 // Iterate over the builtin code objects and code stubs in the
5485 // heap. Note that it is not necessary to iterate over code objects
5486 // on scavenge collections.
5487 if (mode != VISIT_ALL_IN_SCAVENGE) {
5488 isolate_->builtins()->IterateBuiltins(v);
5490 v->Synchronize(VisitorSynchronization::kBuiltins);
5492 // Iterate over global handles.
5494 case VISIT_ONLY_STRONG:
5495 isolate_->global_handles()->IterateStrongRoots(v);
5497 case VISIT_ALL_IN_SCAVENGE:
5498 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5500 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5502 isolate_->global_handles()->IterateAllRoots(v);
5505 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5507 // Iterate over pointers being held by inactive threads.
5508 isolate_->thread_manager()->Iterate(v);
5509 v->Synchronize(VisitorSynchronization::kThreadManager);
5511 // Iterate over the pointers the Serialization/Deserialization code is
5513 // During garbage collection this keeps the partial snapshot cache alive.
5514 // During deserialization of the startup snapshot this creates the partial
5515 // snapshot cache and deserializes the objects it refers to. During
5516 // serialization this does nothing, since the partial snapshot cache is
5517 // empty. However the next thing we do is create the partial snapshot,
5518 // filling up the partial snapshot cache with objects it needs as we go.
5519 SerializerDeserializer::Iterate(v);
5520 // We don't do a v->Synchronize call here, because in debug mode that will
5521 // output a flag to the snapshot. However at this point the serializer and
5522 // deserializer are deliberately a little unsynchronized (see above) so the
5523 // checking of the sync flag in the snapshot would fail.
5527 // TODO(1236194): Since the heap size is configurable on the command line
5528 // and through the API, we should gracefully handle the case that the heap
5529 // size is not big enough to fit all the initial objects.
5530 bool Heap::ConfigureHeap(int max_semispace_size,
5531 intptr_t max_old_gen_size,
5532 intptr_t max_executable_size) {
5533 if (HasBeenSetUp()) return false;
5535 if (max_semispace_size > 0) {
5536 if (max_semispace_size < Page::kPageSize) {
5537 max_semispace_size = Page::kPageSize;
5538 if (FLAG_trace_gc) {
5539 PrintF("Max semispace size cannot be less than %dkbytes\n",
5540 Page::kPageSize >> 10);
5543 max_semispace_size_ = max_semispace_size;
5546 if (Snapshot::IsEnabled()) {
5547 // If we are using a snapshot we always reserve the default amount
5548 // of memory for each semispace because code in the snapshot has
5549 // write-barrier code that relies on the size and alignment of new
5550 // space. We therefore cannot use a larger max semispace size
5551 // than the default reserved semispace size.
5552 if (max_semispace_size_ > reserved_semispace_size_) {
5553 max_semispace_size_ = reserved_semispace_size_;
5554 if (FLAG_trace_gc) {
5555 PrintF("Max semispace size cannot be more than %dkbytes\n",
5556 reserved_semispace_size_ >> 10);
5560 // If we are not using snapshots we reserve space for the actual
5561 // max semispace size.
5562 reserved_semispace_size_ = max_semispace_size_;
5565 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5566 if (max_executable_size > 0) {
5567 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5570 // The max executable size must be less than or equal to the max old
5572 if (max_executable_size_ > max_old_generation_size_) {
5573 max_executable_size_ = max_old_generation_size_;
5576 // The new space size must be a power of two to support single-bit testing
5578 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5579 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5580 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5581 external_allocation_limit_ = 10 * max_semispace_size_;
5583 // The old generation is paged and needs at least one page for each space.
5584 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5585 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5587 RoundUp(max_old_generation_size_,
5595 bool Heap::ConfigureHeapDefault() {
5596 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5597 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5598 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5602 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5603 *stats->start_marker = HeapStats::kStartMarker;
5604 *stats->end_marker = HeapStats::kEndMarker;
5605 *stats->new_space_size = new_space_.SizeAsInt();
5606 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5607 *stats->old_pointer_space_size = old_pointer_space_->Size();
5608 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5609 *stats->old_data_space_size = old_data_space_->Size();
5610 *stats->old_data_space_capacity = old_data_space_->Capacity();
5611 *stats->code_space_size = code_space_->Size();
5612 *stats->code_space_capacity = code_space_->Capacity();
5613 *stats->map_space_size = map_space_->Size();
5614 *stats->map_space_capacity = map_space_->Capacity();
5615 *stats->cell_space_size = cell_space_->Size();
5616 *stats->cell_space_capacity = cell_space_->Capacity();
5617 *stats->lo_space_size = lo_space_->Size();
5618 isolate_->global_handles()->RecordStats(stats);
5619 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5620 *stats->memory_allocator_capacity =
5621 isolate()->memory_allocator()->Size() +
5622 isolate()->memory_allocator()->Available();
5623 *stats->os_error = OS::GetLastError();
5624 isolate()->memory_allocator()->Available();
5625 if (take_snapshot) {
5626 HeapIterator iterator;
5627 for (HeapObject* obj = iterator.next();
5629 obj = iterator.next()) {
5630 InstanceType type = obj->map()->instance_type();
5631 ASSERT(0 <= type && type <= LAST_TYPE);
5632 stats->objects_per_type[type]++;
5633 stats->size_per_type[type] += obj->Size();
5639 intptr_t Heap::PromotedSpaceSize() {
5640 return old_pointer_space_->Size()
5641 + old_data_space_->Size()
5642 + code_space_->Size()
5643 + map_space_->Size()
5644 + cell_space_->Size()
5645 + lo_space_->Size();
5649 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5650 return old_pointer_space_->SizeOfObjects()
5651 + old_data_space_->SizeOfObjects()
5652 + code_space_->SizeOfObjects()
5653 + map_space_->SizeOfObjects()
5654 + cell_space_->SizeOfObjects()
5655 + lo_space_->SizeOfObjects();
5659 int Heap::PromotedExternalMemorySize() {
5660 if (amount_of_external_allocated_memory_
5661 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5662 return amount_of_external_allocated_memory_
5663 - amount_of_external_allocated_memory_at_last_global_gc_;
5668 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5669 static const int kMarkTag = 2;
5672 class HeapDebugUtils {
5674 explicit HeapDebugUtils(Heap* heap)
5675 : search_for_any_global_(false),
5676 search_target_(NULL),
5677 found_target_(false),
5682 class MarkObjectVisitor : public ObjectVisitor {
5684 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5686 void VisitPointers(Object** start, Object** end) {
5687 // Copy all HeapObject pointers in [start, end)
5688 for (Object** p = start; p < end; p++) {
5689 if ((*p)->IsHeapObject())
5690 utils_->MarkObjectRecursively(p);
5694 HeapDebugUtils* utils_;
5697 void MarkObjectRecursively(Object** p) {
5698 if (!(*p)->IsHeapObject()) return;
5700 HeapObject* obj = HeapObject::cast(*p);
5702 Object* map = obj->map();
5704 if (!map->IsHeapObject()) return; // visited before
5706 if (found_target_) return; // stop if target found
5707 object_stack_.Add(obj);
5708 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5709 (!search_for_any_global_ && (obj == search_target_))) {
5710 found_target_ = true;
5715 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5717 Address map_addr = map_p->address();
5719 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
5721 MarkObjectRecursively(&map);
5723 MarkObjectVisitor mark_visitor(this);
5725 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5728 if (!found_target_) // don't pop if found the target
5729 object_stack_.RemoveLast();
5733 class UnmarkObjectVisitor : public ObjectVisitor {
5735 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5737 void VisitPointers(Object** start, Object** end) {
5738 // Copy all HeapObject pointers in [start, end)
5739 for (Object** p = start; p < end; p++) {
5740 if ((*p)->IsHeapObject())
5741 utils_->UnmarkObjectRecursively(p);
5745 HeapDebugUtils* utils_;
5749 void UnmarkObjectRecursively(Object** p) {
5750 if (!(*p)->IsHeapObject()) return;
5752 HeapObject* obj = HeapObject::cast(*p);
5754 Object* map = obj->map();
5756 if (map->IsHeapObject()) return; // unmarked already
5758 Address map_addr = reinterpret_cast<Address>(map);
5760 map_addr -= kMarkTag;
5762 ASSERT_TAG_ALIGNED(map_addr);
5764 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5766 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
5768 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5770 UnmarkObjectVisitor unmark_visitor(this);
5772 obj->IterateBody(Map::cast(map_p)->instance_type(),
5773 obj->SizeFromMap(Map::cast(map_p)),
5778 void MarkRootObjectRecursively(Object** root) {
5779 if (search_for_any_global_) {
5780 ASSERT(search_target_ == NULL);
5782 ASSERT(search_target_->IsHeapObject());
5784 found_target_ = false;
5785 object_stack_.Clear();
5787 MarkObjectRecursively(root);
5788 UnmarkObjectRecursively(root);
5790 if (found_target_) {
5791 PrintF("=====================================\n");
5792 PrintF("==== Path to object ====\n");
5793 PrintF("=====================================\n\n");
5795 ASSERT(!object_stack_.is_empty());
5796 for (int i = 0; i < object_stack_.length(); i++) {
5797 if (i > 0) PrintF("\n |\n |\n V\n\n");
5798 Object* obj = object_stack_[i];
5801 PrintF("=====================================\n");
5805 // Helper class for visiting HeapObjects recursively.
5806 class MarkRootVisitor: public ObjectVisitor {
5808 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5810 void VisitPointers(Object** start, Object** end) {
5811 // Visit all HeapObject pointers in [start, end)
5812 for (Object** p = start; p < end; p++) {
5813 if ((*p)->IsHeapObject())
5814 utils_->MarkRootObjectRecursively(p);
5818 HeapDebugUtils* utils_;
5821 bool search_for_any_global_;
5822 Object* search_target_;
5824 List<Object*> object_stack_;
5832 bool Heap::SetUp(bool create_heap_objects) {
5834 allocation_timeout_ = FLAG_gc_interval;
5835 debug_utils_ = new HeapDebugUtils(this);
5838 // Initialize heap spaces and initial maps and objects. Whenever something
5839 // goes wrong, just return false. The caller should check the results and
5840 // call Heap::TearDown() to release allocated memory.
5842 // If the heap is not yet configured (e.g. through the API), configure it.
5843 // Configuration is based on the flags new-space-size (really the semispace
5844 // size) and old-space-size if set or the initial values of semispace_size_
5845 // and old_generation_size_ otherwise.
5847 if (!ConfigureHeapDefault()) return false;
5850 gc_initializer_mutex->Lock();
5851 static bool initialized_gc = false;
5852 if (!initialized_gc) {
5853 initialized_gc = true;
5854 InitializeScavengingVisitorsTables();
5855 NewSpaceScavenger::Initialize();
5856 MarkCompactCollector::Initialize();
5858 gc_initializer_mutex->Unlock();
5860 MarkMapPointersAsEncoded(false);
5862 // Set up memory allocator.
5863 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
5866 // Set up new space.
5867 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
5871 // Initialize old pointer space.
5872 old_pointer_space_ =
5874 max_old_generation_size_,
5877 if (old_pointer_space_ == NULL) return false;
5878 if (!old_pointer_space_->SetUp()) return false;
5880 // Initialize old data space.
5883 max_old_generation_size_,
5886 if (old_data_space_ == NULL) return false;
5887 if (!old_data_space_->SetUp()) return false;
5889 // Initialize the code space, set its maximum capacity to the old
5890 // generation size. It needs executable memory.
5891 // On 64-bit platform(s), we put all code objects in a 2 GB range of
5892 // virtual address space, so that they can call each other with near calls.
5893 if (code_range_size_ > 0) {
5894 if (!isolate_->code_range()->SetUp(code_range_size_)) {
5900 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
5901 if (code_space_ == NULL) return false;
5902 if (!code_space_->SetUp()) return false;
5904 // Initialize map space.
5905 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
5906 if (map_space_ == NULL) return false;
5907 if (!map_space_->SetUp()) return false;
5909 // Initialize global property cell space.
5910 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
5911 if (cell_space_ == NULL) return false;
5912 if (!cell_space_->SetUp()) return false;
5914 // The large object code space may contain code or data. We set the memory
5915 // to be non-executable here for safety, but this means we need to enable it
5916 // explicitly when allocating large code objects.
5917 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
5918 if (lo_space_ == NULL) return false;
5919 if (!lo_space_->SetUp()) return false;
5921 // Set up the seed that is used to randomize the string hash function.
5922 ASSERT(hash_seed() == 0);
5923 if (FLAG_randomize_hashes) {
5924 if (FLAG_hash_seed == 0) {
5926 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
5928 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5932 if (create_heap_objects) {
5933 // Create initial maps.
5934 if (!CreateInitialMaps()) return false;
5935 if (!CreateApiObjects()) return false;
5937 // Create initial objects
5938 if (!CreateInitialObjects()) return false;
5940 global_contexts_list_ = undefined_value();
5943 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5944 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
5946 store_buffer()->SetUp();
5952 void Heap::SetStackLimits() {
5953 ASSERT(isolate_ != NULL);
5954 ASSERT(isolate_ == isolate());
5955 // On 64 bit machines, pointers are generally out of range of Smis. We write
5956 // something that looks like an out of range Smi to the GC.
5958 // Set up the special root array entries containing the stack limits.
5959 // These are actually addresses, but the tag makes the GC ignore it.
5960 roots_[kStackLimitRootIndex] =
5961 reinterpret_cast<Object*>(
5962 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
5963 roots_[kRealStackLimitRootIndex] =
5964 reinterpret_cast<Object*>(
5965 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
5969 void Heap::TearDown() {
5970 if (FLAG_print_cumulative_gc_stat) {
5972 PrintF("gc_count=%d ", gc_count_);
5973 PrintF("mark_sweep_count=%d ", ms_count_);
5974 PrintF("max_gc_pause=%d ", get_max_gc_pause());
5975 PrintF("min_in_mutator=%d ", get_min_in_mutator());
5976 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
5977 get_max_alive_after_gc());
5981 isolate_->global_handles()->TearDown();
5983 external_string_table_.TearDown();
5985 new_space_.TearDown();
5987 if (old_pointer_space_ != NULL) {
5988 old_pointer_space_->TearDown();
5989 delete old_pointer_space_;
5990 old_pointer_space_ = NULL;
5993 if (old_data_space_ != NULL) {
5994 old_data_space_->TearDown();
5995 delete old_data_space_;
5996 old_data_space_ = NULL;
5999 if (code_space_ != NULL) {
6000 code_space_->TearDown();
6005 if (map_space_ != NULL) {
6006 map_space_->TearDown();
6011 if (cell_space_ != NULL) {
6012 cell_space_->TearDown();
6017 if (lo_space_ != NULL) {
6018 lo_space_->TearDown();
6023 store_buffer()->TearDown();
6024 incremental_marking()->TearDown();
6026 isolate_->memory_allocator()->TearDown();
6029 delete debug_utils_;
6030 debug_utils_ = NULL;
6035 void Heap::Shrink() {
6036 // Try to shrink all paged spaces.
6038 for (PagedSpace* space = spaces.next();
6040 space = spaces.next()) {
6041 space->ReleaseAllUnusedPages();
6046 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6047 ASSERT(callback != NULL);
6048 GCPrologueCallbackPair pair(callback, gc_type);
6049 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6050 return gc_prologue_callbacks_.Add(pair);
6054 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6055 ASSERT(callback != NULL);
6056 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6057 if (gc_prologue_callbacks_[i].callback == callback) {
6058 gc_prologue_callbacks_.Remove(i);
6066 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6067 ASSERT(callback != NULL);
6068 GCEpilogueCallbackPair pair(callback, gc_type);
6069 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6070 return gc_epilogue_callbacks_.Add(pair);
6074 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6075 ASSERT(callback != NULL);
6076 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6077 if (gc_epilogue_callbacks_[i].callback == callback) {
6078 gc_epilogue_callbacks_.Remove(i);
6088 class PrintHandleVisitor: public ObjectVisitor {
6090 void VisitPointers(Object** start, Object** end) {
6091 for (Object** p = start; p < end; p++)
6092 PrintF(" handle %p to %p\n",
6093 reinterpret_cast<void*>(p),
6094 reinterpret_cast<void*>(*p));
6098 void Heap::PrintHandles() {
6099 PrintF("Handles:\n");
6100 PrintHandleVisitor v;
6101 isolate_->handle_scope_implementer()->Iterate(&v);
6107 Space* AllSpaces::next() {
6108 switch (counter_++) {
6110 return HEAP->new_space();
6111 case OLD_POINTER_SPACE:
6112 return HEAP->old_pointer_space();
6113 case OLD_DATA_SPACE:
6114 return HEAP->old_data_space();
6116 return HEAP->code_space();
6118 return HEAP->map_space();
6120 return HEAP->cell_space();
6122 return HEAP->lo_space();
6129 PagedSpace* PagedSpaces::next() {
6130 switch (counter_++) {
6131 case OLD_POINTER_SPACE:
6132 return HEAP->old_pointer_space();
6133 case OLD_DATA_SPACE:
6134 return HEAP->old_data_space();
6136 return HEAP->code_space();
6138 return HEAP->map_space();
6140 return HEAP->cell_space();
6148 OldSpace* OldSpaces::next() {
6149 switch (counter_++) {
6150 case OLD_POINTER_SPACE:
6151 return HEAP->old_pointer_space();
6152 case OLD_DATA_SPACE:
6153 return HEAP->old_data_space();
6155 return HEAP->code_space();
6162 SpaceIterator::SpaceIterator()
6163 : current_space_(FIRST_SPACE),
6169 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6170 : current_space_(FIRST_SPACE),
6172 size_func_(size_func) {
6176 SpaceIterator::~SpaceIterator() {
6177 // Delete active iterator if any.
6182 bool SpaceIterator::has_next() {
6183 // Iterate until no more spaces.
6184 return current_space_ != LAST_SPACE;
6188 ObjectIterator* SpaceIterator::next() {
6189 if (iterator_ != NULL) {
6192 // Move to the next space
6194 if (current_space_ > LAST_SPACE) {
6199 // Return iterator for the new current space.
6200 return CreateIterator();
6204 // Create an iterator for the space to iterate.
6205 ObjectIterator* SpaceIterator::CreateIterator() {
6206 ASSERT(iterator_ == NULL);
6208 switch (current_space_) {
6210 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6212 case OLD_POINTER_SPACE:
6213 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6215 case OLD_DATA_SPACE:
6216 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6219 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6222 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6225 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6228 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6232 // Return the newly allocated iterator;
6233 ASSERT(iterator_ != NULL);
6238 class HeapObjectsFilter {
6240 virtual ~HeapObjectsFilter() {}
6241 virtual bool SkipObject(HeapObject* object) = 0;
6245 class UnreachableObjectsFilter : public HeapObjectsFilter {
6247 UnreachableObjectsFilter() {
6248 MarkReachableObjects();
6251 ~UnreachableObjectsFilter() {
6252 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6255 bool SkipObject(HeapObject* object) {
6256 MarkBit mark_bit = Marking::MarkBitFrom(object);
6257 return !mark_bit.Get();
6261 class MarkingVisitor : public ObjectVisitor {
6263 MarkingVisitor() : marking_stack_(10) {}
6265 void VisitPointers(Object** start, Object** end) {
6266 for (Object** p = start; p < end; p++) {
6267 if (!(*p)->IsHeapObject()) continue;
6268 HeapObject* obj = HeapObject::cast(*p);
6269 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6270 if (!mark_bit.Get()) {
6272 marking_stack_.Add(obj);
6277 void TransitiveClosure() {
6278 while (!marking_stack_.is_empty()) {
6279 HeapObject* obj = marking_stack_.RemoveLast();
6285 List<HeapObject*> marking_stack_;
6288 void MarkReachableObjects() {
6289 Heap* heap = Isolate::Current()->heap();
6290 MarkingVisitor visitor;
6291 heap->IterateRoots(&visitor, VISIT_ALL);
6292 visitor.TransitiveClosure();
6295 AssertNoAllocation no_alloc;
6299 HeapIterator::HeapIterator()
6300 : filtering_(HeapIterator::kNoFiltering),
6306 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6307 : filtering_(filtering),
6313 HeapIterator::~HeapIterator() {
6318 void HeapIterator::Init() {
6319 // Start the iteration.
6320 space_iterator_ = new SpaceIterator;
6321 switch (filtering_) {
6322 case kFilterUnreachable:
6323 filter_ = new UnreachableObjectsFilter;
6328 object_iterator_ = space_iterator_->next();
6332 void HeapIterator::Shutdown() {
6334 // Assert that in filtering mode we have iterated through all
6335 // objects. Otherwise, heap will be left in an inconsistent state.
6336 if (filtering_ != kNoFiltering) {
6337 ASSERT(object_iterator_ == NULL);
6340 // Make sure the last iterator is deallocated.
6341 delete space_iterator_;
6342 space_iterator_ = NULL;
6343 object_iterator_ = NULL;
6349 HeapObject* HeapIterator::next() {
6350 if (filter_ == NULL) return NextObject();
6352 HeapObject* obj = NextObject();
6353 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6358 HeapObject* HeapIterator::NextObject() {
6359 // No iterator means we are done.
6360 if (object_iterator_ == NULL) return NULL;
6362 if (HeapObject* obj = object_iterator_->next_object()) {
6363 // If the current iterator has more objects we are fine.
6366 // Go though the spaces looking for one that has objects.
6367 while (space_iterator_->has_next()) {
6368 object_iterator_ = space_iterator_->next();
6369 if (HeapObject* obj = object_iterator_->next_object()) {
6374 // Done with the last space.
6375 object_iterator_ = NULL;
6380 void HeapIterator::reset() {
6381 // Restart the iterator.
6387 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6389 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6391 class PathTracer::MarkVisitor: public ObjectVisitor {
6393 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6394 void VisitPointers(Object** start, Object** end) {
6395 // Scan all HeapObject pointers in [start, end)
6396 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6397 if ((*p)->IsHeapObject())
6398 tracer_->MarkRecursively(p, this);
6403 PathTracer* tracer_;
6407 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6409 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6410 void VisitPointers(Object** start, Object** end) {
6411 // Scan all HeapObject pointers in [start, end)
6412 for (Object** p = start; p < end; p++) {
6413 if ((*p)->IsHeapObject())
6414 tracer_->UnmarkRecursively(p, this);
6419 PathTracer* tracer_;
6423 void PathTracer::VisitPointers(Object** start, Object** end) {
6424 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6425 // Visit all HeapObject pointers in [start, end)
6426 for (Object** p = start; !done && (p < end); p++) {
6427 if ((*p)->IsHeapObject()) {
6429 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6435 void PathTracer::Reset() {
6436 found_target_ = false;
6437 object_stack_.Clear();
6441 void PathTracer::TracePathFrom(Object** root) {
6442 ASSERT((search_target_ == kAnyGlobalObject) ||
6443 search_target_->IsHeapObject());
6444 found_target_in_trace_ = false;
6445 object_stack_.Clear();
6447 MarkVisitor mark_visitor(this);
6448 MarkRecursively(root, &mark_visitor);
6450 UnmarkVisitor unmark_visitor(this);
6451 UnmarkRecursively(root, &unmark_visitor);
6457 static bool SafeIsGlobalContext(HeapObject* obj) {
6458 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6462 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6463 if (!(*p)->IsHeapObject()) return;
6465 HeapObject* obj = HeapObject::cast(*p);
6467 Object* map = obj->map();
6469 if (!map->IsHeapObject()) return; // visited before
6471 if (found_target_in_trace_) return; // stop if target found
6472 object_stack_.Add(obj);
6473 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6474 (obj == search_target_)) {
6475 found_target_in_trace_ = true;
6476 found_target_ = true;
6480 bool is_global_context = SafeIsGlobalContext(obj);
6483 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6485 Address map_addr = map_p->address();
6487 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6489 // Scan the object body.
6490 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6491 // This is specialized to scan Context's properly.
6492 Object** start = reinterpret_cast<Object**>(obj->address() +
6493 Context::kHeaderSize);
6494 Object** end = reinterpret_cast<Object**>(obj->address() +
6495 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6496 mark_visitor->VisitPointers(start, end);
6498 obj->IterateBody(map_p->instance_type(),
6499 obj->SizeFromMap(map_p),
6503 // Scan the map after the body because the body is a lot more interesting
6504 // when doing leak detection.
6505 MarkRecursively(&map, mark_visitor);
6507 if (!found_target_in_trace_) // don't pop if found the target
6508 object_stack_.RemoveLast();
6512 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6513 if (!(*p)->IsHeapObject()) return;
6515 HeapObject* obj = HeapObject::cast(*p);
6517 Object* map = obj->map();
6519 if (map->IsHeapObject()) return; // unmarked already
6521 Address map_addr = reinterpret_cast<Address>(map);
6523 map_addr -= kMarkTag;
6525 ASSERT_TAG_ALIGNED(map_addr);
6527 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6529 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6531 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6533 obj->IterateBody(Map::cast(map_p)->instance_type(),
6534 obj->SizeFromMap(Map::cast(map_p)),
6539 void PathTracer::ProcessResults() {
6540 if (found_target_) {
6541 PrintF("=====================================\n");
6542 PrintF("==== Path to object ====\n");
6543 PrintF("=====================================\n\n");
6545 ASSERT(!object_stack_.is_empty());
6546 for (int i = 0; i < object_stack_.length(); i++) {
6547 if (i > 0) PrintF("\n |\n |\n V\n\n");
6548 Object* obj = object_stack_[i];
6555 PrintF("=====================================\n");
6558 #endif // DEBUG || LIVE_OBJECT_LIST
6562 // Triggers a depth-first traversal of reachable objects from roots
6563 // and finds a path to a specific heap object and prints it.
6564 void Heap::TracePathToObject(Object* target) {
6565 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6566 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6570 // Triggers a depth-first traversal of reachable objects from roots
6571 // and finds a path to any global object and prints it. Useful for
6572 // determining the source for leaks of global objects.
6573 void Heap::TracePathToGlobal() {
6574 PathTracer tracer(PathTracer::kAnyGlobalObject,
6575 PathTracer::FIND_ALL,
6577 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6582 static intptr_t CountTotalHolesSize() {
6583 intptr_t holes_size = 0;
6585 for (OldSpace* space = spaces.next();
6587 space = spaces.next()) {
6588 holes_size += space->Waste() + space->Available();
6594 GCTracer::GCTracer(Heap* heap,
6595 const char* gc_reason,
6596 const char* collector_reason)
6598 start_object_size_(0),
6599 start_memory_size_(0),
6602 allocated_since_last_gc_(0),
6603 spent_in_mutator_(0),
6604 promoted_objects_size_(0),
6606 gc_reason_(gc_reason),
6607 collector_reason_(collector_reason) {
6608 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6609 start_time_ = OS::TimeCurrentMillis();
6610 start_object_size_ = heap_->SizeOfObjects();
6611 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6613 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6617 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6619 allocated_since_last_gc_ =
6620 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6622 if (heap_->last_gc_end_timestamp_ > 0) {
6623 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6626 steps_count_ = heap_->incremental_marking()->steps_count();
6627 steps_took_ = heap_->incremental_marking()->steps_took();
6628 longest_step_ = heap_->incremental_marking()->longest_step();
6629 steps_count_since_last_gc_ =
6630 heap_->incremental_marking()->steps_count_since_last_gc();
6631 steps_took_since_last_gc_ =
6632 heap_->incremental_marking()->steps_took_since_last_gc();
6636 GCTracer::~GCTracer() {
6637 // Printf ONE line iff flag is set.
6638 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6640 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6642 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6643 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6645 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6647 // Update cumulative GC statistics if required.
6648 if (FLAG_print_cumulative_gc_stat) {
6649 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6650 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6651 heap_->alive_after_last_gc_);
6653 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6654 static_cast<int>(spent_in_mutator_));
6658 PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6660 if (!FLAG_trace_gc_nvp) {
6661 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6663 double end_memory_size_mb =
6664 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6666 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6668 static_cast<double>(start_object_size_) / MB,
6669 static_cast<double>(start_memory_size_) / MB,
6670 SizeOfHeapObjects(),
6671 end_memory_size_mb);
6673 if (external_time > 0) PrintF("%d / ", external_time);
6674 PrintF("%d ms", time);
6675 if (steps_count_ > 0) {
6676 if (collector_ == SCAVENGER) {
6677 PrintF(" (+ %d ms in %d steps since last GC)",
6678 static_cast<int>(steps_took_since_last_gc_),
6679 steps_count_since_last_gc_);
6681 PrintF(" (+ %d ms in %d steps since start of marking, "
6682 "biggest step %f ms)",
6683 static_cast<int>(steps_took_),
6689 if (gc_reason_ != NULL) {
6690 PrintF(" [%s]", gc_reason_);
6693 if (collector_reason_ != NULL) {
6694 PrintF(" [%s]", collector_reason_);
6699 PrintF("pause=%d ", time);
6700 PrintF("mutator=%d ",
6701 static_cast<int>(spent_in_mutator_));
6704 switch (collector_) {
6708 case MARK_COMPACTOR:
6716 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6717 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6718 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6719 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6720 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6721 PrintF("new_new=%d ",
6722 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6723 PrintF("root_new=%d ",
6724 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6725 PrintF("old_new=%d ",
6726 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6727 PrintF("compaction_ptrs=%d ",
6728 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6729 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6730 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6731 PrintF("misc_compaction=%d ",
6732 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
6734 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
6735 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6736 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6737 in_free_list_or_wasted_before_gc_);
6738 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6740 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6741 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6743 if (collector_ == SCAVENGER) {
6744 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6745 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6747 PrintF("stepscount=%d ", steps_count_);
6748 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6754 heap_->PrintShortHeapStatistics();
6758 const char* GCTracer::CollectorString() {
6759 switch (collector_) {
6762 case MARK_COMPACTOR:
6763 return "Mark-sweep";
6765 return "Unknown GC";
6769 int KeyedLookupCache::Hash(Map* map, String* name) {
6770 // Uses only lower 32 bits if pointers are larger.
6771 uintptr_t addr_hash =
6772 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6773 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6777 int KeyedLookupCache::Lookup(Map* map, String* name) {
6778 int index = (Hash(map, name) & kHashMask);
6779 for (int i = 0; i < kEntriesPerBucket; i++) {
6780 Key& key = keys_[index + i];
6781 if ((key.map == map) && key.name->Equals(name)) {
6782 return field_offsets_[index + i];
6789 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6791 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
6792 int index = (Hash(map, symbol) & kHashMask);
6793 // After a GC there will be free slots, so we use them in order (this may
6794 // help to get the most frequently used one in position 0).
6795 for (int i = 0; i< kEntriesPerBucket; i++) {
6796 Key& key = keys_[index];
6797 Object* free_entry_indicator = NULL;
6798 if (key.map == free_entry_indicator) {
6801 field_offsets_[index + i] = field_offset;
6805 // No free entry found in this bucket, so we move them all down one and
6806 // put the new entry at position zero.
6807 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6808 Key& key = keys_[index + i];
6809 Key& key2 = keys_[index + i - 1];
6811 field_offsets_[index + i] = field_offsets_[index + i - 1];
6814 // Write the new first entry.
6815 Key& key = keys_[index];
6818 field_offsets_[index] = field_offset;
6823 void KeyedLookupCache::Clear() {
6824 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6828 void DescriptorLookupCache::Clear() {
6829 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
6834 void Heap::GarbageCollectionGreedyCheck() {
6835 ASSERT(FLAG_gc_greedy);
6836 if (isolate_->bootstrapper()->IsActive()) return;
6837 if (disallow_allocation_failure()) return;
6838 CollectGarbage(NEW_SPACE);
6843 TranscendentalCache::SubCache::SubCache(Type t)
6845 isolate_(Isolate::Current()) {
6846 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
6847 uint32_t in1 = 0xffffffffu; // generated by the FPU.
6848 for (int i = 0; i < kCacheSize; i++) {
6849 elements_[i].in[0] = in0;
6850 elements_[i].in[1] = in1;
6851 elements_[i].output = NULL;
6856 void TranscendentalCache::Clear() {
6857 for (int i = 0; i < kNumberOfCaches; i++) {
6858 if (caches_[i] != NULL) {
6866 void ExternalStringTable::CleanUp() {
6868 for (int i = 0; i < new_space_strings_.length(); ++i) {
6869 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6872 if (heap_->InNewSpace(new_space_strings_[i])) {
6873 new_space_strings_[last++] = new_space_strings_[i];
6875 old_space_strings_.Add(new_space_strings_[i]);
6878 new_space_strings_.Rewind(last);
6880 for (int i = 0; i < old_space_strings_.length(); ++i) {
6881 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
6884 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
6885 old_space_strings_[last++] = old_space_strings_[i];
6887 old_space_strings_.Rewind(last);
6888 if (FLAG_verify_heap) {
6894 void ExternalStringTable::TearDown() {
6895 new_space_strings_.Free();
6896 old_space_strings_.Free();
6900 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6901 chunk->set_next_chunk(chunks_queued_for_free_);
6902 chunks_queued_for_free_ = chunk;
6906 void Heap::FreeQueuedChunks() {
6907 if (chunks_queued_for_free_ == NULL) return;
6910 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6911 next = chunk->next_chunk();
6912 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6914 if (chunk->owner()->identity() == LO_SPACE) {
6915 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6916 // If FromAnyPointerAddress encounters a slot that belongs to a large
6917 // chunk queued for deletion it will fail to find the chunk because
6918 // it try to perform a search in the list of pages owned by of the large
6919 // object space and queued chunks were detached from that list.
6920 // To work around this we split large chunk into normal kPageSize aligned
6921 // pieces and initialize size, owner and flags field of every piece.
6922 // If FromAnyPointerAddress encounters a slot that belongs to one of
6923 // these smaller pieces it will treat it as a slot on a normal Page.
6924 MemoryChunk* inner = MemoryChunk::FromAddress(
6925 chunk->address() + Page::kPageSize);
6926 MemoryChunk* inner_last = MemoryChunk::FromAddress(
6927 chunk->address() + chunk->size() - 1);
6928 while (inner <= inner_last) {
6929 // Size of a large chunk is always a multiple of
6930 // OS::AllocateAlignment() so there is always
6931 // enough space for a fake MemoryChunk header.
6932 inner->set_size(Page::kPageSize);
6933 inner->set_owner(lo_space());
6934 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6935 inner = MemoryChunk::FromAddress(
6936 inner->address() + Page::kPageSize);
6940 isolate_->heap()->store_buffer()->Compact();
6941 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6942 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6943 next = chunk->next_chunk();
6944 isolate_->memory_allocator()->Free(chunk);
6946 chunks_queued_for_free_ = NULL;
6949 } } // namespace v8::internal