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"
46 #include "runtime-profiler.h"
47 #include "scopeinfo.h"
49 #include "store-buffer.h"
50 #include "v8threads.h"
51 #include "vm-state-inl.h"
52 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
53 #include "regexp-macro-assembler.h"
54 #include "arm/regexp-macro-assembler-arm.h"
56 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
57 #include "regexp-macro-assembler.h"
58 #include "mips/regexp-macro-assembler-mips.h"
67 // semispace_size_ should be a power of 2 and old_generation_size_ should be
68 // a multiple of Page::kPageSize.
70 #define LUMP_OF_MEMORY (128 * KB)
72 #elif defined(V8_TARGET_ARCH_X64)
73 #define LUMP_OF_MEMORY (2 * MB)
74 code_range_size_(512*MB),
76 #define LUMP_OF_MEMORY MB
79 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
80 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
81 initial_semispace_size_(Page::kPageSize),
82 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
83 max_executable_size_(256l * LUMP_OF_MEMORY),
85 // Variables set based on semispace_size_ and old_generation_size_ in
86 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
87 // Will be 4 * reserved_semispace_size_ to ensure that young
88 // generation can be aligned to its size.
89 survived_since_last_expansion_(0),
91 always_allocate_scope_depth_(0),
92 linear_allocation_scope_depth_(0),
93 contexts_disposed_(0),
95 scan_on_scavenge_pages_(0),
97 old_pointer_space_(NULL),
98 old_data_space_(NULL),
103 gc_state_(NOT_IN_GC),
104 gc_post_processing_depth_(0),
107 remembered_unmapped_pages_index_(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 mark_sweeps_since_idle_round_started_(0),
148 ms_count_at_last_idle_notification_(0),
149 gc_count_at_last_idle_gc_(0),
150 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
151 promotion_queue_(this),
153 chunks_queued_for_free_(NULL) {
154 // Allow build-time customization of the max semispace size. Building
155 // V8 with snapshots and a non-default max semispace size is much
156 // easier if you can define it as part of the build environment.
157 #if defined(V8_MAX_SEMISPACE_SIZE)
158 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
161 intptr_t max_virtual = OS::MaxVirtualMemory();
163 if (max_virtual > 0) {
164 if (code_range_size_ > 0) {
165 // Reserve no more than 1/8 of the memory for the code range.
166 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
170 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
171 global_contexts_list_ = NULL;
172 mark_compact_collector_.heap_ = this;
173 external_string_table_.heap_ = this;
174 // Put a dummy entry in the remembered pages so we can find the list the
175 // minidump even if there are no real unmapped pages.
176 RememberUnmappedPage(NULL, false);
180 intptr_t Heap::Capacity() {
181 if (!HasBeenSetUp()) return 0;
183 return new_space_.Capacity() +
184 old_pointer_space_->Capacity() +
185 old_data_space_->Capacity() +
186 code_space_->Capacity() +
187 map_space_->Capacity() +
188 cell_space_->Capacity();
192 intptr_t Heap::CommittedMemory() {
193 if (!HasBeenSetUp()) return 0;
195 return new_space_.CommittedMemory() +
196 old_pointer_space_->CommittedMemory() +
197 old_data_space_->CommittedMemory() +
198 code_space_->CommittedMemory() +
199 map_space_->CommittedMemory() +
200 cell_space_->CommittedMemory() +
204 intptr_t Heap::CommittedMemoryExecutable() {
205 if (!HasBeenSetUp()) return 0;
207 return isolate()->memory_allocator()->SizeExecutable();
211 intptr_t Heap::Available() {
212 if (!HasBeenSetUp()) return 0;
214 return new_space_.Available() +
215 old_pointer_space_->Available() +
216 old_data_space_->Available() +
217 code_space_->Available() +
218 map_space_->Available() +
219 cell_space_->Available();
223 bool Heap::HasBeenSetUp() {
224 return old_pointer_space_ != NULL &&
225 old_data_space_ != NULL &&
226 code_space_ != NULL &&
227 map_space_ != NULL &&
228 cell_space_ != NULL &&
233 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
234 if (IntrusiveMarking::IsMarked(object)) {
235 return IntrusiveMarking::SizeOfMarkedObject(object);
237 return object->SizeFromMap(object->map());
241 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
242 const char** reason) {
243 // Is global GC requested?
244 if (space != NEW_SPACE) {
245 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
246 *reason = "GC in old space requested";
247 return MARK_COMPACTOR;
250 if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
251 *reason = "GC in old space forced by flags";
252 return MARK_COMPACTOR;
255 // Is enough data promoted to justify a global GC?
256 if (OldGenerationPromotionLimitReached()) {
257 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
258 *reason = "promotion limit reached";
259 return MARK_COMPACTOR;
262 // Have allocation in OLD and LO failed?
263 if (old_gen_exhausted_) {
264 isolate_->counters()->
265 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
266 *reason = "old generations exhausted";
267 return MARK_COMPACTOR;
270 // Is there enough space left in OLD to guarantee that a scavenge can
273 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
274 // for object promotion. It counts only the bytes that the memory
275 // allocator has not yet allocated from the OS and assigned to any space,
276 // and does not count available bytes already in the old space or code
277 // space. Undercounting is safe---we may get an unrequested full GC when
278 // a scavenge would have succeeded.
279 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
280 isolate_->counters()->
281 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
282 *reason = "scavenge might not succeed";
283 return MARK_COMPACTOR;
292 // TODO(1238405): Combine the infrastructure for --heap-stats and
293 // --log-gc to avoid the complicated preprocessor and flag testing.
294 void Heap::ReportStatisticsBeforeGC() {
295 // Heap::ReportHeapStatistics will also log NewSpace statistics when
296 // compiled --log-gc is set. The following logic is used to avoid
299 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
300 if (FLAG_heap_stats) {
301 ReportHeapStatistics("Before GC");
302 } else if (FLAG_log_gc) {
303 new_space_.ReportStatistics();
305 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
308 new_space_.CollectStatistics();
309 new_space_.ReportStatistics();
310 new_space_.ClearHistograms();
316 void Heap::PrintShortHeapStatistics() {
317 if (!FLAG_trace_gc_verbose) return;
318 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
319 ", available: %8" V8_PTR_PREFIX "d\n",
320 isolate_->memory_allocator()->Size(),
321 isolate_->memory_allocator()->Available());
322 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
323 ", available: %8" V8_PTR_PREFIX "d\n",
324 Heap::new_space_.Size(),
325 new_space_.Available());
326 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
327 ", available: %8" V8_PTR_PREFIX "d"
328 ", waste: %8" V8_PTR_PREFIX "d\n",
329 old_pointer_space_->Size(),
330 old_pointer_space_->Available(),
331 old_pointer_space_->Waste());
332 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
333 ", available: %8" V8_PTR_PREFIX "d"
334 ", waste: %8" V8_PTR_PREFIX "d\n",
335 old_data_space_->Size(),
336 old_data_space_->Available(),
337 old_data_space_->Waste());
338 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
339 ", available: %8" V8_PTR_PREFIX "d"
340 ", waste: %8" V8_PTR_PREFIX "d\n",
342 code_space_->Available(),
343 code_space_->Waste());
344 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
345 ", available: %8" V8_PTR_PREFIX "d"
346 ", waste: %8" V8_PTR_PREFIX "d\n",
348 map_space_->Available(),
349 map_space_->Waste());
350 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
351 ", available: %8" V8_PTR_PREFIX "d"
352 ", waste: %8" V8_PTR_PREFIX "d\n",
354 cell_space_->Available(),
355 cell_space_->Waste());
356 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
357 ", available: %8" V8_PTR_PREFIX "d\n",
359 lo_space_->Available());
363 // TODO(1238405): Combine the infrastructure for --heap-stats and
364 // --log-gc to avoid the complicated preprocessor and flag testing.
365 void Heap::ReportStatisticsAfterGC() {
366 // Similar to the before GC, we use some complicated logic to ensure that
367 // NewSpace statistics are logged exactly once when --log-gc is turned on.
369 if (FLAG_heap_stats) {
370 new_space_.CollectStatistics();
371 ReportHeapStatistics("After GC");
372 } else if (FLAG_log_gc) {
373 new_space_.ReportStatistics();
376 if (FLAG_log_gc) new_space_.ReportStatistics();
381 void Heap::GarbageCollectionPrologue() {
382 isolate_->transcendental_cache()->Clear();
383 ClearJSFunctionResultCaches();
385 unflattened_strings_length_ = 0;
387 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
388 allow_allocation(false);
390 if (FLAG_verify_heap) {
394 if (FLAG_gc_verbose) Print();
398 ReportStatisticsBeforeGC();
401 LiveObjectList::GCPrologue();
402 store_buffer()->GCPrologue();
405 intptr_t Heap::SizeOfObjects() {
408 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
409 total += space->SizeOfObjects();
414 void Heap::GarbageCollectionEpilogue() {
415 store_buffer()->GCEpilogue();
416 LiveObjectList::GCEpilogue();
418 allow_allocation(true);
421 if (FLAG_verify_heap) {
425 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
426 if (FLAG_print_handles) PrintHandles();
427 if (FLAG_gc_verbose) Print();
428 if (FLAG_code_stats) ReportCodeStatistics("After GC");
431 isolate_->counters()->alive_after_last_gc()->Set(
432 static_cast<int>(SizeOfObjects()));
434 isolate_->counters()->symbol_table_capacity()->Set(
435 symbol_table()->Capacity());
436 isolate_->counters()->number_of_symbols()->Set(
437 symbol_table()->NumberOfElements());
439 ReportStatisticsAfterGC();
441 #ifdef ENABLE_DEBUGGER_SUPPORT
442 isolate_->debug()->AfterGarbageCollection();
443 #endif // ENABLE_DEBUGGER_SUPPORT
447 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
448 // Since we are ignoring the return value, the exact choice of space does
449 // not matter, so long as we do not specify NEW_SPACE, which would not
451 mark_compact_collector_.SetFlags(flags);
452 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
453 mark_compact_collector_.SetFlags(kNoGCFlags);
457 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
458 // Since we are ignoring the return value, the exact choice of space does
459 // not matter, so long as we do not specify NEW_SPACE, which would not
461 // Major GC would invoke weak handle callbacks on weakly reachable
462 // handles, but won't collect weakly reachable objects until next
463 // major GC. Therefore if we collect aggressively and weak handle callback
464 // has been invoked, we rerun major GC to release objects which become
466 // Note: as weak callbacks can execute arbitrary code, we cannot
467 // hope that eventually there will be no weak callbacks invocations.
468 // Therefore stop recollecting after several attempts.
469 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
470 kReduceMemoryFootprintMask);
471 isolate_->compilation_cache()->Clear();
472 const int kMaxNumberOfAttempts = 7;
473 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
474 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
478 mark_compact_collector()->SetFlags(kNoGCFlags);
482 incremental_marking()->UncommitMarkingDeque();
486 bool Heap::CollectGarbage(AllocationSpace space,
487 GarbageCollector collector,
488 const char* gc_reason,
489 const char* collector_reason) {
490 // The VM is in the GC state until exiting this function.
491 VMState state(isolate_, GC);
494 // Reset the allocation timeout to the GC interval, but make sure to
495 // allow at least a few allocations after a collection. The reason
496 // for this is that we have a lot of allocation sequences and we
497 // assume that a garbage collection will allow the subsequent
498 // allocation attempts to go through.
499 allocation_timeout_ = Max(6, FLAG_gc_interval);
502 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
503 if (FLAG_trace_incremental_marking) {
504 PrintF("[IncrementalMarking] Scavenge during marking.\n");
508 if (collector == MARK_COMPACTOR &&
509 !mark_compact_collector()->abort_incremental_marking_ &&
510 !incremental_marking()->IsStopped() &&
511 !incremental_marking()->should_hurry() &&
512 FLAG_incremental_marking_steps) {
513 // Make progress in incremental marking.
514 const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
515 incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
516 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
517 if (!incremental_marking()->IsComplete()) {
518 if (FLAG_trace_incremental_marking) {
519 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
521 collector = SCAVENGER;
522 collector_reason = "incremental marking delaying mark-sweep";
526 bool next_gc_likely_to_collect_more = false;
528 { GCTracer tracer(this, gc_reason, collector_reason);
529 GarbageCollectionPrologue();
530 // The GC count was incremented in the prologue. Tell the tracer about
532 tracer.set_gc_count(gc_count_);
534 // Tell the tracer which collector we've selected.
535 tracer.set_collector(collector);
537 HistogramTimer* rate = (collector == SCAVENGER)
538 ? isolate_->counters()->gc_scavenger()
539 : isolate_->counters()->gc_compactor();
541 next_gc_likely_to_collect_more =
542 PerformGarbageCollection(collector, &tracer);
545 GarbageCollectionEpilogue();
548 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
549 if (incremental_marking()->IsStopped()) {
550 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
551 incremental_marking()->Start();
555 return next_gc_likely_to_collect_more;
559 void Heap::PerformScavenge() {
560 GCTracer tracer(this, NULL, NULL);
561 if (incremental_marking()->IsStopped()) {
562 PerformGarbageCollection(SCAVENGER, &tracer);
564 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
570 // Helper class for verifying the symbol table.
571 class SymbolTableVerifier : public ObjectVisitor {
573 void VisitPointers(Object** start, Object** end) {
574 // Visit all HeapObject pointers in [start, end).
575 for (Object** p = start; p < end; p++) {
576 if ((*p)->IsHeapObject()) {
577 // Check that the symbol is actually a symbol.
578 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
586 static void VerifySymbolTable() {
588 SymbolTableVerifier verifier;
589 HEAP->symbol_table()->IterateElements(&verifier);
594 static bool AbortIncrementalMarkingAndCollectGarbage(
596 AllocationSpace space,
597 const char* gc_reason = NULL) {
598 heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
599 bool result = heap->CollectGarbage(space, gc_reason);
600 heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
605 void Heap::ReserveSpace(
607 int pointer_space_size,
612 int large_object_size) {
613 NewSpace* new_space = Heap::new_space();
614 PagedSpace* old_pointer_space = Heap::old_pointer_space();
615 PagedSpace* old_data_space = Heap::old_data_space();
616 PagedSpace* code_space = Heap::code_space();
617 PagedSpace* map_space = Heap::map_space();
618 PagedSpace* cell_space = Heap::cell_space();
619 LargeObjectSpace* lo_space = Heap::lo_space();
620 bool gc_performed = true;
622 static const int kThreshold = 20;
623 while (gc_performed && counter++ < kThreshold) {
624 gc_performed = false;
625 if (!new_space->ReserveSpace(new_space_size)) {
626 Heap::CollectGarbage(NEW_SPACE,
627 "failed to reserve space in the new space");
630 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
631 AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
632 "failed to reserve space in the old pointer space");
635 if (!(old_data_space->ReserveSpace(data_space_size))) {
636 AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
637 "failed to reserve space in the old data space");
640 if (!(code_space->ReserveSpace(code_space_size))) {
641 AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
642 "failed to reserve space in the code space");
645 if (!(map_space->ReserveSpace(map_space_size))) {
646 AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
647 "failed to reserve space in the map space");
650 if (!(cell_space->ReserveSpace(cell_space_size))) {
651 AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
652 "failed to reserve space in the cell space");
655 // We add a slack-factor of 2 in order to have space for a series of
656 // large-object allocations that are only just larger than the page size.
657 large_object_size *= 2;
658 // The ReserveSpace method on the large object space checks how much
659 // we can expand the old generation. This includes expansion caused by
660 // allocation in the other spaces.
661 large_object_size += cell_space_size + map_space_size + code_space_size +
662 data_space_size + pointer_space_size;
663 if (!(lo_space->ReserveSpace(large_object_size))) {
664 AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
665 "failed to reserve space in the large object space");
671 // Failed to reserve the space after several attempts.
672 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
677 void Heap::EnsureFromSpaceIsCommitted() {
678 if (new_space_.CommitFromSpaceIfNeeded()) return;
680 // Committing memory to from space failed.
681 // Try shrinking and try again.
683 if (new_space_.CommitFromSpaceIfNeeded()) return;
685 // Committing memory to from space failed again.
686 // Memory is exhausted and we will die.
687 V8::FatalProcessOutOfMemory("Committing semi space failed.");
691 void Heap::ClearJSFunctionResultCaches() {
692 if (isolate_->bootstrapper()->IsActive()) return;
694 Object* context = global_contexts_list_;
695 while (!context->IsUndefined()) {
696 // Get the caches for this context. GC can happen when the context
697 // is not fully initialized, so the caches can be undefined.
698 Object* caches_or_undefined =
699 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
700 if (!caches_or_undefined->IsUndefined()) {
701 FixedArray* caches = FixedArray::cast(caches_or_undefined);
703 int length = caches->length();
704 for (int i = 0; i < length; i++) {
705 JSFunctionResultCache::cast(caches->get(i))->Clear();
708 // Get the next context:
709 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
715 void Heap::ClearNormalizedMapCaches() {
716 if (isolate_->bootstrapper()->IsActive() &&
717 !incremental_marking()->IsMarking()) {
721 Object* context = global_contexts_list_;
722 while (!context->IsUndefined()) {
723 // GC can happen when the context is not fully initialized,
724 // so the cache can be undefined.
726 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
727 if (!cache->IsUndefined()) {
728 NormalizedMapCache::cast(cache)->Clear();
730 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
735 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
736 double survival_rate =
737 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
738 start_new_space_size;
740 if (survival_rate > kYoungSurvivalRateHighThreshold) {
741 high_survival_rate_period_length_++;
743 high_survival_rate_period_length_ = 0;
746 if (survival_rate < kYoungSurvivalRateLowThreshold) {
747 low_survival_rate_period_length_++;
749 low_survival_rate_period_length_ = 0;
752 double survival_rate_diff = survival_rate_ - survival_rate;
754 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
755 set_survival_rate_trend(DECREASING);
756 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
757 set_survival_rate_trend(INCREASING);
759 set_survival_rate_trend(STABLE);
762 survival_rate_ = survival_rate;
765 bool Heap::PerformGarbageCollection(GarbageCollector collector,
767 bool next_gc_likely_to_collect_more = false;
769 if (collector != SCAVENGER) {
770 PROFILE(isolate_, CodeMovingGCEvent());
773 if (FLAG_verify_heap) {
776 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
777 ASSERT(!allocation_allowed_);
778 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
779 global_gc_prologue_callback_();
783 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
785 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
786 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
787 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
791 EnsureFromSpaceIsCommitted();
793 int start_new_space_size = Heap::new_space()->SizeAsInt();
795 if (IsHighSurvivalRate()) {
796 // We speed up the incremental marker if it is running so that it
797 // does not fall behind the rate of promotion, which would cause a
798 // constantly growing old space.
799 incremental_marking()->NotifyOfHighPromotionRate();
802 if (collector == MARK_COMPACTOR) {
803 // Perform mark-sweep with optional compaction.
806 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
807 IsStableOrIncreasingSurvivalTrend();
809 UpdateSurvivalRateTrend(start_new_space_size);
811 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
813 if (high_survival_rate_during_scavenges &&
814 IsStableOrIncreasingSurvivalTrend()) {
815 // Stable high survival rates of young objects both during partial and
816 // full collection indicate that mutator is either building or modifying
817 // a structure with a long lifetime.
818 // In this case we aggressively raise old generation memory limits to
819 // postpone subsequent mark-sweep collection and thus trade memory
820 // space for the mutation speed.
821 old_gen_limit_factor_ = 2;
823 old_gen_limit_factor_ = 1;
826 old_gen_promotion_limit_ =
827 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
828 old_gen_allocation_limit_ =
829 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
831 old_gen_exhausted_ = false;
837 UpdateSurvivalRateTrend(start_new_space_size);
840 if (!new_space_high_promotion_mode_active_ &&
841 new_space_.Capacity() == new_space_.MaximumCapacity() &&
842 IsStableOrIncreasingSurvivalTrend() &&
843 IsHighSurvivalRate()) {
844 // Stable high survival rates even though young generation is at
845 // maximum capacity indicates that most objects will be promoted.
846 // To decrease scavenger pauses and final mark-sweep pauses, we
847 // have to limit maximal capacity of the young generation.
848 new_space_high_promotion_mode_active_ = true;
850 PrintF("Limited new space size due to high promotion rate: %d MB\n",
851 new_space_.InitialCapacity() / MB);
853 } else if (new_space_high_promotion_mode_active_ &&
854 IsStableOrDecreasingSurvivalTrend() &&
855 IsLowSurvivalRate()) {
856 // Decreasing low survival rates might indicate that the above high
857 // promotion mode is over and we should allow the young generation
859 new_space_high_promotion_mode_active_ = false;
861 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
862 new_space_.MaximumCapacity() / MB);
866 if (new_space_high_promotion_mode_active_ &&
867 new_space_.Capacity() > new_space_.InitialCapacity()) {
871 isolate_->counters()->objs_since_last_young()->Set(0);
873 gc_post_processing_depth_++;
874 { DisableAssertNoAllocation allow_allocation;
875 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
876 next_gc_likely_to_collect_more =
877 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
879 gc_post_processing_depth_--;
881 // Update relocatables.
882 Relocatable::PostGarbageCollectionProcessing();
884 if (collector == MARK_COMPACTOR) {
885 // Register the amount of external allocated memory.
886 amount_of_external_allocated_memory_at_last_global_gc_ =
887 amount_of_external_allocated_memory_;
890 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
891 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
892 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
893 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
897 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
898 ASSERT(!allocation_allowed_);
899 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
900 global_gc_epilogue_callback_();
902 if (FLAG_verify_heap) {
906 return next_gc_likely_to_collect_more;
910 void Heap::MarkCompact(GCTracer* tracer) {
911 gc_state_ = MARK_COMPACT;
912 LOG(isolate_, ResourceEvent("markcompact", "begin"));
914 mark_compact_collector_.Prepare(tracer);
917 tracer->set_full_gc_count(ms_count_);
919 MarkCompactPrologue();
921 mark_compact_collector_.CollectGarbage();
923 LOG(isolate_, ResourceEvent("markcompact", "end"));
925 gc_state_ = NOT_IN_GC;
927 isolate_->counters()->objs_since_last_full()->Set(0);
929 contexts_disposed_ = 0;
931 isolate_->set_context_exit_happened(false);
935 void Heap::MarkCompactPrologue() {
936 // At any old GC clear the keyed lookup cache to enable collection of unused
938 isolate_->keyed_lookup_cache()->Clear();
939 isolate_->context_slot_cache()->Clear();
940 isolate_->descriptor_lookup_cache()->Clear();
941 StringSplitCache::Clear(string_split_cache());
943 isolate_->compilation_cache()->MarkCompactPrologue();
945 CompletelyClearInstanceofCache();
947 FlushNumberStringCache();
948 if (FLAG_cleanup_code_caches_at_gc) {
949 polymorphic_code_cache()->set_cache(undefined_value());
952 ClearNormalizedMapCaches();
956 Object* Heap::FindCodeObject(Address a) {
957 return isolate()->inner_pointer_to_code_cache()->
958 GcSafeFindCodeForInnerPointer(a);
962 // Helper class for copying HeapObjects
963 class ScavengeVisitor: public ObjectVisitor {
965 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
967 void VisitPointer(Object** p) { ScavengePointer(p); }
969 void VisitPointers(Object** start, Object** end) {
970 // Copy all HeapObject pointers in [start, end)
971 for (Object** p = start; p < end; p++) ScavengePointer(p);
975 void ScavengePointer(Object** p) {
977 if (!heap_->InNewSpace(object)) return;
978 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
979 reinterpret_cast<HeapObject*>(object));
987 // Visitor class to verify pointers in code or data space do not point into
989 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
991 void VisitPointers(Object** start, Object**end) {
992 for (Object** current = start; current < end; current++) {
993 if ((*current)->IsHeapObject()) {
994 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
1001 static void VerifyNonPointerSpacePointers() {
1002 // Verify that there are no pointers to new space in spaces where we
1003 // do not expect them.
1004 VerifyNonPointerSpacePointersVisitor v;
1005 HeapObjectIterator code_it(HEAP->code_space());
1006 for (HeapObject* object = code_it.Next();
1007 object != NULL; object = code_it.Next())
1008 object->Iterate(&v);
1010 // The old data space was normally swept conservatively so that the iterator
1011 // doesn't work, so we normally skip the next bit.
1012 if (!HEAP->old_data_space()->was_swept_conservatively()) {
1013 HeapObjectIterator data_it(HEAP->old_data_space());
1014 for (HeapObject* object = data_it.Next();
1015 object != NULL; object = data_it.Next())
1016 object->Iterate(&v);
1022 void Heap::CheckNewSpaceExpansionCriteria() {
1023 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1024 survived_since_last_expansion_ > new_space_.Capacity() &&
1025 !new_space_high_promotion_mode_active_) {
1026 // Grow the size of new space if there is room to grow, enough data
1027 // has survived scavenge since the last expansion and we are not in
1028 // high promotion mode.
1030 survived_since_last_expansion_ = 0;
1035 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1036 return heap->InNewSpace(*p) &&
1037 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1041 void Heap::ScavengeStoreBufferCallback(
1044 StoreBufferEvent event) {
1045 heap->store_buffer_rebuilder_.Callback(page, event);
1049 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1050 if (event == kStoreBufferStartScanningPagesEvent) {
1051 start_of_current_page_ = NULL;
1052 current_page_ = NULL;
1053 } else if (event == kStoreBufferScanningPageEvent) {
1054 if (current_page_ != NULL) {
1055 // If this page already overflowed the store buffer during this iteration.
1056 if (current_page_->scan_on_scavenge()) {
1057 // Then we should wipe out the entries that have been added for it.
1058 store_buffer_->SetTop(start_of_current_page_);
1059 } else if (store_buffer_->Top() - start_of_current_page_ >=
1060 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1061 // Did we find too many pointers in the previous page? The heuristic is
1062 // that no page can take more then 1/5 the remaining slots in the store
1064 current_page_->set_scan_on_scavenge(true);
1065 store_buffer_->SetTop(start_of_current_page_);
1067 // In this case the page we scanned took a reasonable number of slots in
1068 // the store buffer. It has now been rehabilitated and is no longer
1069 // marked scan_on_scavenge.
1070 ASSERT(!current_page_->scan_on_scavenge());
1073 start_of_current_page_ = store_buffer_->Top();
1074 current_page_ = page;
1075 } else if (event == kStoreBufferFullEvent) {
1076 // The current page overflowed the store buffer again. Wipe out its entries
1077 // in the store buffer and mark it scan-on-scavenge again. This may happen
1078 // several times while scanning.
1079 if (current_page_ == NULL) {
1080 // Store Buffer overflowed while scanning promoted objects. These are not
1081 // in any particular page, though they are likely to be clustered by the
1082 // allocation routines.
1083 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1085 // Store Buffer overflowed while scanning a particular old space page for
1086 // pointers to new space.
1087 ASSERT(current_page_ == page);
1088 ASSERT(page != NULL);
1089 current_page_->set_scan_on_scavenge(true);
1090 ASSERT(start_of_current_page_ != store_buffer_->Top());
1091 store_buffer_->SetTop(start_of_current_page_);
1099 void PromotionQueue::Initialize() {
1100 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1101 // entries (where each is a pair of intptr_t). This allows us to simplify
1102 // the test fpr when to switch pages.
1103 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1105 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1107 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1108 emergency_stack_ = NULL;
1113 void PromotionQueue::RelocateQueueHead() {
1114 ASSERT(emergency_stack_ == NULL);
1116 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1117 intptr_t* head_start = rear_;
1118 intptr_t* head_end =
1119 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1122 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1124 emergency_stack_ = new List<Entry>(2 * entries_count);
1126 while (head_start != head_end) {
1127 int size = static_cast<int>(*(head_start++));
1128 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1129 emergency_stack_->Add(Entry(obj, size));
1135 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1137 explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
1139 virtual Object* RetainAs(Object* object) {
1140 if (!heap_->InFromSpace(object)) {
1144 MapWord map_word = HeapObject::cast(object)->map_word();
1145 if (map_word.IsForwardingAddress()) {
1146 return map_word.ToForwardingAddress();
1156 void Heap::Scavenge() {
1158 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1161 gc_state_ = SCAVENGE;
1163 // Implements Cheney's copying algorithm
1164 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1166 // Clear descriptor cache.
1167 isolate_->descriptor_lookup_cache()->Clear();
1169 // Used for updating survived_since_last_expansion_ at function end.
1170 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1172 CheckNewSpaceExpansionCriteria();
1174 SelectScavengingVisitorsTable();
1176 incremental_marking()->PrepareForScavenge();
1178 AdvanceSweepers(static_cast<int>(new_space_.Size()));
1180 // Flip the semispaces. After flipping, to space is empty, from space has
1183 new_space_.ResetAllocationInfo();
1185 // We need to sweep newly copied objects which can be either in the
1186 // to space or promoted to the old generation. For to-space
1187 // objects, we treat the bottom of the to space as a queue. Newly
1188 // copied and unswept objects lie between a 'front' mark and the
1189 // allocation pointer.
1191 // Promoted objects can go into various old-generation spaces, and
1192 // can be allocated internally in the spaces (from the free list).
1193 // We treat the top of the to space as a queue of addresses of
1194 // promoted objects. The addresses of newly promoted and unswept
1195 // objects lie between a 'front' mark and a 'rear' mark that is
1196 // updated as a side effect of promoting an object.
1198 // There is guaranteed to be enough room at the top of the to space
1199 // for the addresses of promoted objects: every object promoted
1200 // frees up its size in bytes from the top of the new space, and
1201 // objects are at least one pointer in size.
1202 Address new_space_front = new_space_.ToSpaceStart();
1203 promotion_queue_.Initialize();
1206 store_buffer()->Clean();
1209 ScavengeVisitor scavenge_visitor(this);
1211 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1213 // Copy objects reachable from the old generation.
1215 StoreBufferRebuildScope scope(this,
1217 &ScavengeStoreBufferCallback);
1218 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1221 // Copy objects reachable from cells by scavenging cell values directly.
1222 HeapObjectIterator cell_iterator(cell_space_);
1223 for (HeapObject* cell = cell_iterator.Next();
1224 cell != NULL; cell = cell_iterator.Next()) {
1225 if (cell->IsJSGlobalPropertyCell()) {
1226 Address value_address =
1227 reinterpret_cast<Address>(cell) +
1228 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1229 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1233 // Scavenge object reachable from the global contexts list directly.
1234 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1236 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1237 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1238 &IsUnscavengedHeapObject);
1239 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1241 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1243 UpdateNewSpaceReferencesInExternalStringTable(
1244 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1246 promotion_queue_.Destroy();
1248 LiveObjectList::UpdateReferencesForScavengeGC();
1249 if (!FLAG_watch_ic_patching) {
1250 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1252 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1254 ScavengeWeakObjectRetainer weak_object_retainer(this);
1255 ProcessWeakReferences(&weak_object_retainer);
1257 ASSERT(new_space_front == new_space_.top());
1260 new_space_.set_age_mark(new_space_.top());
1262 new_space_.LowerInlineAllocationLimit(
1263 new_space_.inline_allocation_limit_step());
1265 // Update how much has survived scavenge.
1266 IncrementYoungSurvivorsCounter(static_cast<int>(
1267 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1269 LOG(isolate_, ResourceEvent("scavenge", "end"));
1271 gc_state_ = NOT_IN_GC;
1273 scavenges_since_last_idle_round_++;
1277 HeapObject* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1279 MapWord first_word = HeapObject::cast(*p)->map_word();
1281 if (!first_word.IsForwardingAddress()) {
1282 // Unreachable external string can be finalized.
1283 heap->FinalizeExternalString(HeapObject::cast(*p));
1287 // String is still reachable.
1288 return HeapObject::cast(first_word.ToForwardingAddress());
1292 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1293 ExternalStringTableUpdaterCallback updater_func) {
1294 if (FLAG_verify_heap) {
1295 external_string_table_.Verify();
1298 if (external_string_table_.new_space_strings_.is_empty()) return;
1300 Object** start = &external_string_table_.new_space_strings_[0];
1301 Object** end = start + external_string_table_.new_space_strings_.length();
1302 Object** last = start;
1304 for (Object** p = start; p < end; ++p) {
1305 ASSERT(InFromSpace(*p));
1306 HeapObject* target = updater_func(this, p);
1308 if (target == NULL) continue;
1310 ASSERT(target->IsExternalString() || target->map()->has_external_resource());
1312 if (InNewSpace(target)) {
1313 // String is still in new space. Update the table entry.
1317 // String got promoted. Move it to the old string list.
1318 external_string_table_.AddOldObject(target);
1322 ASSERT(last <= end);
1323 external_string_table_.ShrinkNewObjects(static_cast<int>(last - start));
1327 void Heap::UpdateReferencesInExternalStringTable(
1328 ExternalStringTableUpdaterCallback updater_func) {
1330 // Update old space string references.
1331 if (external_string_table_.old_space_strings_.length() > 0) {
1332 Object** start = &external_string_table_.old_space_strings_[0];
1333 Object** end = start + external_string_table_.old_space_strings_.length();
1334 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1337 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1341 static Object* ProcessFunctionWeakReferences(Heap* heap,
1343 WeakObjectRetainer* retainer,
1344 bool record_slots) {
1345 Object* undefined = heap->undefined_value();
1346 Object* head = undefined;
1347 JSFunction* tail = NULL;
1348 Object* candidate = function;
1349 while (candidate != undefined) {
1350 // Check whether to keep the candidate in the list.
1351 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1352 Object* retain = retainer->RetainAs(candidate);
1353 if (retain != NULL) {
1354 if (head == undefined) {
1355 // First element in the list.
1358 // Subsequent elements in the list.
1359 ASSERT(tail != NULL);
1360 tail->set_next_function_link(retain);
1362 Object** next_function =
1363 HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
1364 heap->mark_compact_collector()->RecordSlot(
1365 next_function, next_function, retain);
1368 // Retained function is new tail.
1369 candidate_function = reinterpret_cast<JSFunction*>(retain);
1370 tail = candidate_function;
1372 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1374 if (retain == undefined) break;
1377 // Move to next element in the list.
1378 candidate = candidate_function->next_function_link();
1381 // Terminate the list if there is one or more elements.
1383 tail->set_next_function_link(undefined);
1390 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1391 Object* undefined = undefined_value();
1392 Object* head = undefined;
1393 Context* tail = NULL;
1394 Object* candidate = global_contexts_list_;
1396 // We don't record weak slots during marking or scavenges.
1397 // Instead we do it once when we complete mark-compact cycle.
1398 // Note that write barrier has no effect if we are already in the middle of
1399 // compacting mark-sweep cycle and we have to record slots manually.
1401 gc_state() == MARK_COMPACT &&
1402 mark_compact_collector()->is_compacting();
1404 while (candidate != undefined) {
1405 // Check whether to keep the candidate in the list.
1406 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1407 Object* retain = retainer->RetainAs(candidate);
1408 if (retain != NULL) {
1409 if (head == undefined) {
1410 // First element in the list.
1413 // Subsequent elements in the list.
1414 ASSERT(tail != NULL);
1415 tail->set_unchecked(this,
1416 Context::NEXT_CONTEXT_LINK,
1418 UPDATE_WRITE_BARRIER);
1421 Object** next_context =
1422 HeapObject::RawField(
1423 tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
1424 mark_compact_collector()->RecordSlot(
1425 next_context, next_context, retain);
1428 // Retained context is new tail.
1429 candidate_context = reinterpret_cast<Context*>(retain);
1430 tail = candidate_context;
1432 if (retain == undefined) break;
1434 // Process the weak list of optimized functions for the context.
1435 Object* function_list_head =
1436 ProcessFunctionWeakReferences(
1438 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1441 candidate_context->set_unchecked(this,
1442 Context::OPTIMIZED_FUNCTIONS_LIST,
1444 UPDATE_WRITE_BARRIER);
1446 Object** optimized_functions =
1447 HeapObject::RawField(
1448 tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
1449 mark_compact_collector()->RecordSlot(
1450 optimized_functions, optimized_functions, function_list_head);
1454 // Move to next element in the list.
1455 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1458 // Terminate the list if there is one or more elements.
1460 tail->set_unchecked(this,
1461 Context::NEXT_CONTEXT_LINK,
1462 Heap::undefined_value(),
1463 UPDATE_WRITE_BARRIER);
1466 // Update the head of the list of contexts.
1467 global_contexts_list_ = head;
1471 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1472 AssertNoAllocation no_allocation;
1474 class VisitorAdapter : public ObjectVisitor {
1476 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1477 : visitor_(visitor) {}
1478 virtual void VisitPointers(Object** start, Object** end) {
1479 for (Object** p = start; p < end; p++) {
1480 if ((*p)->IsExternalString()) {
1481 visitor_->VisitExternalString(Utils::ToLocal(
1482 Handle<String>(String::cast(*p))));
1487 v8::ExternalResourceVisitor* visitor_;
1488 } visitor_adapter(visitor);
1489 external_string_table_.Iterate(&visitor_adapter);
1493 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1495 static inline void VisitPointer(Heap* heap, Object** p) {
1496 Object* object = *p;
1497 if (!heap->InNewSpace(object)) return;
1498 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1499 reinterpret_cast<HeapObject*>(object));
1504 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1505 Address new_space_front) {
1507 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1508 // The addresses new_space_front and new_space_.top() define a
1509 // queue of unprocessed copied objects. Process them until the
1511 while (new_space_front != new_space_.top()) {
1512 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1513 HeapObject* object = HeapObject::FromAddress(new_space_front);
1515 NewSpaceScavenger::IterateBody(object->map(), object);
1518 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1522 // Promote and process all the to-be-promoted objects.
1524 StoreBufferRebuildScope scope(this,
1526 &ScavengeStoreBufferCallback);
1527 while (!promotion_queue()->is_empty()) {
1530 promotion_queue()->remove(&target, &size);
1532 // Promoted object might be already partially visited
1533 // during old space pointer iteration. Thus we search specificly
1534 // for pointers to from semispace instead of looking for pointers
1536 ASSERT(!target->IsMap());
1537 IterateAndMarkPointersToFromSpace(target->address(),
1538 target->address() + size,
1543 // Take another spin if there are now unswept objects in new space
1544 // (there are currently no more unswept promoted objects).
1545 } while (new_space_front != new_space_.top());
1547 return new_space_front;
1551 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
1554 INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
1558 static HeapObject* EnsureDoubleAligned(Heap* heap,
1561 if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
1562 heap->CreateFillerObjectAt(object->address(), kPointerSize);
1563 return HeapObject::FromAddress(object->address() + kPointerSize);
1565 heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
1572 enum LoggingAndProfiling {
1573 LOGGING_AND_PROFILING_ENABLED,
1574 LOGGING_AND_PROFILING_DISABLED
1578 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1581 template<MarksHandling marks_handling,
1582 LoggingAndProfiling logging_and_profiling_mode>
1583 class ScavengingVisitor : public StaticVisitorBase {
1585 static void Initialize() {
1586 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1587 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1588 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1589 table_.Register(kVisitByteArray, &EvacuateByteArray);
1590 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1591 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1593 table_.Register(kVisitGlobalContext,
1594 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1595 template VisitSpecialized<Context::kSize>);
1597 table_.Register(kVisitConsString,
1598 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1599 template VisitSpecialized<ConsString::kSize>);
1601 table_.Register(kVisitSlicedString,
1602 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1603 template VisitSpecialized<SlicedString::kSize>);
1605 table_.Register(kVisitSharedFunctionInfo,
1606 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1607 template VisitSpecialized<SharedFunctionInfo::kSize>);
1609 table_.Register(kVisitJSWeakMap,
1610 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1613 table_.Register(kVisitJSRegExp,
1614 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1617 if (marks_handling == IGNORE_MARKS) {
1618 table_.Register(kVisitJSFunction,
1619 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1620 template VisitSpecialized<JSFunction::kSize>);
1622 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1625 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1627 kVisitDataObjectGeneric>();
1629 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1631 kVisitJSObjectGeneric>();
1633 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1635 kVisitStructGeneric>();
1638 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1643 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1644 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1646 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1647 bool should_record = false;
1649 should_record = FLAG_heap_stats;
1651 should_record = should_record || FLAG_log_gc;
1652 if (should_record) {
1653 if (heap->new_space()->Contains(obj)) {
1654 heap->new_space()->RecordAllocation(obj);
1656 heap->new_space()->RecordPromotion(obj);
1661 // Helper function used by CopyObject to copy a source object to an
1662 // allocated target object and update the forwarding pointer in the source
1663 // object. Returns the target object.
1664 INLINE(static void MigrateObject(Heap* heap,
1668 // Copy the content of source to target.
1669 heap->CopyBlock(target->address(), source->address(), size);
1671 // Set the forwarding address.
1672 source->set_map_word(MapWord::FromForwardingAddress(target));
1674 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1675 // Update NewSpace stats if necessary.
1676 RecordCopiedObject(heap, target);
1677 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1678 Isolate* isolate = heap->isolate();
1679 if (isolate->logger()->is_logging() ||
1680 CpuProfiler::is_profiling(isolate)) {
1681 if (target->IsSharedFunctionInfo()) {
1682 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1683 source->address(), target->address()));
1688 if (marks_handling == TRANSFER_MARKS) {
1689 if (Marking::TransferColor(source, target)) {
1690 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1696 template<ObjectContents object_contents,
1697 SizeRestriction size_restriction,
1699 static inline void EvacuateObject(Map* map,
1703 SLOW_ASSERT((size_restriction != SMALL) ||
1704 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1705 SLOW_ASSERT(object->Size() == object_size);
1707 int allocation_size = object_size;
1708 if (alignment != kObjectAlignment) {
1709 ASSERT(alignment == kDoubleAlignment);
1710 allocation_size += kPointerSize;
1713 Heap* heap = map->GetHeap();
1714 if (heap->ShouldBePromoted(object->address(), object_size)) {
1715 MaybeObject* maybe_result;
1717 if ((size_restriction != SMALL) &&
1718 (allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
1719 maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
1722 if (object_contents == DATA_OBJECT) {
1723 maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
1726 heap->old_pointer_space()->AllocateRaw(allocation_size);
1730 Object* result = NULL; // Initialization to please compiler.
1731 if (maybe_result->ToObject(&result)) {
1732 HeapObject* target = HeapObject::cast(result);
1734 if (alignment != kObjectAlignment) {
1735 target = EnsureDoubleAligned(heap, target, allocation_size);
1738 // Order is important: slot might be inside of the target if target
1739 // was allocated over a dead object and slot comes from the store
1742 MigrateObject(heap, object, target, object_size);
1744 if (object_contents == POINTER_OBJECT) {
1745 if (map->instance_type() == JS_FUNCTION_TYPE) {
1746 heap->promotion_queue()->insert(
1747 target, JSFunction::kNonWeakFieldsEndOffset);
1749 heap->promotion_queue()->insert(target, object_size);
1753 heap->tracer()->increment_promoted_objects_size(object_size);
1757 MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
1758 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1759 Object* result = allocation->ToObjectUnchecked();
1760 HeapObject* target = HeapObject::cast(result);
1762 if (alignment != kObjectAlignment) {
1763 target = EnsureDoubleAligned(heap, target, allocation_size);
1766 // Order is important: slot might be inside of the target if target
1767 // was allocated over a dead object and slot comes from the store
1770 MigrateObject(heap, object, target, object_size);
1775 static inline void EvacuateJSFunction(Map* map,
1777 HeapObject* object) {
1778 ObjectEvacuationStrategy<POINTER_OBJECT>::
1779 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1781 HeapObject* target = *slot;
1782 MarkBit mark_bit = Marking::MarkBitFrom(target);
1783 if (Marking::IsBlack(mark_bit)) {
1784 // This object is black and it might not be rescanned by marker.
1785 // We should explicitly record code entry slot for compaction because
1786 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1787 // miss it as it is not HeapObject-tagged.
1788 Address code_entry_slot =
1789 target->address() + JSFunction::kCodeEntryOffset;
1790 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1791 map->GetHeap()->mark_compact_collector()->
1792 RecordCodeEntrySlot(code_entry_slot, code);
1797 static inline void EvacuateFixedArray(Map* map,
1799 HeapObject* object) {
1800 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1801 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
1808 static inline void EvacuateFixedDoubleArray(Map* map,
1810 HeapObject* object) {
1811 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1812 int object_size = FixedDoubleArray::SizeFor(length);
1813 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
1821 static inline void EvacuateByteArray(Map* map,
1823 HeapObject* object) {
1824 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1825 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1826 map, slot, object, object_size);
1830 static inline void EvacuateSeqAsciiString(Map* map,
1832 HeapObject* object) {
1833 int object_size = SeqAsciiString::cast(object)->
1834 SeqAsciiStringSize(map->instance_type());
1835 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1836 map, slot, object, object_size);
1840 static inline void EvacuateSeqTwoByteString(Map* map,
1842 HeapObject* object) {
1843 int object_size = SeqTwoByteString::cast(object)->
1844 SeqTwoByteStringSize(map->instance_type());
1845 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1846 map, slot, object, object_size);
1850 static inline bool IsShortcutCandidate(int type) {
1851 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1854 static inline void EvacuateShortcutCandidate(Map* map,
1856 HeapObject* object) {
1857 ASSERT(IsShortcutCandidate(map->instance_type()));
1859 Heap* heap = map->GetHeap();
1861 if (marks_handling == IGNORE_MARKS &&
1862 ConsString::cast(object)->unchecked_second() ==
1863 heap->empty_string()) {
1865 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1869 if (!heap->InNewSpace(first)) {
1870 object->set_map_word(MapWord::FromForwardingAddress(first));
1874 MapWord first_word = first->map_word();
1875 if (first_word.IsForwardingAddress()) {
1876 HeapObject* target = first_word.ToForwardingAddress();
1879 object->set_map_word(MapWord::FromForwardingAddress(target));
1883 heap->DoScavengeObject(first->map(), slot, first);
1884 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1888 int object_size = ConsString::kSize;
1889 EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
1890 map, slot, object, object_size);
1893 template<ObjectContents object_contents>
1894 class ObjectEvacuationStrategy {
1896 template<int object_size>
1897 static inline void VisitSpecialized(Map* map,
1899 HeapObject* object) {
1900 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1901 map, slot, object, object_size);
1904 static inline void Visit(Map* map,
1906 HeapObject* object) {
1907 int object_size = map->instance_size();
1908 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1909 map, slot, object, object_size);
1913 static VisitorDispatchTable<ScavengingCallback> table_;
1917 template<MarksHandling marks_handling,
1918 LoggingAndProfiling logging_and_profiling_mode>
1919 VisitorDispatchTable<ScavengingCallback>
1920 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1923 static void InitializeScavengingVisitorsTables() {
1924 ScavengingVisitor<TRANSFER_MARKS,
1925 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1926 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1927 ScavengingVisitor<TRANSFER_MARKS,
1928 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1929 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1933 void Heap::SelectScavengingVisitorsTable() {
1934 bool logging_and_profiling =
1935 isolate()->logger()->is_logging() ||
1936 CpuProfiler::is_profiling(isolate()) ||
1937 (isolate()->heap_profiler() != NULL &&
1938 isolate()->heap_profiler()->is_profiling());
1940 if (!incremental_marking()->IsMarking()) {
1941 if (!logging_and_profiling) {
1942 scavenging_visitors_table_.CopyFrom(
1943 ScavengingVisitor<IGNORE_MARKS,
1944 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1946 scavenging_visitors_table_.CopyFrom(
1947 ScavengingVisitor<IGNORE_MARKS,
1948 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1951 if (!logging_and_profiling) {
1952 scavenging_visitors_table_.CopyFrom(
1953 ScavengingVisitor<TRANSFER_MARKS,
1954 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1956 scavenging_visitors_table_.CopyFrom(
1957 ScavengingVisitor<TRANSFER_MARKS,
1958 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1961 if (incremental_marking()->IsCompacting()) {
1962 // When compacting forbid short-circuiting of cons-strings.
1963 // Scavenging code relies on the fact that new space object
1964 // can't be evacuated into evacuation candidate but
1965 // short-circuiting violates this assumption.
1966 scavenging_visitors_table_.Register(
1967 StaticVisitorBase::kVisitShortcutCandidate,
1968 scavenging_visitors_table_.GetVisitorById(
1969 StaticVisitorBase::kVisitConsString));
1975 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1976 SLOW_ASSERT(HEAP->InFromSpace(object));
1977 MapWord first_word = object->map_word();
1978 SLOW_ASSERT(!first_word.IsForwardingAddress());
1979 Map* map = first_word.ToMap();
1980 map->GetHeap()->DoScavengeObject(map, p, object);
1984 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1985 int instance_size) {
1987 { MaybeObject* maybe_result = AllocateRawMap();
1988 if (!maybe_result->ToObject(&result)) return maybe_result;
1991 // Map::cast cannot be used due to uninitialized map field.
1992 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1993 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1994 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1995 reinterpret_cast<Map*>(result)->set_visitor_id(
1996 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
1997 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
1998 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
1999 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2000 reinterpret_cast<Map*>(result)->set_bit_field(0);
2001 reinterpret_cast<Map*>(result)->set_bit_field2(0);
2006 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
2008 ElementsKind elements_kind) {
2010 { MaybeObject* maybe_result = AllocateRawMap();
2011 if (!maybe_result->ToObject(&result)) return maybe_result;
2014 Map* map = reinterpret_cast<Map*>(result);
2015 map->set_map_no_write_barrier(meta_map());
2016 map->set_instance_type(instance_type);
2017 map->set_visitor_id(
2018 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2019 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2020 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
2021 map->set_instance_size(instance_size);
2022 map->set_inobject_properties(0);
2023 map->set_pre_allocated_property_fields(0);
2024 map->init_instance_descriptors();
2025 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2026 map->init_prototype_transitions(undefined_value());
2027 map->set_unused_property_fields(0);
2028 map->set_bit_field(0);
2029 map->set_bit_field2(1 << Map::kIsExtensible);
2030 map->set_elements_kind(elements_kind);
2032 // If the map object is aligned fill the padding area with Smi 0 objects.
2033 if (Map::kPadStart < Map::kSize) {
2034 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
2036 Map::kSize - Map::kPadStart);
2042 MaybeObject* Heap::AllocateCodeCache() {
2043 CodeCache* code_cache;
2044 { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
2045 if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
2047 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2048 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
2053 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
2054 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
2058 MaybeObject* Heap::AllocateAccessorPair() {
2059 AccessorPair* accessors;
2060 { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
2061 if (!maybe_accessors->To(&accessors)) return maybe_accessors;
2063 accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
2064 accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
2069 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
2070 TypeFeedbackInfo* info;
2071 { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
2072 if (!maybe_info->To(&info)) return maybe_info;
2074 info->set_ic_total_count(0);
2075 info->set_ic_with_type_info_count(0);
2076 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
2077 SKIP_WRITE_BARRIER);
2082 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
2083 AliasedArgumentsEntry* entry;
2084 { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
2085 if (!maybe_entry->To(&entry)) return maybe_entry;
2087 entry->set_aliased_context_slot(aliased_context_slot);
2092 const Heap::StringTypeTable Heap::string_type_table[] = {
2093 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
2094 {type, size, k##camel_name##MapRootIndex},
2095 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2096 #undef STRING_TYPE_ELEMENT
2100 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
2101 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
2102 {contents, k##name##RootIndex},
2103 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
2104 #undef CONSTANT_SYMBOL_ELEMENT
2108 const Heap::StructTable Heap::struct_table[] = {
2109 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
2110 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
2111 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2112 #undef STRUCT_TABLE_ELEMENT
2116 bool Heap::CreateInitialMaps() {
2118 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2119 if (!maybe_obj->ToObject(&obj)) return false;
2121 // Map::cast cannot be used due to uninitialized map field.
2122 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2123 set_meta_map(new_meta_map);
2124 new_meta_map->set_map(new_meta_map);
2126 { MaybeObject* maybe_obj =
2127 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2128 if (!maybe_obj->ToObject(&obj)) return false;
2130 set_fixed_array_map(Map::cast(obj));
2132 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2133 if (!maybe_obj->ToObject(&obj)) return false;
2135 set_oddball_map(Map::cast(obj));
2137 // Allocate the empty array.
2138 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2139 if (!maybe_obj->ToObject(&obj)) return false;
2141 set_empty_fixed_array(FixedArray::cast(obj));
2143 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2144 if (!maybe_obj->ToObject(&obj)) return false;
2146 set_null_value(Oddball::cast(obj));
2147 Oddball::cast(obj)->set_kind(Oddball::kNull);
2149 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2150 if (!maybe_obj->ToObject(&obj)) return false;
2152 set_undefined_value(Oddball::cast(obj));
2153 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2154 ASSERT(!InNewSpace(undefined_value()));
2156 // Allocate the empty descriptor array.
2157 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2158 if (!maybe_obj->ToObject(&obj)) return false;
2160 set_empty_descriptor_array(DescriptorArray::cast(obj));
2162 // Fix the instance_descriptors for the existing maps.
2163 meta_map()->init_instance_descriptors();
2164 meta_map()->set_code_cache(empty_fixed_array());
2165 meta_map()->init_prototype_transitions(undefined_value());
2167 fixed_array_map()->init_instance_descriptors();
2168 fixed_array_map()->set_code_cache(empty_fixed_array());
2169 fixed_array_map()->init_prototype_transitions(undefined_value());
2171 oddball_map()->init_instance_descriptors();
2172 oddball_map()->set_code_cache(empty_fixed_array());
2173 oddball_map()->init_prototype_transitions(undefined_value());
2175 // Fix prototype object for existing maps.
2176 meta_map()->set_prototype(null_value());
2177 meta_map()->set_constructor(null_value());
2179 fixed_array_map()->set_prototype(null_value());
2180 fixed_array_map()->set_constructor(null_value());
2182 oddball_map()->set_prototype(null_value());
2183 oddball_map()->set_constructor(null_value());
2185 { MaybeObject* maybe_obj =
2186 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2187 if (!maybe_obj->ToObject(&obj)) return false;
2189 set_fixed_cow_array_map(Map::cast(obj));
2190 ASSERT(fixed_array_map() != fixed_cow_array_map());
2192 { MaybeObject* maybe_obj =
2193 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2194 if (!maybe_obj->ToObject(&obj)) return false;
2196 set_scope_info_map(Map::cast(obj));
2198 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2199 if (!maybe_obj->ToObject(&obj)) return false;
2201 set_heap_number_map(Map::cast(obj));
2203 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2204 if (!maybe_obj->ToObject(&obj)) return false;
2206 set_foreign_map(Map::cast(obj));
2208 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2209 const StringTypeTable& entry = string_type_table[i];
2210 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2211 if (!maybe_obj->ToObject(&obj)) return false;
2213 roots_[entry.index] = Map::cast(obj);
2216 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2217 if (!maybe_obj->ToObject(&obj)) return false;
2219 set_undetectable_string_map(Map::cast(obj));
2220 Map::cast(obj)->set_is_undetectable();
2222 { MaybeObject* maybe_obj =
2223 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2224 if (!maybe_obj->ToObject(&obj)) return false;
2226 set_undetectable_ascii_string_map(Map::cast(obj));
2227 Map::cast(obj)->set_is_undetectable();
2229 { MaybeObject* maybe_obj =
2230 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2231 if (!maybe_obj->ToObject(&obj)) return false;
2233 set_fixed_double_array_map(Map::cast(obj));
2235 { MaybeObject* maybe_obj =
2236 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2237 if (!maybe_obj->ToObject(&obj)) return false;
2239 set_byte_array_map(Map::cast(obj));
2241 { MaybeObject* maybe_obj =
2242 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2243 if (!maybe_obj->ToObject(&obj)) return false;
2245 set_free_space_map(Map::cast(obj));
2247 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2248 if (!maybe_obj->ToObject(&obj)) return false;
2250 set_empty_byte_array(ByteArray::cast(obj));
2252 { MaybeObject* maybe_obj =
2253 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2254 if (!maybe_obj->ToObject(&obj)) return false;
2256 set_external_pixel_array_map(Map::cast(obj));
2258 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2259 ExternalArray::kAlignedSize);
2260 if (!maybe_obj->ToObject(&obj)) return false;
2262 set_external_byte_array_map(Map::cast(obj));
2264 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2265 ExternalArray::kAlignedSize);
2266 if (!maybe_obj->ToObject(&obj)) return false;
2268 set_external_unsigned_byte_array_map(Map::cast(obj));
2270 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2271 ExternalArray::kAlignedSize);
2272 if (!maybe_obj->ToObject(&obj)) return false;
2274 set_external_short_array_map(Map::cast(obj));
2276 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2277 ExternalArray::kAlignedSize);
2278 if (!maybe_obj->ToObject(&obj)) return false;
2280 set_external_unsigned_short_array_map(Map::cast(obj));
2282 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2283 ExternalArray::kAlignedSize);
2284 if (!maybe_obj->ToObject(&obj)) return false;
2286 set_external_int_array_map(Map::cast(obj));
2288 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2289 ExternalArray::kAlignedSize);
2290 if (!maybe_obj->ToObject(&obj)) return false;
2292 set_external_unsigned_int_array_map(Map::cast(obj));
2294 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2295 ExternalArray::kAlignedSize);
2296 if (!maybe_obj->ToObject(&obj)) return false;
2298 set_external_float_array_map(Map::cast(obj));
2300 { MaybeObject* maybe_obj =
2301 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2302 if (!maybe_obj->ToObject(&obj)) return false;
2304 set_non_strict_arguments_elements_map(Map::cast(obj));
2306 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2307 ExternalArray::kAlignedSize);
2308 if (!maybe_obj->ToObject(&obj)) return false;
2310 set_external_double_array_map(Map::cast(obj));
2312 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2313 if (!maybe_obj->ToObject(&obj)) return false;
2315 set_code_map(Map::cast(obj));
2317 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2318 JSGlobalPropertyCell::kSize);
2319 if (!maybe_obj->ToObject(&obj)) return false;
2321 set_global_property_cell_map(Map::cast(obj));
2323 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2324 if (!maybe_obj->ToObject(&obj)) return false;
2326 set_one_pointer_filler_map(Map::cast(obj));
2328 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2329 if (!maybe_obj->ToObject(&obj)) return false;
2331 set_two_pointer_filler_map(Map::cast(obj));
2333 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2334 const StructTable& entry = struct_table[i];
2335 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2336 if (!maybe_obj->ToObject(&obj)) return false;
2338 roots_[entry.index] = Map::cast(obj);
2341 { MaybeObject* maybe_obj =
2342 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2343 if (!maybe_obj->ToObject(&obj)) return false;
2345 set_hash_table_map(Map::cast(obj));
2347 { MaybeObject* maybe_obj =
2348 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2349 if (!maybe_obj->ToObject(&obj)) return false;
2351 set_function_context_map(Map::cast(obj));
2353 { MaybeObject* maybe_obj =
2354 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2355 if (!maybe_obj->ToObject(&obj)) return false;
2357 set_catch_context_map(Map::cast(obj));
2359 { MaybeObject* maybe_obj =
2360 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2361 if (!maybe_obj->ToObject(&obj)) return false;
2363 set_with_context_map(Map::cast(obj));
2365 { MaybeObject* maybe_obj =
2366 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2367 if (!maybe_obj->ToObject(&obj)) return false;
2369 set_block_context_map(Map::cast(obj));
2371 { MaybeObject* maybe_obj =
2372 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2373 if (!maybe_obj->ToObject(&obj)) return false;
2375 set_module_context_map(Map::cast(obj));
2377 { MaybeObject* maybe_obj =
2378 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2379 if (!maybe_obj->ToObject(&obj)) return false;
2381 Map* global_context_map = Map::cast(obj);
2382 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2383 set_global_context_map(global_context_map);
2385 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2386 SharedFunctionInfo::kAlignedSize);
2387 if (!maybe_obj->ToObject(&obj)) return false;
2389 set_shared_function_info_map(Map::cast(obj));
2391 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2392 JSMessageObject::kSize);
2393 if (!maybe_obj->ToObject(&obj)) return false;
2395 set_message_object_map(Map::cast(obj));
2397 ASSERT(!InNewSpace(empty_fixed_array()));
2402 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2403 // Statically ensure that it is safe to allocate heap numbers in paged
2405 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2406 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2409 { MaybeObject* maybe_result =
2410 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2411 if (!maybe_result->ToObject(&result)) return maybe_result;
2414 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2415 HeapNumber::cast(result)->set_value(value);
2420 MaybeObject* Heap::AllocateHeapNumber(double value) {
2421 // Use general version, if we're forced to always allocate.
2422 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2424 // This version of AllocateHeapNumber is optimized for
2425 // allocation in new space.
2426 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2427 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2429 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2430 if (!maybe_result->ToObject(&result)) return maybe_result;
2432 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2433 HeapNumber::cast(result)->set_value(value);
2438 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2440 { MaybeObject* maybe_result = AllocateRawCell();
2441 if (!maybe_result->ToObject(&result)) return maybe_result;
2443 HeapObject::cast(result)->set_map_no_write_barrier(
2444 global_property_cell_map());
2445 JSGlobalPropertyCell::cast(result)->set_value(value);
2450 MaybeObject* Heap::CreateOddball(const char* to_string,
2454 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2455 if (!maybe_result->ToObject(&result)) return maybe_result;
2457 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2461 bool Heap::CreateApiObjects() {
2464 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2465 if (!maybe_obj->ToObject(&obj)) return false;
2467 // Don't use Smi-only elements optimizations for objects with the neander
2468 // map. There are too many cases where element values are set directly with a
2469 // bottleneck to trap the Smi-only -> fast elements transition, and there
2470 // appears to be no benefit for optimize this case.
2471 Map* new_neander_map = Map::cast(obj);
2472 new_neander_map->set_elements_kind(FAST_ELEMENTS);
2473 set_neander_map(new_neander_map);
2475 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2476 if (!maybe_obj->ToObject(&obj)) return false;
2479 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2480 if (!maybe_elements->ToObject(&elements)) return false;
2482 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2483 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2484 set_message_listeners(JSObject::cast(obj));
2490 void Heap::CreateJSEntryStub() {
2492 set_js_entry_code(*stub.GetCode());
2496 void Heap::CreateJSConstructEntryStub() {
2497 JSConstructEntryStub stub;
2498 set_js_construct_entry_code(*stub.GetCode());
2502 void Heap::CreateFixedStubs() {
2503 // Here we create roots for fixed stubs. They are needed at GC
2504 // for cooking and uncooking (check out frames.cc).
2505 // The eliminates the need for doing dictionary lookup in the
2506 // stub cache for these stubs.
2508 // gcc-4.4 has problem generating correct code of following snippet:
2509 // { JSEntryStub stub;
2510 // js_entry_code_ = *stub.GetCode();
2512 // { JSConstructEntryStub stub;
2513 // js_construct_entry_code_ = *stub.GetCode();
2515 // To workaround the problem, make separate functions without inlining.
2516 Heap::CreateJSEntryStub();
2517 Heap::CreateJSConstructEntryStub();
2519 // Create stubs that should be there, so we don't unexpectedly have to
2520 // create them if we need them during the creation of another stub.
2521 // Stub creation mixes raw pointers and handles in an unsafe manner so
2522 // we cannot create stubs while we are creating stubs.
2523 CodeStub::GenerateStubsAheadOfTime();
2527 bool Heap::CreateInitialObjects() {
2530 // The -0 value must be set before NumberFromDouble works.
2531 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2532 if (!maybe_obj->ToObject(&obj)) return false;
2534 set_minus_zero_value(HeapNumber::cast(obj));
2535 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2537 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2538 if (!maybe_obj->ToObject(&obj)) return false;
2540 set_nan_value(HeapNumber::cast(obj));
2542 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2543 if (!maybe_obj->ToObject(&obj)) return false;
2545 set_infinity_value(HeapNumber::cast(obj));
2547 // The hole has not been created yet, but we want to put something
2548 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2549 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2551 // Allocate initial symbol table.
2552 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2553 if (!maybe_obj->ToObject(&obj)) return false;
2555 // Don't use set_symbol_table() due to asserts.
2556 roots_[kSymbolTableRootIndex] = obj;
2558 // Finish initializing oddballs after creating symboltable.
2559 { MaybeObject* maybe_obj =
2560 undefined_value()->Initialize("undefined",
2562 Oddball::kUndefined);
2563 if (!maybe_obj->ToObject(&obj)) return false;
2566 // Initialize the null_value.
2567 { MaybeObject* maybe_obj =
2568 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2569 if (!maybe_obj->ToObject(&obj)) return false;
2572 { MaybeObject* maybe_obj = CreateOddball("true",
2575 if (!maybe_obj->ToObject(&obj)) return false;
2577 set_true_value(Oddball::cast(obj));
2579 { MaybeObject* maybe_obj = CreateOddball("false",
2582 if (!maybe_obj->ToObject(&obj)) return false;
2584 set_false_value(Oddball::cast(obj));
2586 { MaybeObject* maybe_obj = CreateOddball("hole",
2589 if (!maybe_obj->ToObject(&obj)) return false;
2591 set_the_hole_value(Oddball::cast(obj));
2593 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2595 Oddball::kArgumentMarker);
2596 if (!maybe_obj->ToObject(&obj)) return false;
2598 set_arguments_marker(Oddball::cast(obj));
2600 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2603 if (!maybe_obj->ToObject(&obj)) return false;
2605 set_no_interceptor_result_sentinel(obj);
2607 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2610 if (!maybe_obj->ToObject(&obj)) return false;
2612 set_termination_exception(obj);
2614 // Allocate the empty string.
2615 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2616 if (!maybe_obj->ToObject(&obj)) return false;
2618 set_empty_string(String::cast(obj));
2620 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2621 { MaybeObject* maybe_obj =
2622 LookupAsciiSymbol(constant_symbol_table[i].contents);
2623 if (!maybe_obj->ToObject(&obj)) return false;
2625 roots_[constant_symbol_table[i].index] = String::cast(obj);
2628 // Allocate the hidden symbol which is used to identify the hidden properties
2629 // in JSObjects. The hash code has a special value so that it will not match
2630 // the empty string when searching for the property. It cannot be part of the
2631 // loop above because it needs to be allocated manually with the special
2632 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2633 // that it will always be at the first entry in property descriptors.
2634 { MaybeObject* maybe_obj =
2635 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2636 if (!maybe_obj->ToObject(&obj)) return false;
2638 hidden_symbol_ = String::cast(obj);
2640 // Allocate the foreign for __proto__.
2641 { MaybeObject* maybe_obj =
2642 AllocateForeign((Address) &Accessors::ObjectPrototype);
2643 if (!maybe_obj->ToObject(&obj)) return false;
2645 set_prototype_accessors(Foreign::cast(obj));
2647 // Allocate the code_stubs dictionary. The initial size is set to avoid
2648 // expanding the dictionary during bootstrapping.
2649 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2650 if (!maybe_obj->ToObject(&obj)) return false;
2652 set_code_stubs(UnseededNumberDictionary::cast(obj));
2655 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2656 // is set to avoid expanding the dictionary during bootstrapping.
2657 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2658 if (!maybe_obj->ToObject(&obj)) return false;
2660 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2662 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2663 if (!maybe_obj->ToObject(&obj)) return false;
2665 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2667 set_instanceof_cache_function(Smi::FromInt(0));
2668 set_instanceof_cache_map(Smi::FromInt(0));
2669 set_instanceof_cache_answer(Smi::FromInt(0));
2673 // Allocate the dictionary of intrinsic function names.
2674 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2675 if (!maybe_obj->ToObject(&obj)) return false;
2677 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2679 if (!maybe_obj->ToObject(&obj)) return false;
2681 set_intrinsic_function_names(StringDictionary::cast(obj));
2683 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2684 if (!maybe_obj->ToObject(&obj)) return false;
2686 set_number_string_cache(FixedArray::cast(obj));
2688 // Allocate cache for single character ASCII strings.
2689 { MaybeObject* maybe_obj =
2690 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2691 if (!maybe_obj->ToObject(&obj)) return false;
2693 set_single_character_string_cache(FixedArray::cast(obj));
2695 // Allocate cache for string split.
2696 { MaybeObject* maybe_obj =
2697 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2698 if (!maybe_obj->ToObject(&obj)) return false;
2700 set_string_split_cache(FixedArray::cast(obj));
2702 // Allocate cache for external strings pointing to native source code.
2703 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2704 if (!maybe_obj->ToObject(&obj)) return false;
2706 set_natives_source_cache(FixedArray::cast(obj));
2708 // Handling of script id generation is in FACTORY->NewScript.
2709 set_last_script_id(undefined_value());
2711 // Initialize keyed lookup cache.
2712 isolate_->keyed_lookup_cache()->Clear();
2714 // Initialize context slot cache.
2715 isolate_->context_slot_cache()->Clear();
2717 // Initialize descriptor cache.
2718 isolate_->descriptor_lookup_cache()->Clear();
2720 // Initialize compilation cache.
2721 isolate_->compilation_cache()->Clear();
2727 Object* StringSplitCache::Lookup(
2728 FixedArray* cache, String* string, String* pattern) {
2729 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2730 uint32_t hash = string->Hash();
2731 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2732 ~(kArrayEntriesPerCacheEntry - 1));
2733 if (cache->get(index + kStringOffset) == string &&
2734 cache->get(index + kPatternOffset) == pattern) {
2735 return cache->get(index + kArrayOffset);
2737 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2738 if (cache->get(index + kStringOffset) == string &&
2739 cache->get(index + kPatternOffset) == pattern) {
2740 return cache->get(index + kArrayOffset);
2742 return Smi::FromInt(0);
2746 void StringSplitCache::Enter(Heap* heap,
2750 FixedArray* array) {
2751 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2752 uint32_t hash = string->Hash();
2753 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2754 ~(kArrayEntriesPerCacheEntry - 1));
2755 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2756 cache->set(index + kStringOffset, string);
2757 cache->set(index + kPatternOffset, pattern);
2758 cache->set(index + kArrayOffset, array);
2761 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2762 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2763 cache->set(index2 + kStringOffset, string);
2764 cache->set(index2 + kPatternOffset, pattern);
2765 cache->set(index2 + kArrayOffset, array);
2767 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2768 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2769 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2770 cache->set(index + kStringOffset, string);
2771 cache->set(index + kPatternOffset, pattern);
2772 cache->set(index + kArrayOffset, array);
2775 if (array->length() < 100) { // Limit how many new symbols we want to make.
2776 for (int i = 0; i < array->length(); i++) {
2777 String* str = String::cast(array->get(i));
2779 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2780 if (maybe_symbol->ToObject(&symbol)) {
2781 array->set(i, symbol);
2785 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2789 void StringSplitCache::Clear(FixedArray* cache) {
2790 for (int i = 0; i < kStringSplitCacheSize; i++) {
2791 cache->set(i, Smi::FromInt(0));
2796 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2797 MaybeObject* maybe_obj =
2798 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2803 int Heap::FullSizeNumberStringCacheLength() {
2804 // Compute the size of the number string cache based on the max newspace size.
2805 // The number string cache has a minimum size based on twice the initial cache
2806 // size to ensure that it is bigger after being made 'full size'.
2807 int number_string_cache_size = max_semispace_size_ / 512;
2808 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2809 Min(0x4000, number_string_cache_size));
2810 // There is a string and a number per entry so the length is twice the number
2812 return number_string_cache_size * 2;
2816 void Heap::AllocateFullSizeNumberStringCache() {
2817 // The idea is to have a small number string cache in the snapshot to keep
2818 // boot-time memory usage down. If we expand the number string cache already
2819 // while creating the snapshot then that didn't work out.
2820 ASSERT(!Serializer::enabled());
2821 MaybeObject* maybe_obj =
2822 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2824 if (maybe_obj->ToObject(&new_cache)) {
2825 // We don't bother to repopulate the cache with entries from the old cache.
2826 // It will be repopulated soon enough with new strings.
2827 set_number_string_cache(FixedArray::cast(new_cache));
2829 // If allocation fails then we just return without doing anything. It is only
2830 // a cache, so best effort is OK here.
2834 void Heap::FlushNumberStringCache() {
2835 // Flush the number to string cache.
2836 int len = number_string_cache()->length();
2837 for (int i = 0; i < len; i++) {
2838 number_string_cache()->set_undefined(this, i);
2843 static inline int double_get_hash(double d) {
2844 DoubleRepresentation rep(d);
2845 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2849 static inline int smi_get_hash(Smi* smi) {
2850 return smi->value();
2854 Object* Heap::GetNumberStringCache(Object* number) {
2856 int mask = (number_string_cache()->length() >> 1) - 1;
2857 if (number->IsSmi()) {
2858 hash = smi_get_hash(Smi::cast(number)) & mask;
2860 hash = double_get_hash(number->Number()) & mask;
2862 Object* key = number_string_cache()->get(hash * 2);
2863 if (key == number) {
2864 return String::cast(number_string_cache()->get(hash * 2 + 1));
2865 } else if (key->IsHeapNumber() &&
2866 number->IsHeapNumber() &&
2867 key->Number() == number->Number()) {
2868 return String::cast(number_string_cache()->get(hash * 2 + 1));
2870 return undefined_value();
2874 void Heap::SetNumberStringCache(Object* number, String* string) {
2876 int mask = (number_string_cache()->length() >> 1) - 1;
2877 if (number->IsSmi()) {
2878 hash = smi_get_hash(Smi::cast(number)) & mask;
2880 hash = double_get_hash(number->Number()) & mask;
2882 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2883 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2884 // The first time we have a hash collision, we move to the full sized
2885 // number string cache.
2886 AllocateFullSizeNumberStringCache();
2889 number_string_cache()->set(hash * 2, number);
2890 number_string_cache()->set(hash * 2 + 1, string);
2894 MaybeObject* Heap::NumberToString(Object* number,
2895 bool check_number_string_cache) {
2896 isolate_->counters()->number_to_string_runtime()->Increment();
2897 if (check_number_string_cache) {
2898 Object* cached = GetNumberStringCache(number);
2899 if (cached != undefined_value()) {
2905 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2907 if (number->IsSmi()) {
2908 int num = Smi::cast(number)->value();
2909 str = IntToCString(num, buffer);
2911 double num = HeapNumber::cast(number)->value();
2912 str = DoubleToCString(num, buffer);
2916 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2917 if (maybe_js_string->ToObject(&js_string)) {
2918 SetNumberStringCache(number, String::cast(js_string));
2920 return maybe_js_string;
2924 MaybeObject* Heap::Uint32ToString(uint32_t value,
2925 bool check_number_string_cache) {
2927 MaybeObject* maybe = NumberFromUint32(value);
2928 if (!maybe->To<Object>(&number)) return maybe;
2929 return NumberToString(number, check_number_string_cache);
2933 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2934 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2938 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2939 ExternalArrayType array_type) {
2940 switch (array_type) {
2941 case kExternalByteArray:
2942 return kExternalByteArrayMapRootIndex;
2943 case kExternalUnsignedByteArray:
2944 return kExternalUnsignedByteArrayMapRootIndex;
2945 case kExternalShortArray:
2946 return kExternalShortArrayMapRootIndex;
2947 case kExternalUnsignedShortArray:
2948 return kExternalUnsignedShortArrayMapRootIndex;
2949 case kExternalIntArray:
2950 return kExternalIntArrayMapRootIndex;
2951 case kExternalUnsignedIntArray:
2952 return kExternalUnsignedIntArrayMapRootIndex;
2953 case kExternalFloatArray:
2954 return kExternalFloatArrayMapRootIndex;
2955 case kExternalDoubleArray:
2956 return kExternalDoubleArrayMapRootIndex;
2957 case kExternalPixelArray:
2958 return kExternalPixelArrayMapRootIndex;
2961 return kUndefinedValueRootIndex;
2966 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2967 // We need to distinguish the minus zero value and this cannot be
2968 // done after conversion to int. Doing this by comparing bit
2969 // patterns is faster than using fpclassify() et al.
2970 static const DoubleRepresentation minus_zero(-0.0);
2972 DoubleRepresentation rep(value);
2973 if (rep.bits == minus_zero.bits) {
2974 return AllocateHeapNumber(-0.0, pretenure);
2977 int int_value = FastD2I(value);
2978 if (value == int_value && Smi::IsValid(int_value)) {
2979 return Smi::FromInt(int_value);
2982 // Materialize the value in the heap.
2983 return AllocateHeapNumber(value, pretenure);
2987 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2988 // Statically ensure that it is safe to allocate foreigns in paged spaces.
2989 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
2990 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2992 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2993 if (!maybe_result->To(&result)) return maybe_result;
2994 result->set_foreign_address(address);
2999 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
3000 SharedFunctionInfo* share;
3001 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
3002 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
3004 // Set pointer fields.
3005 share->set_name(name);
3006 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
3007 share->set_code(illegal);
3008 share->set_scope_info(ScopeInfo::Empty());
3009 Code* construct_stub =
3010 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
3011 share->set_construct_stub(construct_stub);
3012 share->set_instance_class_name(Object_symbol());
3013 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
3014 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
3015 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
3016 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
3017 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
3018 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
3019 share->set_ast_node_count(0);
3020 share->set_deopt_counter(FLAG_deopt_every_n_times);
3021 share->set_ic_age(0);
3023 // Set integer fields (smi or int, depending on the architecture).
3024 share->set_length(0);
3025 share->set_formal_parameter_count(0);
3026 share->set_expected_nof_properties(0);
3027 share->set_num_literals(0);
3028 share->set_start_position_and_type(0);
3029 share->set_end_position(0);
3030 share->set_function_token_position(0);
3031 // All compiler hints default to false or 0.
3032 share->set_compiler_hints(0);
3033 share->set_this_property_assignments_count(0);
3034 share->set_opt_count(0);
3040 MaybeObject* Heap::AllocateJSMessageObject(String* type,
3045 Object* stack_trace,
3046 Object* stack_frames) {
3048 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
3049 if (!maybe_result->ToObject(&result)) return maybe_result;
3051 JSMessageObject* message = JSMessageObject::cast(result);
3052 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3053 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3054 message->set_type(type);
3055 message->set_arguments(arguments);
3056 message->set_start_position(start_position);
3057 message->set_end_position(end_position);
3058 message->set_script(script);
3059 message->set_stack_trace(stack_trace);
3060 message->set_stack_frames(stack_frames);
3066 // Returns true for a character in a range. Both limits are inclusive.
3067 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
3068 // This makes uses of the the unsigned wraparound.
3069 return character - from <= to - from;
3073 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
3078 // Numeric strings have a different hash algorithm not known by
3079 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
3080 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
3081 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
3083 // Now we know the length is 2, we might as well make use of that fact
3084 // when building the new string.
3085 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
3086 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
3088 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
3089 if (!maybe_result->ToObject(&result)) return maybe_result;
3091 char* dest = SeqAsciiString::cast(result)->GetChars();
3097 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
3098 if (!maybe_result->ToObject(&result)) return maybe_result;
3100 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3108 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
3109 int first_length = first->length();
3110 if (first_length == 0) {
3114 int second_length = second->length();
3115 if (second_length == 0) {
3119 int length = first_length + second_length;
3121 // Optimization for 2-byte strings often used as keys in a decompression
3122 // dictionary. Check whether we already have the string in the symbol
3123 // table to prevent creation of many unneccesary strings.
3125 unsigned c1 = first->Get(0);
3126 unsigned c2 = second->Get(0);
3127 return MakeOrFindTwoCharacterString(this, c1, c2);
3130 bool first_is_ascii = first->IsAsciiRepresentation();
3131 bool second_is_ascii = second->IsAsciiRepresentation();
3132 bool is_ascii = first_is_ascii && second_is_ascii;
3134 // Make sure that an out of memory exception is thrown if the length
3135 // of the new cons string is too large.
3136 if (length > String::kMaxLength || length < 0) {
3137 isolate()->context()->mark_out_of_memory();
3138 return Failure::OutOfMemoryException();
3141 bool is_ascii_data_in_two_byte_string = false;
3143 // At least one of the strings uses two-byte representation so we
3144 // can't use the fast case code for short ASCII strings below, but
3145 // we can try to save memory if all chars actually fit in ASCII.
3146 is_ascii_data_in_two_byte_string =
3147 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3148 if (is_ascii_data_in_two_byte_string) {
3149 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3153 // If the resulting string is small make a flat string.
3154 if (length < ConsString::kMinLength) {
3155 // Note that neither of the two inputs can be a slice because:
3156 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3157 ASSERT(first->IsFlat());
3158 ASSERT(second->IsFlat());
3161 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3162 if (!maybe_result->ToObject(&result)) return maybe_result;
3164 // Copy the characters into the new object.
3165 char* dest = SeqAsciiString::cast(result)->GetChars();
3168 if (first->IsExternalString()) {
3169 src = ExternalAsciiString::cast(first)->GetChars();
3171 src = SeqAsciiString::cast(first)->GetChars();
3173 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3174 // Copy second part.
3175 if (second->IsExternalString()) {
3176 src = ExternalAsciiString::cast(second)->GetChars();
3178 src = SeqAsciiString::cast(second)->GetChars();
3180 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3183 if (is_ascii_data_in_two_byte_string) {
3185 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3186 if (!maybe_result->ToObject(&result)) return maybe_result;
3188 // Copy the characters into the new object.
3189 char* dest = SeqAsciiString::cast(result)->GetChars();
3190 String::WriteToFlat(first, dest, 0, first_length);
3191 String::WriteToFlat(second, dest + first_length, 0, second_length);
3192 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3197 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3198 if (!maybe_result->ToObject(&result)) return maybe_result;
3200 // Copy the characters into the new object.
3201 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3202 String::WriteToFlat(first, dest, 0, first_length);
3203 String::WriteToFlat(second, dest + first_length, 0, second_length);
3208 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3209 cons_ascii_string_map() : cons_string_map();
3212 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3213 if (!maybe_result->ToObject(&result)) return maybe_result;
3216 AssertNoAllocation no_gc;
3217 ConsString* cons_string = ConsString::cast(result);
3218 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3219 cons_string->set_length(length);
3220 cons_string->set_hash_field(String::kEmptyHashField);
3221 cons_string->set_first(first, mode);
3222 cons_string->set_second(second, mode);
3227 MaybeObject* Heap::AllocateSubString(String* buffer,
3230 PretenureFlag pretenure) {
3231 int length = end - start;
3233 return empty_string();
3234 } else if (length == 1) {
3235 return LookupSingleCharacterStringFromCode(buffer->Get(start));
3236 } else if (length == 2) {
3237 // Optimization for 2-byte strings often used as keys in a decompression
3238 // dictionary. Check whether we already have the string in the symbol
3239 // table to prevent creation of many unneccesary strings.
3240 unsigned c1 = buffer->Get(start);
3241 unsigned c2 = buffer->Get(start + 1);
3242 return MakeOrFindTwoCharacterString(this, c1, c2);
3245 // Make an attempt to flatten the buffer to reduce access time.
3246 buffer = buffer->TryFlattenGetString();
3248 if (!FLAG_string_slices ||
3249 !buffer->IsFlat() ||
3250 length < SlicedString::kMinLength ||
3251 pretenure == TENURED) {
3253 // WriteToFlat takes care of the case when an indirect string has a
3254 // different encoding from its underlying string. These encodings may
3255 // differ because of externalization.
3256 bool is_ascii = buffer->IsAsciiRepresentation();
3257 { MaybeObject* maybe_result = is_ascii
3258 ? AllocateRawAsciiString(length, pretenure)
3259 : AllocateRawTwoByteString(length, pretenure);
3260 if (!maybe_result->ToObject(&result)) return maybe_result;
3262 String* string_result = String::cast(result);
3263 // Copy the characters into the new object.
3265 ASSERT(string_result->IsAsciiRepresentation());
3266 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3267 String::WriteToFlat(buffer, dest, start, end);
3269 ASSERT(string_result->IsTwoByteRepresentation());
3270 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3271 String::WriteToFlat(buffer, dest, start, end);
3276 ASSERT(buffer->IsFlat());
3278 if (FLAG_verify_heap) {
3279 buffer->StringVerify();
3284 // When slicing an indirect string we use its encoding for a newly created
3285 // slice and don't check the encoding of the underlying string. This is safe
3286 // even if the encodings are different because of externalization. If an
3287 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3288 // codes of the underlying string must still fit into ASCII (because
3289 // externalization must not change char codes).
3290 { Map* map = buffer->IsAsciiRepresentation()
3291 ? sliced_ascii_string_map()
3292 : sliced_string_map();
3293 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3294 if (!maybe_result->ToObject(&result)) return maybe_result;
3297 AssertNoAllocation no_gc;
3298 SlicedString* sliced_string = SlicedString::cast(result);
3299 sliced_string->set_length(length);
3300 sliced_string->set_hash_field(String::kEmptyHashField);
3301 if (buffer->IsConsString()) {
3302 ConsString* cons = ConsString::cast(buffer);
3303 ASSERT(cons->second()->length() == 0);
3304 sliced_string->set_parent(cons->first());
3305 sliced_string->set_offset(start);
3306 } else if (buffer->IsSlicedString()) {
3307 // Prevent nesting sliced strings.
3308 SlicedString* parent_slice = SlicedString::cast(buffer);
3309 sliced_string->set_parent(parent_slice->parent());
3310 sliced_string->set_offset(start + parent_slice->offset());
3312 sliced_string->set_parent(buffer);
3313 sliced_string->set_offset(start);
3315 ASSERT(sliced_string->parent()->IsSeqString() ||
3316 sliced_string->parent()->IsExternalString());
3321 MaybeObject* Heap::AllocateExternalStringFromAscii(
3322 const ExternalAsciiString::Resource* resource) {
3323 size_t length = resource->length();
3324 if (length > static_cast<size_t>(String::kMaxLength)) {
3325 isolate()->context()->mark_out_of_memory();
3326 return Failure::OutOfMemoryException();
3329 Map* map = external_ascii_string_map();
3331 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3332 if (!maybe_result->ToObject(&result)) return maybe_result;
3335 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3336 external_string->set_length(static_cast<int>(length));
3337 external_string->set_hash_field(String::kEmptyHashField);
3338 external_string->set_resource(resource);
3344 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3345 const ExternalTwoByteString::Resource* resource) {
3346 size_t length = resource->length();
3347 if (length > static_cast<size_t>(String::kMaxLength)) {
3348 isolate()->context()->mark_out_of_memory();
3349 return Failure::OutOfMemoryException();
3352 // For small strings we check whether the resource contains only
3353 // ASCII characters. If yes, we use a different string map.
3354 static const size_t kAsciiCheckLengthLimit = 32;
3355 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3356 String::IsAscii(resource->data(), static_cast<int>(length));
3357 Map* map = is_ascii ?
3358 external_string_with_ascii_data_map() : external_string_map();
3360 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3361 if (!maybe_result->ToObject(&result)) return maybe_result;
3364 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3365 external_string->set_length(static_cast<int>(length));
3366 external_string->set_hash_field(String::kEmptyHashField);
3367 external_string->set_resource(resource);
3373 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3374 if (code <= String::kMaxAsciiCharCode) {
3375 Object* value = single_character_string_cache()->get(code);
3376 if (value != undefined_value()) return value;
3379 buffer[0] = static_cast<char>(code);
3381 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3383 if (!maybe_result->ToObject(&result)) return maybe_result;
3384 single_character_string_cache()->set(code, result);
3389 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3390 if (!maybe_result->ToObject(&result)) return maybe_result;
3392 String* answer = String::cast(result);
3393 answer->Set(0, code);
3398 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3399 if (length < 0 || length > ByteArray::kMaxLength) {
3400 return Failure::OutOfMemoryException();
3402 if (pretenure == NOT_TENURED) {
3403 return AllocateByteArray(length);
3405 int size = ByteArray::SizeFor(length);
3407 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3408 ? old_data_space_->AllocateRaw(size)
3409 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3410 if (!maybe_result->ToObject(&result)) return maybe_result;
3413 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3415 reinterpret_cast<ByteArray*>(result)->set_length(length);
3420 MaybeObject* Heap::AllocateByteArray(int length) {
3421 if (length < 0 || length > ByteArray::kMaxLength) {
3422 return Failure::OutOfMemoryException();
3424 int size = ByteArray::SizeFor(length);
3425 AllocationSpace space =
3426 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3428 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3429 if (!maybe_result->ToObject(&result)) return maybe_result;
3432 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3434 reinterpret_cast<ByteArray*>(result)->set_length(length);
3439 void Heap::CreateFillerObjectAt(Address addr, int size) {
3440 if (size == 0) return;
3441 HeapObject* filler = HeapObject::FromAddress(addr);
3442 if (size == kPointerSize) {
3443 filler->set_map_no_write_barrier(one_pointer_filler_map());
3444 } else if (size == 2 * kPointerSize) {
3445 filler->set_map_no_write_barrier(two_pointer_filler_map());
3447 filler->set_map_no_write_barrier(free_space_map());
3448 FreeSpace::cast(filler)->set_size(size);
3453 MaybeObject* Heap::AllocateExternalArray(int length,
3454 ExternalArrayType array_type,
3455 void* external_pointer,
3456 PretenureFlag pretenure) {
3457 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3459 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3462 if (!maybe_result->ToObject(&result)) return maybe_result;
3465 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3466 MapForExternalArrayType(array_type));
3467 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3468 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3475 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3477 Handle<Object> self_reference,
3479 // Allocate ByteArray before the Code object, so that we do not risk
3480 // leaving uninitialized Code object (and breaking the heap).
3481 ByteArray* reloc_info;
3482 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3483 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3486 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3487 int obj_size = Code::SizeFor(body_size);
3488 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3489 MaybeObject* maybe_result;
3490 // Large code objects and code objects which should stay at a fixed address
3491 // are allocated in large object space.
3492 if (obj_size > code_space()->AreaSize() || immovable) {
3493 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3495 maybe_result = code_space_->AllocateRaw(obj_size);
3499 if (!maybe_result->ToObject(&result)) return maybe_result;
3501 // Initialize the object
3502 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3503 Code* code = Code::cast(result);
3504 ASSERT(!isolate_->code_range()->exists() ||
3505 isolate_->code_range()->contains(code->address()));
3506 code->set_instruction_size(desc.instr_size);
3507 code->set_relocation_info(reloc_info);
3508 code->set_flags(flags);
3509 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3510 code->set_check_type(RECEIVER_MAP_CHECK);
3512 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3513 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3514 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3515 code->set_gc_metadata(Smi::FromInt(0));
3516 code->set_ic_age(global_ic_age_);
3517 // Allow self references to created code object by patching the handle to
3518 // point to the newly allocated Code object.
3519 if (!self_reference.is_null()) {
3520 *(self_reference.location()) = code;
3522 // Migrate generated code.
3523 // The generated code can contain Object** values (typically from handles)
3524 // that are dereferenced during the copy to point directly to the actual heap
3525 // objects. These pointers can include references to the code object itself,
3526 // through the self_reference parameter.
3527 code->CopyFrom(desc);
3530 if (FLAG_verify_heap) {
3538 MaybeObject* Heap::CopyCode(Code* code) {
3539 // Allocate an object the same size as the code object.
3540 int obj_size = code->Size();
3541 MaybeObject* maybe_result;
3542 if (obj_size > code_space()->AreaSize()) {
3543 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3545 maybe_result = code_space_->AllocateRaw(obj_size);
3549 if (!maybe_result->ToObject(&result)) return maybe_result;
3551 // Copy code object.
3552 Address old_addr = code->address();
3553 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3554 CopyBlock(new_addr, old_addr, obj_size);
3555 // Relocate the copy.
3556 Code* new_code = Code::cast(result);
3557 ASSERT(!isolate_->code_range()->exists() ||
3558 isolate_->code_range()->contains(code->address()));
3559 new_code->Relocate(new_addr - old_addr);
3564 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3565 // Allocate ByteArray before the Code object, so that we do not risk
3566 // leaving uninitialized Code object (and breaking the heap).
3567 Object* reloc_info_array;
3568 { MaybeObject* maybe_reloc_info_array =
3569 AllocateByteArray(reloc_info.length(), TENURED);
3570 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3571 return maybe_reloc_info_array;
3575 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3577 int new_obj_size = Code::SizeFor(new_body_size);
3579 Address old_addr = code->address();
3581 size_t relocation_offset =
3582 static_cast<size_t>(code->instruction_end() - old_addr);
3584 MaybeObject* maybe_result;
3585 if (new_obj_size > code_space()->AreaSize()) {
3586 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3588 maybe_result = code_space_->AllocateRaw(new_obj_size);
3592 if (!maybe_result->ToObject(&result)) return maybe_result;
3594 // Copy code object.
3595 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3597 // Copy header and instructions.
3598 memcpy(new_addr, old_addr, relocation_offset);
3600 Code* new_code = Code::cast(result);
3601 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3603 // Copy patched rinfo.
3604 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3606 // Relocate the copy.
3607 ASSERT(!isolate_->code_range()->exists() ||
3608 isolate_->code_range()->contains(code->address()));
3609 new_code->Relocate(new_addr - old_addr);
3612 if (FLAG_verify_heap) {
3620 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3621 ASSERT(gc_state_ == NOT_IN_GC);
3622 ASSERT(map->instance_type() != MAP_TYPE);
3623 // If allocation failures are disallowed, we may allocate in a different
3624 // space when new space is full and the object is not a large object.
3625 AllocationSpace retry_space =
3626 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3628 { MaybeObject* maybe_result =
3629 AllocateRaw(map->instance_size(), space, retry_space);
3630 if (!maybe_result->ToObject(&result)) return maybe_result;
3632 // No need for write barrier since object is white and map is in old space.
3633 HeapObject::cast(result)->set_map_no_write_barrier(map);
3638 void Heap::InitializeFunction(JSFunction* function,
3639 SharedFunctionInfo* shared,
3640 Object* prototype) {
3641 ASSERT(!prototype->IsMap());
3642 function->initialize_properties();
3643 function->initialize_elements();
3644 function->set_shared(shared);
3645 function->set_code(shared->code());
3646 function->set_prototype_or_initial_map(prototype);
3647 function->set_context(undefined_value());
3648 function->set_literals_or_bindings(empty_fixed_array());
3649 function->set_next_function_link(undefined_value());
3653 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3654 // Allocate the prototype. Make sure to use the object function
3655 // from the function's context, since the function can be from a
3656 // different context.
3657 JSFunction* object_function =
3658 function->context()->global_context()->object_function();
3660 // Each function prototype gets a copy of the object function map.
3661 // This avoid unwanted sharing of maps between prototypes of different
3664 ASSERT(object_function->has_initial_map());
3665 { MaybeObject* maybe_map =
3666 object_function->initial_map()->CopyDropTransitions();
3667 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3670 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3671 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3673 // When creating the prototype for the function we must set its
3674 // constructor to the function.
3676 { MaybeObject* maybe_result =
3677 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3678 constructor_symbol(), function, DONT_ENUM);
3679 if (!maybe_result->ToObject(&result)) return maybe_result;
3685 MaybeObject* Heap::AllocateFunction(Map* function_map,
3686 SharedFunctionInfo* shared,
3688 PretenureFlag pretenure) {
3689 AllocationSpace space =
3690 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3692 { MaybeObject* maybe_result = Allocate(function_map, space);
3693 if (!maybe_result->ToObject(&result)) return maybe_result;
3695 InitializeFunction(JSFunction::cast(result), shared, prototype);
3700 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3701 // To get fast allocation and map sharing for arguments objects we
3702 // allocate them based on an arguments boilerplate.
3704 JSObject* boilerplate;
3705 int arguments_object_size;
3706 bool strict_mode_callee = callee->IsJSFunction() &&
3707 !JSFunction::cast(callee)->shared()->is_classic_mode();
3708 if (strict_mode_callee) {
3710 isolate()->context()->global_context()->
3711 strict_mode_arguments_boilerplate();
3712 arguments_object_size = kArgumentsObjectSizeStrict;
3715 isolate()->context()->global_context()->arguments_boilerplate();
3716 arguments_object_size = kArgumentsObjectSize;
3719 // This calls Copy directly rather than using Heap::AllocateRaw so we
3720 // duplicate the check here.
3721 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3723 // Check that the size of the boilerplate matches our
3724 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3725 // on the size being a known constant.
3726 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3728 // Do the allocation.
3730 { MaybeObject* maybe_result =
3731 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3732 if (!maybe_result->ToObject(&result)) return maybe_result;
3735 // Copy the content. The arguments boilerplate doesn't have any
3736 // fields that point to new space so it's safe to skip the write
3738 CopyBlock(HeapObject::cast(result)->address(),
3739 boilerplate->address(),
3740 JSObject::kHeaderSize);
3742 // Set the length property.
3743 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3744 Smi::FromInt(length),
3745 SKIP_WRITE_BARRIER);
3746 // Set the callee property for non-strict mode arguments object only.
3747 if (!strict_mode_callee) {
3748 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3752 // Check the state of the object
3753 ASSERT(JSObject::cast(result)->HasFastProperties());
3754 ASSERT(JSObject::cast(result)->HasFastElements());
3760 static bool HasDuplicates(DescriptorArray* descriptors) {
3761 int count = descriptors->number_of_descriptors();
3763 String* prev_key = descriptors->GetKey(0);
3764 for (int i = 1; i != count; i++) {
3765 String* current_key = descriptors->GetKey(i);
3766 if (prev_key == current_key) return true;
3767 prev_key = current_key;
3774 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3775 ASSERT(!fun->has_initial_map());
3777 // First create a new map with the size and number of in-object properties
3778 // suggested by the function.
3779 int instance_size = fun->shared()->CalculateInstanceSize();
3780 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3782 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3783 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3786 // Fetch or allocate prototype.
3788 if (fun->has_instance_prototype()) {
3789 prototype = fun->instance_prototype();
3791 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3792 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3795 Map* map = Map::cast(map_obj);
3796 map->set_inobject_properties(in_object_properties);
3797 map->set_unused_property_fields(in_object_properties);
3798 map->set_prototype(prototype);
3799 ASSERT(map->has_fast_elements());
3801 // If the function has only simple this property assignments add
3802 // field descriptors for these to the initial map as the object
3803 // cannot be constructed without having these properties. Guard by
3804 // the inline_new flag so we only change the map if we generate a
3805 // specialized construct stub.
3806 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3807 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3808 int count = fun->shared()->this_property_assignments_count();
3809 if (count > in_object_properties) {
3810 // Inline constructor can only handle inobject properties.
3811 fun->shared()->ForbidInlineConstructor();
3813 DescriptorArray* descriptors;
3814 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
3815 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
3816 return maybe_descriptors_obj;
3819 DescriptorArray::WhitenessWitness witness(descriptors);
3820 for (int i = 0; i < count; i++) {
3821 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3822 ASSERT(name->IsSymbol());
3823 FieldDescriptor field(name, i, NONE);
3824 field.SetEnumerationIndex(i);
3825 descriptors->Set(i, &field, witness);
3827 descriptors->SetNextEnumerationIndex(count);
3828 descriptors->SortUnchecked(witness);
3830 // The descriptors may contain duplicates because the compiler does not
3831 // guarantee the uniqueness of property names (it would have required
3832 // quadratic time). Once the descriptors are sorted we can check for
3833 // duplicates in linear time.
3834 if (HasDuplicates(descriptors)) {
3835 fun->shared()->ForbidInlineConstructor();
3837 map->set_instance_descriptors(descriptors);
3838 map->set_pre_allocated_property_fields(count);
3839 map->set_unused_property_fields(in_object_properties - count);
3844 fun->shared()->StartInobjectSlackTracking(map);
3850 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3851 FixedArray* properties,
3853 obj->set_properties(properties);
3854 obj->initialize_elements();
3855 // TODO(1240798): Initialize the object's body using valid initial values
3856 // according to the object's initial map. For example, if the map's
3857 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3858 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3859 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3860 // verification code has to cope with (temporarily) invalid objects. See
3861 // for example, JSArray::JSArrayVerify).
3863 // We cannot always fill with one_pointer_filler_map because objects
3864 // created from API functions expect their internal fields to be initialized
3865 // with undefined_value.
3866 // Pre-allocated fields need to be initialized with undefined_value as well
3867 // so that object accesses before the constructor completes (e.g. in the
3868 // debugger) will not cause a crash.
3869 if (map->constructor()->IsJSFunction() &&
3870 JSFunction::cast(map->constructor())->shared()->
3871 IsInobjectSlackTrackingInProgress()) {
3872 // We might want to shrink the object later.
3873 ASSERT(obj->GetInternalFieldCount() == 0);
3874 filler = Heap::one_pointer_filler_map();
3876 filler = Heap::undefined_value();
3878 obj->InitializeBody(map, Heap::undefined_value(), filler);
3882 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3883 // JSFunctions should be allocated using AllocateFunction to be
3884 // properly initialized.
3885 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3887 // Both types of global objects should be allocated using
3888 // AllocateGlobalObject to be properly initialized.
3889 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3890 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3892 // Allocate the backing storage for the properties.
3894 map->pre_allocated_property_fields() +
3895 map->unused_property_fields() -
3896 map->inobject_properties();
3897 ASSERT(prop_size >= 0);
3899 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3900 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3903 // Allocate the JSObject.
3904 AllocationSpace space =
3905 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3906 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
3908 { MaybeObject* maybe_obj = Allocate(map, space);
3909 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3912 // Initialize the JSObject.
3913 InitializeJSObjectFromMap(JSObject::cast(obj),
3914 FixedArray::cast(properties),
3916 ASSERT(JSObject::cast(obj)->HasFastSmiOnlyElements() ||
3917 JSObject::cast(obj)->HasFastElements());
3922 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3923 PretenureFlag pretenure) {
3924 // Allocate the initial map if absent.
3925 if (!constructor->has_initial_map()) {
3926 Object* initial_map;
3927 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3928 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3930 constructor->set_initial_map(Map::cast(initial_map));
3931 Map::cast(initial_map)->set_constructor(constructor);
3933 // Allocate the object based on the constructors initial map.
3934 MaybeObject* result = AllocateJSObjectFromMap(
3935 constructor->initial_map(), pretenure);
3937 // Make sure result is NOT a global object if valid.
3938 Object* non_failure;
3939 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3945 MaybeObject* Heap::AllocateJSModule() {
3946 // Allocate a fresh map. Modules do not have a prototype.
3948 MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
3949 if (!maybe_map->To(&map)) return maybe_map;
3950 // Allocate the object based on the map.
3951 return AllocateJSObjectFromMap(map, TENURED);
3955 MaybeObject* Heap::AllocateJSArrayAndStorage(
3956 ElementsKind elements_kind,
3959 ArrayStorageAllocationMode mode,
3960 PretenureFlag pretenure) {
3961 ASSERT(capacity >= length);
3962 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3964 if (!maybe_array->To(&array)) return maybe_array;
3966 if (capacity == 0) {
3967 array->set_length(Smi::FromInt(0));
3968 array->set_elements(empty_fixed_array());
3972 FixedArrayBase* elms;
3973 MaybeObject* maybe_elms = NULL;
3974 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3975 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3976 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3978 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3979 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3982 ASSERT(elements_kind == FAST_ELEMENTS ||
3983 elements_kind == FAST_SMI_ONLY_ELEMENTS);
3984 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3985 maybe_elms = AllocateUninitializedFixedArray(capacity);
3987 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3988 maybe_elms = AllocateFixedArrayWithHoles(capacity);
3991 if (!maybe_elms->To(&elms)) return maybe_elms;
3993 array->set_elements(elms);
3994 array->set_length(Smi::FromInt(length));
3999 MaybeObject* Heap::AllocateJSArrayWithElements(
4000 FixedArrayBase* elements,
4001 ElementsKind elements_kind,
4002 PretenureFlag pretenure) {
4003 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4005 if (!maybe_array->To(&array)) return maybe_array;
4007 array->set_elements(elements);
4008 array->set_length(Smi::FromInt(elements->length()));
4013 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
4015 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4016 // maps. Will probably depend on the identity of the handler object, too.
4018 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
4019 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4020 map->set_prototype(prototype);
4022 // Allocate the proxy object.
4024 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4025 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
4026 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4027 result->set_handler(handler);
4028 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4033 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
4035 Object* construct_trap,
4036 Object* prototype) {
4038 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4039 // maps. Will probably depend on the identity of the handler object, too.
4041 MaybeObject* maybe_map_obj =
4042 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
4043 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4044 map->set_prototype(prototype);
4046 // Allocate the proxy object.
4047 JSFunctionProxy* result;
4048 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4049 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
4050 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4051 result->set_handler(handler);
4052 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4053 result->set_call_trap(call_trap);
4054 result->set_construct_trap(construct_trap);
4059 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
4060 ASSERT(constructor->has_initial_map());
4061 Map* map = constructor->initial_map();
4063 // Make sure no field properties are described in the initial map.
4064 // This guarantees us that normalizing the properties does not
4065 // require us to change property values to JSGlobalPropertyCells.
4066 ASSERT(map->NextFreePropertyIndex() == 0);
4068 // Make sure we don't have a ton of pre-allocated slots in the
4069 // global objects. They will be unused once we normalize the object.
4070 ASSERT(map->unused_property_fields() == 0);
4071 ASSERT(map->inobject_properties() == 0);
4073 // Initial size of the backing store to avoid resize of the storage during
4074 // bootstrapping. The size differs between the JS global object ad the
4076 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
4078 // Allocate a dictionary object for backing storage.
4080 { MaybeObject* maybe_obj =
4081 StringDictionary::Allocate(
4082 map->NumberOfDescribedProperties() * 2 + initial_size);
4083 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4085 StringDictionary* dictionary = StringDictionary::cast(obj);
4087 // The global object might be created from an object template with accessors.
4088 // Fill these accessors into the dictionary.
4089 DescriptorArray* descs = map->instance_descriptors();
4090 for (int i = 0; i < descs->number_of_descriptors(); i++) {
4091 PropertyDetails details = descs->GetDetails(i);
4092 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
4094 PropertyDetails(details.attributes(), CALLBACKS, details.index());
4095 Object* value = descs->GetCallbacksObject(i);
4096 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
4097 if (!maybe_value->ToObject(&value)) return maybe_value;
4101 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
4102 if (!maybe_result->ToObject(&result)) return maybe_result;
4104 dictionary = StringDictionary::cast(result);
4107 // Allocate the global object and initialize it with the backing store.
4108 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
4109 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4111 JSObject* global = JSObject::cast(obj);
4112 InitializeJSObjectFromMap(global, dictionary, map);
4114 // Create a new map for the global object.
4115 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
4116 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4118 Map* new_map = Map::cast(obj);
4120 // Set up the global object as a normalized object.
4121 global->set_map(new_map);
4122 global->map()->clear_instance_descriptors();
4123 global->set_properties(dictionary);
4125 // Make sure result is a global object with properties in dictionary.
4126 ASSERT(global->IsGlobalObject());
4127 ASSERT(!global->HasFastProperties());
4132 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4133 // Never used to copy functions. If functions need to be copied we
4134 // have to be careful to clear the literals array.
4135 SLOW_ASSERT(!source->IsJSFunction());
4138 Map* map = source->map();
4139 int object_size = map->instance_size();
4142 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4144 // If we're forced to always allocate, we use the general allocation
4145 // functions which may leave us with an object in old space.
4146 if (always_allocate()) {
4147 { MaybeObject* maybe_clone =
4148 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4149 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4151 Address clone_address = HeapObject::cast(clone)->address();
4152 CopyBlock(clone_address,
4155 // Update write barrier for all fields that lie beyond the header.
4156 RecordWrites(clone_address,
4157 JSObject::kHeaderSize,
4158 (object_size - JSObject::kHeaderSize) / kPointerSize);
4160 wb_mode = SKIP_WRITE_BARRIER;
4161 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4162 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4164 SLOW_ASSERT(InNewSpace(clone));
4165 // Since we know the clone is allocated in new space, we can copy
4166 // the contents without worrying about updating the write barrier.
4167 CopyBlock(HeapObject::cast(clone)->address(),
4173 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4174 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4175 FixedArray* properties = FixedArray::cast(source->properties());
4176 // Update elements if necessary.
4177 if (elements->length() > 0) {
4179 { MaybeObject* maybe_elem;
4180 if (elements->map() == fixed_cow_array_map()) {
4181 maybe_elem = FixedArray::cast(elements);
4182 } else if (source->HasFastDoubleElements()) {
4183 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4185 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4187 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4189 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4191 // Update properties if necessary.
4192 if (properties->length() > 0) {
4194 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4195 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4197 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4199 // Return the new clone.
4204 MaybeObject* Heap::ReinitializeJSReceiver(
4205 JSReceiver* object, InstanceType type, int size) {
4206 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4208 // Allocate fresh map.
4209 // TODO(rossberg): Once we optimize proxies, cache these maps.
4211 MaybeObject* maybe = AllocateMap(type, size);
4212 if (!maybe->To<Map>(&map)) return maybe;
4214 // Check that the receiver has at least the size of the fresh object.
4215 int size_difference = object->map()->instance_size() - map->instance_size();
4216 ASSERT(size_difference >= 0);
4218 map->set_prototype(object->map()->prototype());
4220 // Allocate the backing storage for the properties.
4221 int prop_size = map->unused_property_fields() - map->inobject_properties();
4223 maybe = AllocateFixedArray(prop_size, TENURED);
4224 if (!maybe->ToObject(&properties)) return maybe;
4226 // Functions require some allocation, which might fail here.
4227 SharedFunctionInfo* shared = NULL;
4228 if (type == JS_FUNCTION_TYPE) {
4230 maybe = LookupAsciiSymbol("<freezing call trap>");
4231 if (!maybe->To<String>(&name)) return maybe;
4232 maybe = AllocateSharedFunctionInfo(name);
4233 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4236 // Because of possible retries of this function after failure,
4237 // we must NOT fail after this point, where we have changed the type!
4239 // Reset the map for the object.
4240 object->set_map(map);
4241 JSObject* jsobj = JSObject::cast(object);
4243 // Reinitialize the object from the constructor map.
4244 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4246 // Functions require some minimal initialization.
4247 if (type == JS_FUNCTION_TYPE) {
4248 map->set_function_with_prototype(true);
4249 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4250 JSFunction::cast(object)->set_context(
4251 isolate()->context()->global_context());
4254 // Put in filler if the new object is smaller than the old.
4255 if (size_difference > 0) {
4256 CreateFillerObjectAt(
4257 object->address() + map->instance_size(), size_difference);
4264 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4265 JSGlobalProxy* object) {
4266 ASSERT(constructor->has_initial_map());
4267 Map* map = constructor->initial_map();
4269 // Check that the already allocated object has the same size and type as
4270 // objects allocated using the constructor.
4271 ASSERT(map->instance_size() == object->map()->instance_size());
4272 ASSERT(map->instance_type() == object->map()->instance_type());
4274 // Allocate the backing storage for the properties.
4275 int prop_size = map->unused_property_fields() - map->inobject_properties();
4277 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4278 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4281 // Reset the map for the object.
4282 object->set_map(constructor->initial_map());
4284 // Reinitialize the object from the constructor map.
4285 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4290 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4291 PretenureFlag pretenure) {
4292 if (string.length() == 1) {
4293 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4296 { MaybeObject* maybe_result =
4297 AllocateRawAsciiString(string.length(), pretenure);
4298 if (!maybe_result->ToObject(&result)) return maybe_result;
4301 // Copy the characters into the new object.
4302 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4303 for (int i = 0; i < string.length(); i++) {
4304 string_result->SeqAsciiStringSet(i, string[i]);
4310 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4311 PretenureFlag pretenure) {
4312 // Count the number of characters in the UTF-8 string and check if
4313 // it is an ASCII string.
4314 Access<UnicodeCache::Utf8Decoder>
4315 decoder(isolate_->unicode_cache()->utf8_decoder());
4316 decoder->Reset(string.start(), string.length());
4318 while (decoder->has_more()) {
4319 uint32_t r = decoder->GetNext();
4320 if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4328 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4329 if (!maybe_result->ToObject(&result)) return maybe_result;
4332 // Convert and copy the characters into the new object.
4333 String* string_result = String::cast(result);
4334 decoder->Reset(string.start(), string.length());
4337 uint32_t r = decoder->GetNext();
4338 if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4339 string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4340 string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4342 string_result->Set(i++, r);
4349 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4350 PretenureFlag pretenure) {
4351 // Check if the string is an ASCII string.
4352 MaybeObject* maybe_result;
4353 if (String::IsAscii(string.start(), string.length())) {
4354 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4355 } else { // It's not an ASCII string.
4356 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4359 if (!maybe_result->ToObject(&result)) return maybe_result;
4361 // Copy the characters into the new object, which may be either ASCII or
4363 String* string_result = String::cast(result);
4364 for (int i = 0; i < string.length(); i++) {
4365 string_result->Set(i, string[i]);
4371 Map* Heap::SymbolMapForString(String* string) {
4372 // If the string is in new space it cannot be used as a symbol.
4373 if (InNewSpace(string)) return NULL;
4375 // Find the corresponding symbol map for strings.
4376 switch (string->map()->instance_type()) {
4377 case STRING_TYPE: return symbol_map();
4378 case ASCII_STRING_TYPE: return ascii_symbol_map();
4379 case CONS_STRING_TYPE: return cons_symbol_map();
4380 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4381 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4382 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4383 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4384 return external_symbol_with_ascii_data_map();
4385 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4386 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4387 return short_external_ascii_symbol_map();
4388 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4389 return short_external_symbol_with_ascii_data_map();
4390 default: return NULL; // No match found.
4395 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4397 uint32_t hash_field) {
4399 // Ensure the chars matches the number of characters in the buffer.
4400 ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4401 // Determine whether the string is ASCII.
4402 bool is_ascii = true;
4403 while (buffer->has_more()) {
4404 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4411 // Compute map and object size.
4416 if (chars > SeqAsciiString::kMaxLength) {
4417 return Failure::OutOfMemoryException();
4419 map = ascii_symbol_map();
4420 size = SeqAsciiString::SizeFor(chars);
4422 if (chars > SeqTwoByteString::kMaxLength) {
4423 return Failure::OutOfMemoryException();
4426 size = SeqTwoByteString::SizeFor(chars);
4431 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4432 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4433 : old_data_space_->AllocateRaw(size);
4434 if (!maybe_result->ToObject(&result)) return maybe_result;
4437 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4438 // Set length and hash fields of the allocated string.
4439 String* answer = String::cast(result);
4440 answer->set_length(chars);
4441 answer->set_hash_field(hash_field);
4442 SeqString::cast(answer)->set_symbol_id(0);
4444 ASSERT_EQ(size, answer->Size());
4446 // Fill in the characters.
4449 uint32_t character = buffer->GetNext();
4450 if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4451 answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4452 answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4454 answer->Set(i++, character);
4461 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4462 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4463 return Failure::OutOfMemoryException();
4466 int size = SeqAsciiString::SizeFor(length);
4467 ASSERT(size <= SeqAsciiString::kMaxSize);
4469 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4470 AllocationSpace retry_space = OLD_DATA_SPACE;
4472 if (space == NEW_SPACE) {
4473 if (size > kMaxObjectSizeInNewSpace) {
4474 // Allocate in large object space, retry space will be ignored.
4476 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4477 // Allocate in new space, retry in large object space.
4478 retry_space = LO_SPACE;
4480 } else if (space == OLD_DATA_SPACE &&
4481 size > Page::kMaxNonCodeHeapObjectSize) {
4485 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4486 if (!maybe_result->ToObject(&result)) return maybe_result;
4489 // Partially initialize the object.
4490 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4491 String::cast(result)->set_length(length);
4492 String::cast(result)->set_hash_field(String::kEmptyHashField);
4493 SeqString::cast(result)->set_symbol_id(0);
4494 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4499 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4500 PretenureFlag pretenure) {
4501 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4502 return Failure::OutOfMemoryException();
4504 int size = SeqTwoByteString::SizeFor(length);
4505 ASSERT(size <= SeqTwoByteString::kMaxSize);
4506 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4507 AllocationSpace retry_space = OLD_DATA_SPACE;
4509 if (space == NEW_SPACE) {
4510 if (size > kMaxObjectSizeInNewSpace) {
4511 // Allocate in large object space, retry space will be ignored.
4513 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4514 // Allocate in new space, retry in large object space.
4515 retry_space = LO_SPACE;
4517 } else if (space == OLD_DATA_SPACE &&
4518 size > Page::kMaxNonCodeHeapObjectSize) {
4522 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4523 if (!maybe_result->ToObject(&result)) return maybe_result;
4526 // Partially initialize the object.
4527 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4528 String::cast(result)->set_length(length);
4529 String::cast(result)->set_hash_field(String::kEmptyHashField);
4530 SeqString::cast(result)->set_symbol_id(0);
4531 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4536 MaybeObject* Heap::AllocateJSArray(
4537 ElementsKind elements_kind,
4538 PretenureFlag pretenure) {
4539 Context* global_context = isolate()->context()->global_context();
4540 JSFunction* array_function = global_context->array_function();
4541 Map* map = array_function->initial_map();
4542 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
4543 map = Map::cast(global_context->double_js_array_map());
4544 } else if (elements_kind == FAST_ELEMENTS || !FLAG_smi_only_arrays) {
4545 map = Map::cast(global_context->object_js_array_map());
4547 ASSERT(elements_kind == FAST_SMI_ONLY_ELEMENTS);
4548 ASSERT(map == global_context->smi_js_array_map());
4551 return AllocateJSObjectFromMap(map, pretenure);
4555 MaybeObject* Heap::AllocateEmptyFixedArray() {
4556 int size = FixedArray::SizeFor(0);
4558 { MaybeObject* maybe_result =
4559 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4560 if (!maybe_result->ToObject(&result)) return maybe_result;
4562 // Initialize the object.
4563 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4565 reinterpret_cast<FixedArray*>(result)->set_length(0);
4570 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4571 if (length < 0 || length > FixedArray::kMaxLength) {
4572 return Failure::OutOfMemoryException();
4575 // Use the general function if we're forced to always allocate.
4576 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4577 // Allocate the raw data for a fixed array.
4578 int size = FixedArray::SizeFor(length);
4579 return size <= kMaxObjectSizeInNewSpace
4580 ? new_space_.AllocateRaw(size)
4581 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4585 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4586 int len = src->length();
4588 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4589 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4591 if (InNewSpace(obj)) {
4592 HeapObject* dst = HeapObject::cast(obj);
4593 dst->set_map_no_write_barrier(map);
4594 CopyBlock(dst->address() + kPointerSize,
4595 src->address() + kPointerSize,
4596 FixedArray::SizeFor(len) - kPointerSize);
4599 HeapObject::cast(obj)->set_map_no_write_barrier(map);
4600 FixedArray* result = FixedArray::cast(obj);
4601 result->set_length(len);
4604 AssertNoAllocation no_gc;
4605 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4606 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4611 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4613 int len = src->length();
4615 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4616 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4618 HeapObject* dst = HeapObject::cast(obj);
4619 dst->set_map_no_write_barrier(map);
4621 dst->address() + FixedDoubleArray::kLengthOffset,
4622 src->address() + FixedDoubleArray::kLengthOffset,
4623 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4628 MaybeObject* Heap::AllocateFixedArray(int length) {
4629 ASSERT(length >= 0);
4630 if (length == 0) return empty_fixed_array();
4632 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4633 if (!maybe_result->ToObject(&result)) return maybe_result;
4635 // Initialize header.
4636 FixedArray* array = reinterpret_cast<FixedArray*>(result);
4637 array->set_map_no_write_barrier(fixed_array_map());
4638 array->set_length(length);
4640 ASSERT(!InNewSpace(undefined_value()));
4641 MemsetPointer(array->data_start(), undefined_value(), length);
4646 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4647 if (length < 0 || length > FixedArray::kMaxLength) {
4648 return Failure::OutOfMemoryException();
4651 AllocationSpace space =
4652 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4653 int size = FixedArray::SizeFor(length);
4654 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4655 // Too big for new space.
4657 } else if (space == OLD_POINTER_SPACE &&
4658 size > Page::kMaxNonCodeHeapObjectSize) {
4659 // Too big for old pointer space.
4663 AllocationSpace retry_space =
4664 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4666 return AllocateRaw(size, space, retry_space);
4670 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4673 PretenureFlag pretenure,
4675 ASSERT(length >= 0);
4676 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4677 if (length == 0) return heap->empty_fixed_array();
4679 ASSERT(!heap->InNewSpace(filler));
4681 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4682 if (!maybe_result->ToObject(&result)) return maybe_result;
4685 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4686 FixedArray* array = FixedArray::cast(result);
4687 array->set_length(length);
4688 MemsetPointer(array->data_start(), filler, length);
4693 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4694 return AllocateFixedArrayWithFiller(this,
4701 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4702 PretenureFlag pretenure) {
4703 return AllocateFixedArrayWithFiller(this,
4710 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4711 if (length == 0) return empty_fixed_array();
4714 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4715 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4718 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4720 FixedArray::cast(obj)->set_length(length);
4725 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4726 int size = FixedDoubleArray::SizeFor(0);
4728 { MaybeObject* maybe_result =
4729 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4730 if (!maybe_result->ToObject(&result)) return maybe_result;
4732 // Initialize the object.
4733 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4734 fixed_double_array_map());
4735 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4740 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4742 PretenureFlag pretenure) {
4743 if (length == 0) return empty_fixed_array();
4745 Object* elements_object;
4746 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4747 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4748 FixedDoubleArray* elements =
4749 reinterpret_cast<FixedDoubleArray*>(elements_object);
4751 elements->set_map_no_write_barrier(fixed_double_array_map());
4752 elements->set_length(length);
4757 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4759 PretenureFlag pretenure) {
4760 if (length == 0) return empty_fixed_array();
4762 Object* elements_object;
4763 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4764 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4765 FixedDoubleArray* elements =
4766 reinterpret_cast<FixedDoubleArray*>(elements_object);
4768 for (int i = 0; i < length; ++i) {
4769 elements->set_the_hole(i);
4772 elements->set_map_no_write_barrier(fixed_double_array_map());
4773 elements->set_length(length);
4778 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4779 PretenureFlag pretenure) {
4780 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4781 return Failure::OutOfMemoryException();
4784 AllocationSpace space =
4785 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4786 int size = FixedDoubleArray::SizeFor(length);
4788 #ifndef V8_HOST_ARCH_64_BIT
4789 size += kPointerSize;
4792 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4793 // Too big for new space.
4795 } else if (space == OLD_DATA_SPACE &&
4796 size > Page::kMaxNonCodeHeapObjectSize) {
4797 // Too big for old data space.
4801 AllocationSpace retry_space =
4802 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4805 { MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
4806 if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
4809 return EnsureDoubleAligned(this, object, size);
4813 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4815 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4816 if (!maybe_result->ToObject(&result)) return maybe_result;
4818 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4820 ASSERT(result->IsHashTable());
4825 MaybeObject* Heap::AllocateGlobalContext() {
4827 { MaybeObject* maybe_result =
4828 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4829 if (!maybe_result->ToObject(&result)) return maybe_result;
4831 Context* context = reinterpret_cast<Context*>(result);
4832 context->set_map_no_write_barrier(global_context_map());
4833 context->set_smi_js_array_map(undefined_value());
4834 context->set_double_js_array_map(undefined_value());
4835 context->set_object_js_array_map(undefined_value());
4836 ASSERT(context->IsGlobalContext());
4837 ASSERT(result->IsContext());
4842 MaybeObject* Heap::AllocateModuleContext(Context* previous,
4843 ScopeInfo* scope_info) {
4845 { MaybeObject* maybe_result =
4846 AllocateFixedArrayWithHoles(scope_info->ContextLength(), TENURED);
4847 if (!maybe_result->ToObject(&result)) return maybe_result;
4849 Context* context = reinterpret_cast<Context*>(result);
4850 context->set_map_no_write_barrier(module_context_map());
4851 context->set_previous(previous);
4852 context->set_extension(scope_info);
4853 context->set_global(previous->global());
4858 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4859 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4861 { MaybeObject* maybe_result = AllocateFixedArray(length);
4862 if (!maybe_result->ToObject(&result)) return maybe_result;
4864 Context* context = reinterpret_cast<Context*>(result);
4865 context->set_map_no_write_barrier(function_context_map());
4866 context->set_closure(function);
4867 context->set_previous(function->context());
4868 context->set_extension(NULL);
4869 context->set_global(function->context()->global());
4870 context->set_qml_global(function->context()->qml_global());
4875 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4878 Object* thrown_object) {
4879 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4881 { MaybeObject* maybe_result =
4882 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4883 if (!maybe_result->ToObject(&result)) return maybe_result;
4885 Context* context = reinterpret_cast<Context*>(result);
4886 context->set_map_no_write_barrier(catch_context_map());
4887 context->set_closure(function);
4888 context->set_previous(previous);
4889 context->set_extension(name);
4890 context->set_global(previous->global());
4891 context->set_qml_global(previous->qml_global());
4892 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4897 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4899 JSObject* extension) {
4901 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4902 if (!maybe_result->ToObject(&result)) return maybe_result;
4904 Context* context = reinterpret_cast<Context*>(result);
4905 context->set_map_no_write_barrier(with_context_map());
4906 context->set_closure(function);
4907 context->set_previous(previous);
4908 context->set_extension(extension);
4909 context->set_global(previous->global());
4910 context->set_qml_global(previous->qml_global());
4915 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4917 ScopeInfo* scope_info) {
4919 { MaybeObject* maybe_result =
4920 AllocateFixedArrayWithHoles(scope_info->ContextLength());
4921 if (!maybe_result->ToObject(&result)) return maybe_result;
4923 Context* context = reinterpret_cast<Context*>(result);
4924 context->set_map_no_write_barrier(block_context_map());
4925 context->set_closure(function);
4926 context->set_previous(previous);
4927 context->set_extension(scope_info);
4928 context->set_global(previous->global());
4929 context->set_qml_global(previous->qml_global());
4934 MaybeObject* Heap::AllocateScopeInfo(int length) {
4935 FixedArray* scope_info;
4936 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4937 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4938 scope_info->set_map_no_write_barrier(scope_info_map());
4943 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4946 #define MAKE_CASE(NAME, Name, name) \
4947 case NAME##_TYPE: map = name##_map(); break;
4948 STRUCT_LIST(MAKE_CASE)
4952 return Failure::InternalError();
4954 int size = map->instance_size();
4955 AllocationSpace space =
4956 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
4958 { MaybeObject* maybe_result = Allocate(map, space);
4959 if (!maybe_result->ToObject(&result)) return maybe_result;
4961 Struct::cast(result)->InitializeBody(size);
4966 bool Heap::IsHeapIterable() {
4967 return (!old_pointer_space()->was_swept_conservatively() &&
4968 !old_data_space()->was_swept_conservatively());
4972 void Heap::EnsureHeapIsIterable() {
4973 ASSERT(IsAllocationAllowed());
4974 if (!IsHeapIterable()) {
4975 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
4977 ASSERT(IsHeapIterable());
4981 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
4982 incremental_marking()->Step(step_size,
4983 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
4985 if (incremental_marking()->IsComplete()) {
4986 bool uncommit = false;
4987 if (gc_count_at_last_idle_gc_ == gc_count_) {
4988 // No GC since the last full GC, the mutator is probably not active.
4989 isolate_->compilation_cache()->Clear();
4992 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4993 gc_count_at_last_idle_gc_ = gc_count_;
4995 new_space_.Shrink();
4996 UncommitFromSpace();
5002 bool Heap::IdleNotification(int hint) {
5003 const int kMaxHint = 1000;
5004 intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
5005 // The size factor is in range [5..250]. The numbers here are chosen from
5006 // experiments. If you changes them, make sure to test with
5007 // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
5008 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
5010 if (contexts_disposed_ > 0) {
5011 if (hint >= kMaxHint) {
5012 // The embedder is requesting a lot of GC work after context disposal,
5013 // we age inline caches so that they don't keep objects from
5014 // the old context alive.
5017 int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
5018 if (hint >= mark_sweep_time && !FLAG_expose_gc &&
5019 incremental_marking()->IsStopped()) {
5020 HistogramTimerScope scope(isolate_->counters()->gc_context());
5021 CollectAllGarbage(kReduceMemoryFootprintMask,
5022 "idle notification: contexts disposed");
5024 AdvanceIdleIncrementalMarking(step_size);
5025 contexts_disposed_ = 0;
5027 // Make sure that we have no pending context disposals.
5028 // Take into account that we might have decided to delay full collection
5029 // because incremental marking is in progress.
5030 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
5031 // After context disposal there is likely a lot of garbage remaining, reset
5032 // the idle notification counters in order to trigger more incremental GCs
5033 // on subsequent idle notifications.
5038 if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
5039 return IdleGlobalGC();
5042 // By doing small chunks of GC work in each IdleNotification,
5043 // perform a round of incremental GCs and after that wait until
5044 // the mutator creates enough garbage to justify a new round.
5045 // An incremental GC progresses as follows:
5046 // 1. many incremental marking steps,
5047 // 2. one old space mark-sweep-compact,
5048 // 3. many lazy sweep steps.
5049 // Use mark-sweep-compact events to count incremental GCs in a round.
5052 if (incremental_marking()->IsStopped()) {
5053 if (!IsSweepingComplete() &&
5054 !AdvanceSweepers(static_cast<int>(step_size))) {
5059 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5060 if (EnoughGarbageSinceLastIdleRound()) {
5067 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
5068 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
5069 ms_count_at_last_idle_notification_ = ms_count_;
5071 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5076 if (incremental_marking()->IsStopped()) {
5077 incremental_marking()->Start();
5080 AdvanceIdleIncrementalMarking(step_size);
5085 bool Heap::IdleGlobalGC() {
5086 static const int kIdlesBeforeScavenge = 4;
5087 static const int kIdlesBeforeMarkSweep = 7;
5088 static const int kIdlesBeforeMarkCompact = 8;
5089 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
5090 static const unsigned int kGCsBetweenCleanup = 4;
5092 if (!last_idle_notification_gc_count_init_) {
5093 last_idle_notification_gc_count_ = gc_count_;
5094 last_idle_notification_gc_count_init_ = true;
5097 bool uncommit = true;
5098 bool finished = false;
5100 // Reset the number of idle notifications received when a number of
5101 // GCs have taken place. This allows another round of cleanup based
5102 // on idle notifications if enough work has been carried out to
5103 // provoke a number of garbage collections.
5104 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
5105 number_idle_notifications_ =
5106 Min(number_idle_notifications_ + 1, kMaxIdleCount);
5108 number_idle_notifications_ = 0;
5109 last_idle_notification_gc_count_ = gc_count_;
5112 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
5113 CollectGarbage(NEW_SPACE, "idle notification");
5114 new_space_.Shrink();
5115 last_idle_notification_gc_count_ = gc_count_;
5116 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
5117 // Before doing the mark-sweep collections we clear the
5118 // compilation cache to avoid hanging on to source code and
5119 // generated code for cached functions.
5120 isolate_->compilation_cache()->Clear();
5122 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5123 new_space_.Shrink();
5124 last_idle_notification_gc_count_ = gc_count_;
5126 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
5127 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5128 new_space_.Shrink();
5129 last_idle_notification_gc_count_ = gc_count_;
5130 number_idle_notifications_ = 0;
5132 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
5133 // If we have received more than kIdlesBeforeMarkCompact idle
5134 // notifications we do not perform any cleanup because we don't
5135 // expect to gain much by doing so.
5139 if (uncommit) UncommitFromSpace();
5147 void Heap::Print() {
5148 if (!HasBeenSetUp()) return;
5149 isolate()->PrintStack();
5151 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
5156 void Heap::ReportCodeStatistics(const char* title) {
5157 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5158 PagedSpace::ResetCodeStatistics();
5159 // We do not look for code in new space, map space, or old space. If code
5160 // somehow ends up in those spaces, we would miss it here.
5161 code_space_->CollectCodeStatistics();
5162 lo_space_->CollectCodeStatistics();
5163 PagedSpace::ReportCodeStatistics();
5167 // This function expects that NewSpace's allocated objects histogram is
5168 // populated (via a call to CollectStatistics or else as a side effect of a
5169 // just-completed scavenge collection).
5170 void Heap::ReportHeapStatistics(const char* title) {
5172 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5174 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5175 old_gen_promotion_limit_);
5176 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5177 old_gen_allocation_limit_);
5178 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5181 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5182 isolate_->global_handles()->PrintStats();
5185 PrintF("Heap statistics : ");
5186 isolate_->memory_allocator()->ReportStatistics();
5187 PrintF("To space : ");
5188 new_space_.ReportStatistics();
5189 PrintF("Old pointer space : ");
5190 old_pointer_space_->ReportStatistics();
5191 PrintF("Old data space : ");
5192 old_data_space_->ReportStatistics();
5193 PrintF("Code space : ");
5194 code_space_->ReportStatistics();
5195 PrintF("Map space : ");
5196 map_space_->ReportStatistics();
5197 PrintF("Cell space : ");
5198 cell_space_->ReportStatistics();
5199 PrintF("Large object space : ");
5200 lo_space_->ReportStatistics();
5201 PrintF(">>>>>> ========================================= >>>>>>\n");
5206 bool Heap::Contains(HeapObject* value) {
5207 return Contains(value->address());
5211 bool Heap::Contains(Address addr) {
5212 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5213 return HasBeenSetUp() &&
5214 (new_space_.ToSpaceContains(addr) ||
5215 old_pointer_space_->Contains(addr) ||
5216 old_data_space_->Contains(addr) ||
5217 code_space_->Contains(addr) ||
5218 map_space_->Contains(addr) ||
5219 cell_space_->Contains(addr) ||
5220 lo_space_->SlowContains(addr));
5224 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5225 return InSpace(value->address(), space);
5229 bool Heap::InSpace(Address addr, AllocationSpace space) {
5230 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5231 if (!HasBeenSetUp()) return false;
5235 return new_space_.ToSpaceContains(addr);
5236 case OLD_POINTER_SPACE:
5237 return old_pointer_space_->Contains(addr);
5238 case OLD_DATA_SPACE:
5239 return old_data_space_->Contains(addr);
5241 return code_space_->Contains(addr);
5243 return map_space_->Contains(addr);
5245 return cell_space_->Contains(addr);
5247 return lo_space_->SlowContains(addr);
5255 void Heap::Verify() {
5256 ASSERT(HasBeenSetUp());
5258 store_buffer()->Verify();
5260 VerifyPointersVisitor visitor;
5261 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5263 new_space_.Verify();
5265 old_pointer_space_->Verify(&visitor);
5266 map_space_->Verify(&visitor);
5268 VerifyPointersVisitor no_dirty_regions_visitor;
5269 old_data_space_->Verify(&no_dirty_regions_visitor);
5270 code_space_->Verify(&no_dirty_regions_visitor);
5271 cell_space_->Verify(&no_dirty_regions_visitor);
5273 lo_space_->Verify();
5275 VerifyNoAccessorPairSharing();
5279 void Heap::VerifyNoAccessorPairSharing() {
5280 // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5281 // that we mark only unmarked pairs, then we clear all marks, restoring the
5282 // initial state. We use the Smi tag of the AccessorPair's getter as the
5283 // marking bit, because we can never see a Smi as the getter.
5284 for (int phase = 0; phase < 2; phase++) {
5285 HeapObjectIterator iter(map_space());
5286 for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5288 DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5289 for (int i = 0; i < descs->number_of_descriptors(); i++) {
5290 if (descs->GetType(i) == CALLBACKS &&
5291 descs->GetValue(i)->IsAccessorPair()) {
5292 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5293 uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5294 uintptr_t after = (phase == 0) ?
5295 ((before & ~kSmiTagMask) | kSmiTag) :
5296 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5297 CHECK(before != after);
5298 accessors->set_getter(reinterpret_cast<Object*>(after));
5308 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5309 Object* symbol = NULL;
5311 { MaybeObject* maybe_new_table =
5312 symbol_table()->LookupSymbol(string, &symbol);
5313 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5315 // Can't use set_symbol_table because SymbolTable::cast knows that
5316 // SymbolTable is a singleton and checks for identity.
5317 roots_[kSymbolTableRootIndex] = new_table;
5318 ASSERT(symbol != NULL);
5323 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5324 Object* symbol = NULL;
5326 { MaybeObject* maybe_new_table =
5327 symbol_table()->LookupAsciiSymbol(string, &symbol);
5328 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5330 // Can't use set_symbol_table because SymbolTable::cast knows that
5331 // SymbolTable is a singleton and checks for identity.
5332 roots_[kSymbolTableRootIndex] = new_table;
5333 ASSERT(symbol != NULL);
5338 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5341 Object* symbol = NULL;
5343 { MaybeObject* maybe_new_table =
5344 symbol_table()->LookupSubStringAsciiSymbol(string,
5348 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5350 // Can't use set_symbol_table because SymbolTable::cast knows that
5351 // SymbolTable is a singleton and checks for identity.
5352 roots_[kSymbolTableRootIndex] = new_table;
5353 ASSERT(symbol != NULL);
5358 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5359 Object* symbol = NULL;
5361 { MaybeObject* maybe_new_table =
5362 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5363 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5365 // Can't use set_symbol_table because SymbolTable::cast knows that
5366 // SymbolTable is a singleton and checks for identity.
5367 roots_[kSymbolTableRootIndex] = new_table;
5368 ASSERT(symbol != NULL);
5373 MaybeObject* Heap::LookupSymbol(String* string) {
5374 if (string->IsSymbol()) return string;
5375 Object* symbol = NULL;
5377 { MaybeObject* maybe_new_table =
5378 symbol_table()->LookupString(string, &symbol);
5379 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5381 // Can't use set_symbol_table because SymbolTable::cast knows that
5382 // SymbolTable is a singleton and checks for identity.
5383 roots_[kSymbolTableRootIndex] = new_table;
5384 ASSERT(symbol != NULL);
5389 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5390 if (string->IsSymbol()) {
5394 return symbol_table()->LookupSymbolIfExists(string, symbol);
5399 void Heap::ZapFromSpace() {
5400 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5401 new_space_.FromSpaceEnd());
5402 while (it.has_next()) {
5403 NewSpacePage* page = it.next();
5404 for (Address cursor = page->area_start(), limit = page->area_end();
5406 cursor += kPointerSize) {
5407 Memory::Address_at(cursor) = kFromSpaceZapValue;
5414 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5416 ObjectSlotCallback callback) {
5417 Address slot_address = start;
5419 // We are not collecting slots on new space objects during mutation
5420 // thus we have to scan for pointers to evacuation candidates when we
5421 // promote objects. But we should not record any slots in non-black
5422 // objects. Grey object's slots would be rescanned.
5423 // White object might not survive until the end of collection
5424 // it would be a violation of the invariant to record it's slots.
5425 bool record_slots = false;
5426 if (incremental_marking()->IsCompacting()) {
5427 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5428 record_slots = Marking::IsBlack(mark_bit);
5431 while (slot_address < end) {
5432 Object** slot = reinterpret_cast<Object**>(slot_address);
5433 Object* object = *slot;
5434 // If the store buffer becomes overfull we mark pages as being exempt from
5435 // the store buffer. These pages are scanned to find pointers that point
5436 // to the new space. In that case we may hit newly promoted objects and
5437 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5438 if (object->IsHeapObject()) {
5439 if (Heap::InFromSpace(object)) {
5440 callback(reinterpret_cast<HeapObject**>(slot),
5441 HeapObject::cast(object));
5442 Object* new_object = *slot;
5443 if (InNewSpace(new_object)) {
5444 SLOW_ASSERT(Heap::InToSpace(new_object));
5445 SLOW_ASSERT(new_object->IsHeapObject());
5446 store_buffer_.EnterDirectlyIntoStoreBuffer(
5447 reinterpret_cast<Address>(slot));
5449 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5450 } else if (record_slots &&
5451 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5452 mark_compact_collector()->RecordSlot(slot, slot, object);
5455 slot_address += kPointerSize;
5461 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5464 bool IsAMapPointerAddress(Object** addr) {
5465 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5466 int mod = a % Map::kSize;
5467 return mod >= Map::kPointerFieldsBeginOffset &&
5468 mod < Map::kPointerFieldsEndOffset;
5472 bool EverythingsAPointer(Object** addr) {
5477 static void CheckStoreBuffer(Heap* heap,
5480 Object**** store_buffer_position,
5481 Object*** store_buffer_top,
5482 CheckStoreBufferFilter filter,
5483 Address special_garbage_start,
5484 Address special_garbage_end) {
5485 Map* free_space_map = heap->free_space_map();
5486 for ( ; current < limit; current++) {
5487 Object* o = *current;
5488 Address current_address = reinterpret_cast<Address>(current);
5490 if (o == free_space_map) {
5491 Address current_address = reinterpret_cast<Address>(current);
5492 FreeSpace* free_space =
5493 FreeSpace::cast(HeapObject::FromAddress(current_address));
5494 int skip = free_space->Size();
5495 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5497 current_address += skip - kPointerSize;
5498 current = reinterpret_cast<Object**>(current_address);
5501 // Skip the current linear allocation space between top and limit which is
5502 // unmarked with the free space map, but can contain junk.
5503 if (current_address == special_garbage_start &&
5504 special_garbage_end != special_garbage_start) {
5505 current_address = special_garbage_end - kPointerSize;
5506 current = reinterpret_cast<Object**>(current_address);
5509 if (!(*filter)(current)) continue;
5510 ASSERT(current_address < special_garbage_start ||
5511 current_address >= special_garbage_end);
5512 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5513 // We have to check that the pointer does not point into new space
5514 // without trying to cast it to a heap object since the hash field of
5515 // a string can contain values like 1 and 3 which are tagged null
5517 if (!heap->InNewSpace(o)) continue;
5518 while (**store_buffer_position < current &&
5519 *store_buffer_position < store_buffer_top) {
5520 (*store_buffer_position)++;
5522 if (**store_buffer_position != current ||
5523 *store_buffer_position == store_buffer_top) {
5524 Object** obj_start = current;
5525 while (!(*obj_start)->IsMap()) obj_start--;
5532 // Check that the store buffer contains all intergenerational pointers by
5533 // scanning a page and ensuring that all pointers to young space are in the
5535 void Heap::OldPointerSpaceCheckStoreBuffer() {
5536 OldSpace* space = old_pointer_space();
5537 PageIterator pages(space);
5539 store_buffer()->SortUniq();
5541 while (pages.has_next()) {
5542 Page* page = pages.next();
5543 Object** current = reinterpret_cast<Object**>(page->area_start());
5545 Address end = page->area_end();
5547 Object*** store_buffer_position = store_buffer()->Start();
5548 Object*** store_buffer_top = store_buffer()->Top();
5550 Object** limit = reinterpret_cast<Object**>(end);
5551 CheckStoreBuffer(this,
5554 &store_buffer_position,
5556 &EverythingsAPointer,
5563 void Heap::MapSpaceCheckStoreBuffer() {
5564 MapSpace* space = map_space();
5565 PageIterator pages(space);
5567 store_buffer()->SortUniq();
5569 while (pages.has_next()) {
5570 Page* page = pages.next();
5571 Object** current = reinterpret_cast<Object**>(page->area_start());
5573 Address end = page->area_end();
5575 Object*** store_buffer_position = store_buffer()->Start();
5576 Object*** store_buffer_top = store_buffer()->Top();
5578 Object** limit = reinterpret_cast<Object**>(end);
5579 CheckStoreBuffer(this,
5582 &store_buffer_position,
5584 &IsAMapPointerAddress,
5591 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5592 LargeObjectIterator it(lo_space());
5593 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5594 // We only have code, sequential strings, or fixed arrays in large
5595 // object space, and only fixed arrays can possibly contain pointers to
5596 // the young generation.
5597 if (object->IsFixedArray()) {
5598 Object*** store_buffer_position = store_buffer()->Start();
5599 Object*** store_buffer_top = store_buffer()->Top();
5600 Object** current = reinterpret_cast<Object**>(object->address());
5602 reinterpret_cast<Object**>(object->address() + object->Size());
5603 CheckStoreBuffer(this,
5606 &store_buffer_position,
5608 &EverythingsAPointer,
5617 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5618 IterateStrongRoots(v, mode);
5619 IterateWeakRoots(v, mode);
5623 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5624 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5625 v->Synchronize(VisitorSynchronization::kSymbolTable);
5626 if (mode != VISIT_ALL_IN_SCAVENGE &&
5627 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5628 // Scavenge collections have special processing for this.
5629 external_string_table_.Iterate(v);
5631 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5635 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5636 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5637 v->Synchronize(VisitorSynchronization::kStrongRootList);
5639 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5640 v->Synchronize(VisitorSynchronization::kSymbol);
5642 isolate_->bootstrapper()->Iterate(v);
5643 v->Synchronize(VisitorSynchronization::kBootstrapper);
5644 isolate_->Iterate(v);
5645 v->Synchronize(VisitorSynchronization::kTop);
5646 Relocatable::Iterate(v);
5647 v->Synchronize(VisitorSynchronization::kRelocatable);
5649 #ifdef ENABLE_DEBUGGER_SUPPORT
5650 isolate_->debug()->Iterate(v);
5651 if (isolate_->deoptimizer_data() != NULL) {
5652 isolate_->deoptimizer_data()->Iterate(v);
5655 v->Synchronize(VisitorSynchronization::kDebug);
5656 isolate_->compilation_cache()->Iterate(v);
5657 v->Synchronize(VisitorSynchronization::kCompilationCache);
5659 // Iterate over local handles in handle scopes.
5660 isolate_->handle_scope_implementer()->Iterate(v);
5661 v->Synchronize(VisitorSynchronization::kHandleScope);
5663 // Iterate over the builtin code objects and code stubs in the
5664 // heap. Note that it is not necessary to iterate over code objects
5665 // on scavenge collections.
5666 if (mode != VISIT_ALL_IN_SCAVENGE) {
5667 isolate_->builtins()->IterateBuiltins(v);
5669 v->Synchronize(VisitorSynchronization::kBuiltins);
5671 // Iterate over global handles.
5673 case VISIT_ONLY_STRONG:
5674 isolate_->global_handles()->IterateStrongRoots(v);
5676 case VISIT_ALL_IN_SCAVENGE:
5677 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5679 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5681 isolate_->global_handles()->IterateAllRoots(v);
5684 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5686 // Iterate over pointers being held by inactive threads.
5687 isolate_->thread_manager()->Iterate(v);
5688 v->Synchronize(VisitorSynchronization::kThreadManager);
5690 // Iterate over the pointers the Serialization/Deserialization code is
5692 // During garbage collection this keeps the partial snapshot cache alive.
5693 // During deserialization of the startup snapshot this creates the partial
5694 // snapshot cache and deserializes the objects it refers to. During
5695 // serialization this does nothing, since the partial snapshot cache is
5696 // empty. However the next thing we do is create the partial snapshot,
5697 // filling up the partial snapshot cache with objects it needs as we go.
5698 SerializerDeserializer::Iterate(v);
5699 // We don't do a v->Synchronize call here, because in debug mode that will
5700 // output a flag to the snapshot. However at this point the serializer and
5701 // deserializer are deliberately a little unsynchronized (see above) so the
5702 // checking of the sync flag in the snapshot would fail.
5706 // TODO(1236194): Since the heap size is configurable on the command line
5707 // and through the API, we should gracefully handle the case that the heap
5708 // size is not big enough to fit all the initial objects.
5709 bool Heap::ConfigureHeap(int max_semispace_size,
5710 intptr_t max_old_gen_size,
5711 intptr_t max_executable_size) {
5712 if (HasBeenSetUp()) return false;
5714 if (FLAG_stress_compaction) {
5715 // This will cause more frequent GCs when stressing.
5716 max_semispace_size_ = Page::kPageSize;
5719 if (max_semispace_size > 0) {
5720 if (max_semispace_size < Page::kPageSize) {
5721 max_semispace_size = Page::kPageSize;
5722 if (FLAG_trace_gc) {
5723 PrintF("Max semispace size cannot be less than %dkbytes\n",
5724 Page::kPageSize >> 10);
5727 max_semispace_size_ = max_semispace_size;
5730 if (Snapshot::IsEnabled()) {
5731 // If we are using a snapshot we always reserve the default amount
5732 // of memory for each semispace because code in the snapshot has
5733 // write-barrier code that relies on the size and alignment of new
5734 // space. We therefore cannot use a larger max semispace size
5735 // than the default reserved semispace size.
5736 if (max_semispace_size_ > reserved_semispace_size_) {
5737 max_semispace_size_ = reserved_semispace_size_;
5738 if (FLAG_trace_gc) {
5739 PrintF("Max semispace size cannot be more than %dkbytes\n",
5740 reserved_semispace_size_ >> 10);
5744 // If we are not using snapshots we reserve space for the actual
5745 // max semispace size.
5746 reserved_semispace_size_ = max_semispace_size_;
5749 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5750 if (max_executable_size > 0) {
5751 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5754 // The max executable size must be less than or equal to the max old
5756 if (max_executable_size_ > max_old_generation_size_) {
5757 max_executable_size_ = max_old_generation_size_;
5760 // The new space size must be a power of two to support single-bit testing
5762 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5763 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5764 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5765 external_allocation_limit_ = 10 * max_semispace_size_;
5767 // The old generation is paged and needs at least one page for each space.
5768 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5769 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5771 RoundUp(max_old_generation_size_,
5779 bool Heap::ConfigureHeapDefault() {
5780 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5781 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5782 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5786 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5787 *stats->start_marker = HeapStats::kStartMarker;
5788 *stats->end_marker = HeapStats::kEndMarker;
5789 *stats->new_space_size = new_space_.SizeAsInt();
5790 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5791 *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5792 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5793 *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5794 *stats->old_data_space_capacity = old_data_space_->Capacity();
5795 *stats->code_space_size = code_space_->SizeOfObjects();
5796 *stats->code_space_capacity = code_space_->Capacity();
5797 *stats->map_space_size = map_space_->SizeOfObjects();
5798 *stats->map_space_capacity = map_space_->Capacity();
5799 *stats->cell_space_size = cell_space_->SizeOfObjects();
5800 *stats->cell_space_capacity = cell_space_->Capacity();
5801 *stats->lo_space_size = lo_space_->Size();
5802 isolate_->global_handles()->RecordStats(stats);
5803 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5804 *stats->memory_allocator_capacity =
5805 isolate()->memory_allocator()->Size() +
5806 isolate()->memory_allocator()->Available();
5807 *stats->os_error = OS::GetLastError();
5808 isolate()->memory_allocator()->Available();
5809 if (take_snapshot) {
5810 HeapIterator iterator;
5811 for (HeapObject* obj = iterator.next();
5813 obj = iterator.next()) {
5814 InstanceType type = obj->map()->instance_type();
5815 ASSERT(0 <= type && type <= LAST_TYPE);
5816 stats->objects_per_type[type]++;
5817 stats->size_per_type[type] += obj->Size();
5823 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5824 return old_pointer_space_->SizeOfObjects()
5825 + old_data_space_->SizeOfObjects()
5826 + code_space_->SizeOfObjects()
5827 + map_space_->SizeOfObjects()
5828 + cell_space_->SizeOfObjects()
5829 + lo_space_->SizeOfObjects();
5833 intptr_t Heap::PromotedExternalMemorySize() {
5834 if (amount_of_external_allocated_memory_
5835 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5836 return amount_of_external_allocated_memory_
5837 - amount_of_external_allocated_memory_at_last_global_gc_;
5842 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5843 static const int kMarkTag = 2;
5846 class HeapDebugUtils {
5848 explicit HeapDebugUtils(Heap* heap)
5849 : search_for_any_global_(false),
5850 search_target_(NULL),
5851 found_target_(false),
5856 class MarkObjectVisitor : public ObjectVisitor {
5858 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5860 void VisitPointers(Object** start, Object** end) {
5861 // Copy all HeapObject pointers in [start, end)
5862 for (Object** p = start; p < end; p++) {
5863 if ((*p)->IsHeapObject())
5864 utils_->MarkObjectRecursively(p);
5868 HeapDebugUtils* utils_;
5871 void MarkObjectRecursively(Object** p) {
5872 if (!(*p)->IsHeapObject()) return;
5874 HeapObject* obj = HeapObject::cast(*p);
5876 Object* map = obj->map();
5878 if (!map->IsHeapObject()) return; // visited before
5880 if (found_target_) return; // stop if target found
5881 object_stack_.Add(obj);
5882 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5883 (!search_for_any_global_ && (obj == search_target_))) {
5884 found_target_ = true;
5889 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5891 Address map_addr = map_p->address();
5893 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
5895 MarkObjectRecursively(&map);
5897 MarkObjectVisitor mark_visitor(this);
5899 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5902 if (!found_target_) // don't pop if found the target
5903 object_stack_.RemoveLast();
5907 class UnmarkObjectVisitor : public ObjectVisitor {
5909 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5911 void VisitPointers(Object** start, Object** end) {
5912 // Copy all HeapObject pointers in [start, end)
5913 for (Object** p = start; p < end; p++) {
5914 if ((*p)->IsHeapObject())
5915 utils_->UnmarkObjectRecursively(p);
5919 HeapDebugUtils* utils_;
5923 void UnmarkObjectRecursively(Object** p) {
5924 if (!(*p)->IsHeapObject()) return;
5926 HeapObject* obj = HeapObject::cast(*p);
5928 Object* map = obj->map();
5930 if (map->IsHeapObject()) return; // unmarked already
5932 Address map_addr = reinterpret_cast<Address>(map);
5934 map_addr -= kMarkTag;
5936 ASSERT_TAG_ALIGNED(map_addr);
5938 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5940 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
5942 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5944 UnmarkObjectVisitor unmark_visitor(this);
5946 obj->IterateBody(Map::cast(map_p)->instance_type(),
5947 obj->SizeFromMap(Map::cast(map_p)),
5952 void MarkRootObjectRecursively(Object** root) {
5953 if (search_for_any_global_) {
5954 ASSERT(search_target_ == NULL);
5956 ASSERT(search_target_->IsHeapObject());
5958 found_target_ = false;
5959 object_stack_.Clear();
5961 MarkObjectRecursively(root);
5962 UnmarkObjectRecursively(root);
5964 if (found_target_) {
5965 PrintF("=====================================\n");
5966 PrintF("==== Path to object ====\n");
5967 PrintF("=====================================\n\n");
5969 ASSERT(!object_stack_.is_empty());
5970 for (int i = 0; i < object_stack_.length(); i++) {
5971 if (i > 0) PrintF("\n |\n |\n V\n\n");
5972 Object* obj = object_stack_[i];
5975 PrintF("=====================================\n");
5979 // Helper class for visiting HeapObjects recursively.
5980 class MarkRootVisitor: public ObjectVisitor {
5982 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5984 void VisitPointers(Object** start, Object** end) {
5985 // Visit all HeapObject pointers in [start, end)
5986 for (Object** p = start; p < end; p++) {
5987 if ((*p)->IsHeapObject())
5988 utils_->MarkRootObjectRecursively(p);
5992 HeapDebugUtils* utils_;
5995 bool search_for_any_global_;
5996 Object* search_target_;
5998 List<Object*> object_stack_;
6007 V8_DECLARE_ONCE(initialize_gc_once);
6009 static void InitializeGCOnce() {
6010 InitializeScavengingVisitorsTables();
6011 NewSpaceScavenger::Initialize();
6012 MarkCompactCollector::Initialize();
6015 bool Heap::SetUp(bool create_heap_objects) {
6017 allocation_timeout_ = FLAG_gc_interval;
6018 debug_utils_ = new HeapDebugUtils(this);
6021 // Initialize heap spaces and initial maps and objects. Whenever something
6022 // goes wrong, just return false. The caller should check the results and
6023 // call Heap::TearDown() to release allocated memory.
6025 // If the heap is not yet configured (e.g. through the API), configure it.
6026 // Configuration is based on the flags new-space-size (really the semispace
6027 // size) and old-space-size if set or the initial values of semispace_size_
6028 // and old_generation_size_ otherwise.
6030 if (!ConfigureHeapDefault()) return false;
6033 CallOnce(&initialize_gc_once, &InitializeGCOnce);
6035 MarkMapPointersAsEncoded(false);
6037 // Set up memory allocator.
6038 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
6041 // Set up new space.
6042 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
6046 // Initialize old pointer space.
6047 old_pointer_space_ =
6049 max_old_generation_size_,
6052 if (old_pointer_space_ == NULL) return false;
6053 if (!old_pointer_space_->SetUp()) return false;
6055 // Initialize old data space.
6058 max_old_generation_size_,
6061 if (old_data_space_ == NULL) return false;
6062 if (!old_data_space_->SetUp()) return false;
6064 // Initialize the code space, set its maximum capacity to the old
6065 // generation size. It needs executable memory.
6066 // On 64-bit platform(s), we put all code objects in a 2 GB range of
6067 // virtual address space, so that they can call each other with near calls.
6068 if (code_range_size_ > 0) {
6069 if (!isolate_->code_range()->SetUp(code_range_size_)) {
6075 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
6076 if (code_space_ == NULL) return false;
6077 if (!code_space_->SetUp()) return false;
6079 // Initialize map space.
6080 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
6081 if (map_space_ == NULL) return false;
6082 if (!map_space_->SetUp()) return false;
6084 // Initialize global property cell space.
6085 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
6086 if (cell_space_ == NULL) return false;
6087 if (!cell_space_->SetUp()) return false;
6089 // The large object code space may contain code or data. We set the memory
6090 // to be non-executable here for safety, but this means we need to enable it
6091 // explicitly when allocating large code objects.
6092 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
6093 if (lo_space_ == NULL) return false;
6094 if (!lo_space_->SetUp()) return false;
6096 // Set up the seed that is used to randomize the string hash function.
6097 ASSERT(hash_seed() == 0);
6098 if (FLAG_randomize_hashes) {
6099 if (FLAG_hash_seed == 0) {
6101 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
6103 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
6107 if (create_heap_objects) {
6108 // Create initial maps.
6109 if (!CreateInitialMaps()) return false;
6110 if (!CreateApiObjects()) return false;
6112 // Create initial objects
6113 if (!CreateInitialObjects()) return false;
6115 global_contexts_list_ = undefined_value();
6118 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
6119 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
6121 store_buffer()->SetUp();
6127 void Heap::SetStackLimits() {
6128 ASSERT(isolate_ != NULL);
6129 ASSERT(isolate_ == isolate());
6130 // On 64 bit machines, pointers are generally out of range of Smis. We write
6131 // something that looks like an out of range Smi to the GC.
6133 // Set up the special root array entries containing the stack limits.
6134 // These are actually addresses, but the tag makes the GC ignore it.
6135 roots_[kStackLimitRootIndex] =
6136 reinterpret_cast<Object*>(
6137 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
6138 roots_[kRealStackLimitRootIndex] =
6139 reinterpret_cast<Object*>(
6140 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
6144 void Heap::TearDown() {
6146 if (FLAG_verify_heap) {
6150 if (FLAG_print_cumulative_gc_stat) {
6152 PrintF("gc_count=%d ", gc_count_);
6153 PrintF("mark_sweep_count=%d ", ms_count_);
6154 PrintF("max_gc_pause=%d ", get_max_gc_pause());
6155 PrintF("min_in_mutator=%d ", get_min_in_mutator());
6156 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
6157 get_max_alive_after_gc());
6161 isolate_->global_handles()->TearDown();
6163 external_string_table_.TearDown();
6165 new_space_.TearDown();
6167 if (old_pointer_space_ != NULL) {
6168 old_pointer_space_->TearDown();
6169 delete old_pointer_space_;
6170 old_pointer_space_ = NULL;
6173 if (old_data_space_ != NULL) {
6174 old_data_space_->TearDown();
6175 delete old_data_space_;
6176 old_data_space_ = NULL;
6179 if (code_space_ != NULL) {
6180 code_space_->TearDown();
6185 if (map_space_ != NULL) {
6186 map_space_->TearDown();
6191 if (cell_space_ != NULL) {
6192 cell_space_->TearDown();
6197 if (lo_space_ != NULL) {
6198 lo_space_->TearDown();
6203 store_buffer()->TearDown();
6204 incremental_marking()->TearDown();
6206 isolate_->memory_allocator()->TearDown();
6209 delete debug_utils_;
6210 debug_utils_ = NULL;
6215 void Heap::Shrink() {
6216 // Try to shrink all paged spaces.
6218 for (PagedSpace* space = spaces.next();
6220 space = spaces.next()) {
6221 space->ReleaseAllUnusedPages();
6226 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6227 ASSERT(callback != NULL);
6228 GCPrologueCallbackPair pair(callback, gc_type);
6229 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6230 return gc_prologue_callbacks_.Add(pair);
6234 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6235 ASSERT(callback != NULL);
6236 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6237 if (gc_prologue_callbacks_[i].callback == callback) {
6238 gc_prologue_callbacks_.Remove(i);
6246 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6247 ASSERT(callback != NULL);
6248 GCEpilogueCallbackPair pair(callback, gc_type);
6249 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6250 return gc_epilogue_callbacks_.Add(pair);
6254 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6255 ASSERT(callback != NULL);
6256 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6257 if (gc_epilogue_callbacks_[i].callback == callback) {
6258 gc_epilogue_callbacks_.Remove(i);
6268 class PrintHandleVisitor: public ObjectVisitor {
6270 void VisitPointers(Object** start, Object** end) {
6271 for (Object** p = start; p < end; p++)
6272 PrintF(" handle %p to %p\n",
6273 reinterpret_cast<void*>(p),
6274 reinterpret_cast<void*>(*p));
6278 void Heap::PrintHandles() {
6279 PrintF("Handles:\n");
6280 PrintHandleVisitor v;
6281 isolate_->handle_scope_implementer()->Iterate(&v);
6287 Space* AllSpaces::next() {
6288 switch (counter_++) {
6290 return HEAP->new_space();
6291 case OLD_POINTER_SPACE:
6292 return HEAP->old_pointer_space();
6293 case OLD_DATA_SPACE:
6294 return HEAP->old_data_space();
6296 return HEAP->code_space();
6298 return HEAP->map_space();
6300 return HEAP->cell_space();
6302 return HEAP->lo_space();
6309 PagedSpace* PagedSpaces::next() {
6310 switch (counter_++) {
6311 case OLD_POINTER_SPACE:
6312 return HEAP->old_pointer_space();
6313 case OLD_DATA_SPACE:
6314 return HEAP->old_data_space();
6316 return HEAP->code_space();
6318 return HEAP->map_space();
6320 return HEAP->cell_space();
6328 OldSpace* OldSpaces::next() {
6329 switch (counter_++) {
6330 case OLD_POINTER_SPACE:
6331 return HEAP->old_pointer_space();
6332 case OLD_DATA_SPACE:
6333 return HEAP->old_data_space();
6335 return HEAP->code_space();
6342 SpaceIterator::SpaceIterator()
6343 : current_space_(FIRST_SPACE),
6349 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6350 : current_space_(FIRST_SPACE),
6352 size_func_(size_func) {
6356 SpaceIterator::~SpaceIterator() {
6357 // Delete active iterator if any.
6362 bool SpaceIterator::has_next() {
6363 // Iterate until no more spaces.
6364 return current_space_ != LAST_SPACE;
6368 ObjectIterator* SpaceIterator::next() {
6369 if (iterator_ != NULL) {
6372 // Move to the next space
6374 if (current_space_ > LAST_SPACE) {
6379 // Return iterator for the new current space.
6380 return CreateIterator();
6384 // Create an iterator for the space to iterate.
6385 ObjectIterator* SpaceIterator::CreateIterator() {
6386 ASSERT(iterator_ == NULL);
6388 switch (current_space_) {
6390 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6392 case OLD_POINTER_SPACE:
6393 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6395 case OLD_DATA_SPACE:
6396 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6399 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6402 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6405 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6408 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6412 // Return the newly allocated iterator;
6413 ASSERT(iterator_ != NULL);
6418 class HeapObjectsFilter {
6420 virtual ~HeapObjectsFilter() {}
6421 virtual bool SkipObject(HeapObject* object) = 0;
6425 class UnreachableObjectsFilter : public HeapObjectsFilter {
6427 UnreachableObjectsFilter() {
6428 MarkReachableObjects();
6431 ~UnreachableObjectsFilter() {
6432 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6435 bool SkipObject(HeapObject* object) {
6436 MarkBit mark_bit = Marking::MarkBitFrom(object);
6437 return !mark_bit.Get();
6441 class MarkingVisitor : public ObjectVisitor {
6443 MarkingVisitor() : marking_stack_(10) {}
6445 void VisitPointers(Object** start, Object** end) {
6446 for (Object** p = start; p < end; p++) {
6447 if (!(*p)->IsHeapObject()) continue;
6448 HeapObject* obj = HeapObject::cast(*p);
6449 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6450 if (!mark_bit.Get()) {
6452 marking_stack_.Add(obj);
6457 void TransitiveClosure() {
6458 while (!marking_stack_.is_empty()) {
6459 HeapObject* obj = marking_stack_.RemoveLast();
6465 List<HeapObject*> marking_stack_;
6468 void MarkReachableObjects() {
6469 Heap* heap = Isolate::Current()->heap();
6470 MarkingVisitor visitor;
6471 heap->IterateRoots(&visitor, VISIT_ALL);
6472 visitor.TransitiveClosure();
6475 AssertNoAllocation no_alloc;
6479 HeapIterator::HeapIterator()
6480 : filtering_(HeapIterator::kNoFiltering),
6486 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6487 : filtering_(filtering),
6493 HeapIterator::~HeapIterator() {
6498 void HeapIterator::Init() {
6499 // Start the iteration.
6500 space_iterator_ = new SpaceIterator;
6501 switch (filtering_) {
6502 case kFilterUnreachable:
6503 filter_ = new UnreachableObjectsFilter;
6508 object_iterator_ = space_iterator_->next();
6512 void HeapIterator::Shutdown() {
6514 // Assert that in filtering mode we have iterated through all
6515 // objects. Otherwise, heap will be left in an inconsistent state.
6516 if (filtering_ != kNoFiltering) {
6517 ASSERT(object_iterator_ == NULL);
6520 // Make sure the last iterator is deallocated.
6521 delete space_iterator_;
6522 space_iterator_ = NULL;
6523 object_iterator_ = NULL;
6529 HeapObject* HeapIterator::next() {
6530 if (filter_ == NULL) return NextObject();
6532 HeapObject* obj = NextObject();
6533 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6538 HeapObject* HeapIterator::NextObject() {
6539 // No iterator means we are done.
6540 if (object_iterator_ == NULL) return NULL;
6542 if (HeapObject* obj = object_iterator_->next_object()) {
6543 // If the current iterator has more objects we are fine.
6546 // Go though the spaces looking for one that has objects.
6547 while (space_iterator_->has_next()) {
6548 object_iterator_ = space_iterator_->next();
6549 if (HeapObject* obj = object_iterator_->next_object()) {
6554 // Done with the last space.
6555 object_iterator_ = NULL;
6560 void HeapIterator::reset() {
6561 // Restart the iterator.
6567 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6569 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6571 class PathTracer::MarkVisitor: public ObjectVisitor {
6573 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6574 void VisitPointers(Object** start, Object** end) {
6575 // Scan all HeapObject pointers in [start, end)
6576 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6577 if ((*p)->IsHeapObject())
6578 tracer_->MarkRecursively(p, this);
6583 PathTracer* tracer_;
6587 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6589 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6590 void VisitPointers(Object** start, Object** end) {
6591 // Scan all HeapObject pointers in [start, end)
6592 for (Object** p = start; p < end; p++) {
6593 if ((*p)->IsHeapObject())
6594 tracer_->UnmarkRecursively(p, this);
6599 PathTracer* tracer_;
6603 void PathTracer::VisitPointers(Object** start, Object** end) {
6604 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6605 // Visit all HeapObject pointers in [start, end)
6606 for (Object** p = start; !done && (p < end); p++) {
6607 if ((*p)->IsHeapObject()) {
6609 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6615 void PathTracer::Reset() {
6616 found_target_ = false;
6617 object_stack_.Clear();
6621 void PathTracer::TracePathFrom(Object** root) {
6622 ASSERT((search_target_ == kAnyGlobalObject) ||
6623 search_target_->IsHeapObject());
6624 found_target_in_trace_ = false;
6625 object_stack_.Clear();
6627 MarkVisitor mark_visitor(this);
6628 MarkRecursively(root, &mark_visitor);
6630 UnmarkVisitor unmark_visitor(this);
6631 UnmarkRecursively(root, &unmark_visitor);
6637 static bool SafeIsGlobalContext(HeapObject* obj) {
6638 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6642 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6643 if (!(*p)->IsHeapObject()) return;
6645 HeapObject* obj = HeapObject::cast(*p);
6647 Object* map = obj->map();
6649 if (!map->IsHeapObject()) return; // visited before
6651 if (found_target_in_trace_) return; // stop if target found
6652 object_stack_.Add(obj);
6653 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6654 (obj == search_target_)) {
6655 found_target_in_trace_ = true;
6656 found_target_ = true;
6660 bool is_global_context = SafeIsGlobalContext(obj);
6663 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6665 Address map_addr = map_p->address();
6667 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6669 // Scan the object body.
6670 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6671 // This is specialized to scan Context's properly.
6672 Object** start = reinterpret_cast<Object**>(obj->address() +
6673 Context::kHeaderSize);
6674 Object** end = reinterpret_cast<Object**>(obj->address() +
6675 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6676 mark_visitor->VisitPointers(start, end);
6678 obj->IterateBody(map_p->instance_type(),
6679 obj->SizeFromMap(map_p),
6683 // Scan the map after the body because the body is a lot more interesting
6684 // when doing leak detection.
6685 MarkRecursively(&map, mark_visitor);
6687 if (!found_target_in_trace_) // don't pop if found the target
6688 object_stack_.RemoveLast();
6692 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6693 if (!(*p)->IsHeapObject()) return;
6695 HeapObject* obj = HeapObject::cast(*p);
6697 Object* map = obj->map();
6699 if (map->IsHeapObject()) return; // unmarked already
6701 Address map_addr = reinterpret_cast<Address>(map);
6703 map_addr -= kMarkTag;
6705 ASSERT_TAG_ALIGNED(map_addr);
6707 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6709 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6711 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6713 obj->IterateBody(Map::cast(map_p)->instance_type(),
6714 obj->SizeFromMap(Map::cast(map_p)),
6719 void PathTracer::ProcessResults() {
6720 if (found_target_) {
6721 PrintF("=====================================\n");
6722 PrintF("==== Path to object ====\n");
6723 PrintF("=====================================\n\n");
6725 ASSERT(!object_stack_.is_empty());
6726 for (int i = 0; i < object_stack_.length(); i++) {
6727 if (i > 0) PrintF("\n |\n |\n V\n\n");
6728 Object* obj = object_stack_[i];
6735 PrintF("=====================================\n");
6738 #endif // DEBUG || LIVE_OBJECT_LIST
6742 // Triggers a depth-first traversal of reachable objects from roots
6743 // and finds a path to a specific heap object and prints it.
6744 void Heap::TracePathToObject(Object* target) {
6745 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6746 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6750 // Triggers a depth-first traversal of reachable objects from roots
6751 // and finds a path to any global object and prints it. Useful for
6752 // determining the source for leaks of global objects.
6753 void Heap::TracePathToGlobal() {
6754 PathTracer tracer(PathTracer::kAnyGlobalObject,
6755 PathTracer::FIND_ALL,
6757 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6762 static intptr_t CountTotalHolesSize() {
6763 intptr_t holes_size = 0;
6765 for (OldSpace* space = spaces.next();
6767 space = spaces.next()) {
6768 holes_size += space->Waste() + space->Available();
6774 GCTracer::GCTracer(Heap* heap,
6775 const char* gc_reason,
6776 const char* collector_reason)
6778 start_object_size_(0),
6779 start_memory_size_(0),
6782 allocated_since_last_gc_(0),
6783 spent_in_mutator_(0),
6784 promoted_objects_size_(0),
6786 gc_reason_(gc_reason),
6787 collector_reason_(collector_reason) {
6788 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6789 start_time_ = OS::TimeCurrentMillis();
6790 start_object_size_ = heap_->SizeOfObjects();
6791 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6793 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6797 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6799 allocated_since_last_gc_ =
6800 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6802 if (heap_->last_gc_end_timestamp_ > 0) {
6803 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6806 steps_count_ = heap_->incremental_marking()->steps_count();
6807 steps_took_ = heap_->incremental_marking()->steps_took();
6808 longest_step_ = heap_->incremental_marking()->longest_step();
6809 steps_count_since_last_gc_ =
6810 heap_->incremental_marking()->steps_count_since_last_gc();
6811 steps_took_since_last_gc_ =
6812 heap_->incremental_marking()->steps_took_since_last_gc();
6816 GCTracer::~GCTracer() {
6817 // Printf ONE line iff flag is set.
6818 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6820 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6822 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6823 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6825 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6827 // Update cumulative GC statistics if required.
6828 if (FLAG_print_cumulative_gc_stat) {
6829 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6830 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6831 heap_->alive_after_last_gc_);
6833 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6834 static_cast<int>(spent_in_mutator_));
6838 PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6840 if (!FLAG_trace_gc_nvp) {
6841 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6843 double end_memory_size_mb =
6844 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6846 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6848 static_cast<double>(start_object_size_) / MB,
6849 static_cast<double>(start_memory_size_) / MB,
6850 SizeOfHeapObjects(),
6851 end_memory_size_mb);
6853 if (external_time > 0) PrintF("%d / ", external_time);
6854 PrintF("%d ms", time);
6855 if (steps_count_ > 0) {
6856 if (collector_ == SCAVENGER) {
6857 PrintF(" (+ %d ms in %d steps since last GC)",
6858 static_cast<int>(steps_took_since_last_gc_),
6859 steps_count_since_last_gc_);
6861 PrintF(" (+ %d ms in %d steps since start of marking, "
6862 "biggest step %f ms)",
6863 static_cast<int>(steps_took_),
6869 if (gc_reason_ != NULL) {
6870 PrintF(" [%s]", gc_reason_);
6873 if (collector_reason_ != NULL) {
6874 PrintF(" [%s]", collector_reason_);
6879 PrintF("pause=%d ", time);
6880 PrintF("mutator=%d ",
6881 static_cast<int>(spent_in_mutator_));
6884 switch (collector_) {
6888 case MARK_COMPACTOR:
6896 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6897 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6898 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6899 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6900 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6901 PrintF("new_new=%d ",
6902 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6903 PrintF("root_new=%d ",
6904 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6905 PrintF("old_new=%d ",
6906 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6907 PrintF("compaction_ptrs=%d ",
6908 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6909 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6910 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6911 PrintF("misc_compaction=%d ",
6912 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
6914 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
6915 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6916 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6917 in_free_list_or_wasted_before_gc_);
6918 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6920 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6921 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6923 if (collector_ == SCAVENGER) {
6924 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6925 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6927 PrintF("stepscount=%d ", steps_count_);
6928 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6934 heap_->PrintShortHeapStatistics();
6938 const char* GCTracer::CollectorString() {
6939 switch (collector_) {
6942 case MARK_COMPACTOR:
6943 return "Mark-sweep";
6945 return "Unknown GC";
6949 int KeyedLookupCache::Hash(Map* map, String* name) {
6950 // Uses only lower 32 bits if pointers are larger.
6951 uintptr_t addr_hash =
6952 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6953 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6957 int KeyedLookupCache::Lookup(Map* map, String* name) {
6958 int index = (Hash(map, name) & kHashMask);
6959 for (int i = 0; i < kEntriesPerBucket; i++) {
6960 Key& key = keys_[index + i];
6961 if ((key.map == map) && key.name->Equals(name)) {
6962 return field_offsets_[index + i];
6969 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
6971 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
6972 int index = (Hash(map, symbol) & kHashMask);
6973 // After a GC there will be free slots, so we use them in order (this may
6974 // help to get the most frequently used one in position 0).
6975 for (int i = 0; i< kEntriesPerBucket; i++) {
6976 Key& key = keys_[index];
6977 Object* free_entry_indicator = NULL;
6978 if (key.map == free_entry_indicator) {
6981 field_offsets_[index + i] = field_offset;
6985 // No free entry found in this bucket, so we move them all down one and
6986 // put the new entry at position zero.
6987 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6988 Key& key = keys_[index + i];
6989 Key& key2 = keys_[index + i - 1];
6991 field_offsets_[index + i] = field_offsets_[index + i - 1];
6994 // Write the new first entry.
6995 Key& key = keys_[index];
6998 field_offsets_[index] = field_offset;
7003 void KeyedLookupCache::Clear() {
7004 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
7008 void DescriptorLookupCache::Clear() {
7009 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
7014 void Heap::GarbageCollectionGreedyCheck() {
7015 ASSERT(FLAG_gc_greedy);
7016 if (isolate_->bootstrapper()->IsActive()) return;
7017 if (disallow_allocation_failure()) return;
7018 CollectGarbage(NEW_SPACE);
7023 TranscendentalCache::SubCache::SubCache(Type t)
7025 isolate_(Isolate::Current()) {
7026 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
7027 uint32_t in1 = 0xffffffffu; // generated by the FPU.
7028 for (int i = 0; i < kCacheSize; i++) {
7029 elements_[i].in[0] = in0;
7030 elements_[i].in[1] = in1;
7031 elements_[i].output = NULL;
7036 void TranscendentalCache::Clear() {
7037 for (int i = 0; i < kNumberOfCaches; i++) {
7038 if (caches_[i] != NULL) {
7046 void ExternalStringTable::CleanUp() {
7048 for (int i = 0; i < new_space_strings_.length(); ++i) {
7049 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7052 if (heap_->InNewSpace(new_space_strings_[i])) {
7053 new_space_strings_[last++] = new_space_strings_[i];
7055 old_space_strings_.Add(new_space_strings_[i]);
7058 new_space_strings_.Rewind(last);
7060 for (int i = 0; i < old_space_strings_.length(); ++i) {
7061 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7064 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
7065 old_space_strings_[last++] = old_space_strings_[i];
7067 old_space_strings_.Rewind(last);
7068 if (FLAG_verify_heap) {
7074 void ExternalStringTable::TearDown() {
7075 for (int i = 0; i < new_space_strings_.length(); ++i) {
7076 if (new_space_strings_[i] == heap_->raw_unchecked_null_value()) continue;
7077 HeapObject *object = HeapObject::cast(new_space_strings_[i]);
7078 if (!object->IsExternalString())
7079 heap_->FinalizeExternalString(object);
7081 for (int i = 0; i < old_space_strings_.length(); ++i) {
7082 if (old_space_strings_[i] == heap_->raw_unchecked_null_value()) continue;
7083 HeapObject *object = HeapObject::cast(old_space_strings_[i]);
7084 if (!object->IsExternalString())
7085 heap_->FinalizeExternalString(object);
7088 new_space_strings_.Free();
7089 old_space_strings_.Free();
7093 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
7094 chunk->set_next_chunk(chunks_queued_for_free_);
7095 chunks_queued_for_free_ = chunk;
7099 void Heap::FreeQueuedChunks() {
7100 if (chunks_queued_for_free_ == NULL) return;
7103 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7104 next = chunk->next_chunk();
7105 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7107 if (chunk->owner()->identity() == LO_SPACE) {
7108 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
7109 // If FromAnyPointerAddress encounters a slot that belongs to a large
7110 // chunk queued for deletion it will fail to find the chunk because
7111 // it try to perform a search in the list of pages owned by of the large
7112 // object space and queued chunks were detached from that list.
7113 // To work around this we split large chunk into normal kPageSize aligned
7114 // pieces and initialize size, owner and flags field of every piece.
7115 // If FromAnyPointerAddress encounters a slot that belongs to one of
7116 // these smaller pieces it will treat it as a slot on a normal Page.
7117 Address chunk_end = chunk->address() + chunk->size();
7118 MemoryChunk* inner = MemoryChunk::FromAddress(
7119 chunk->address() + Page::kPageSize);
7120 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
7121 while (inner <= inner_last) {
7122 // Size of a large chunk is always a multiple of
7123 // OS::AllocateAlignment() so there is always
7124 // enough space for a fake MemoryChunk header.
7125 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
7126 // Guard against overflow.
7127 if (area_end < inner->address()) area_end = chunk_end;
7128 inner->SetArea(inner->address(), area_end);
7129 inner->set_size(Page::kPageSize);
7130 inner->set_owner(lo_space());
7131 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7132 inner = MemoryChunk::FromAddress(
7133 inner->address() + Page::kPageSize);
7137 isolate_->heap()->store_buffer()->Compact();
7138 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
7139 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7140 next = chunk->next_chunk();
7141 isolate_->memory_allocator()->Free(chunk);
7143 chunks_queued_for_free_ = NULL;
7147 void Heap::RememberUnmappedPage(Address page, bool compacted) {
7148 uintptr_t p = reinterpret_cast<uintptr_t>(page);
7149 // Tag the page pointer to make it findable in the dump file.
7151 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
7153 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
7155 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
7156 reinterpret_cast<Address>(p);
7157 remembered_unmapped_pages_index_++;
7158 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
7161 } } // namespace v8::internal