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.
69 #if defined(V8_TARGET_ARCH_X64)
70 #define LUMP_OF_MEMORY (2 * MB)
71 code_range_size_(512*MB),
73 #define LUMP_OF_MEMORY MB
77 reserved_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
78 max_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
79 initial_semispace_size_(Page::kPageSize),
80 max_old_generation_size_(192*MB),
81 max_executable_size_(max_old_generation_size_),
83 reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
84 max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
85 initial_semispace_size_(Page::kPageSize),
86 max_old_generation_size_(700ul * LUMP_OF_MEMORY),
87 max_executable_size_(256l * LUMP_OF_MEMORY),
90 // Variables set based on semispace_size_ and old_generation_size_ in
91 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
92 // Will be 4 * reserved_semispace_size_ to ensure that young
93 // generation can be aligned to its size.
94 survived_since_last_expansion_(0),
96 always_allocate_scope_depth_(0),
97 linear_allocation_scope_depth_(0),
98 contexts_disposed_(0),
100 scan_on_scavenge_pages_(0),
102 old_pointer_space_(NULL),
103 old_data_space_(NULL),
108 gc_state_(NOT_IN_GC),
109 gc_post_processing_depth_(0),
112 remembered_unmapped_pages_index_(0),
113 unflattened_strings_length_(0),
115 allocation_allowed_(true),
116 allocation_timeout_(0),
117 disallow_allocation_failure_(false),
120 new_space_high_promotion_mode_active_(false),
121 old_gen_promotion_limit_(kMinimumPromotionLimit),
122 old_gen_allocation_limit_(kMinimumAllocationLimit),
123 old_gen_limit_factor_(1),
124 size_of_old_gen_at_last_old_space_gc_(0),
125 external_allocation_limit_(0),
126 amount_of_external_allocated_memory_(0),
127 amount_of_external_allocated_memory_at_last_global_gc_(0),
128 old_gen_exhausted_(false),
129 store_buffer_rebuilder_(store_buffer()),
130 hidden_symbol_(NULL),
131 global_gc_prologue_callback_(NULL),
132 global_gc_epilogue_callback_(NULL),
133 gc_safe_size_of_old_object_(NULL),
134 total_regexp_code_generated_(0),
136 young_survivors_after_last_gc_(0),
137 high_survival_rate_period_length_(0),
139 previous_survival_rate_trend_(Heap::STABLE),
140 survival_rate_trend_(Heap::STABLE),
142 max_alive_after_gc_(0),
143 min_in_mutator_(kMaxInt),
144 alive_after_last_gc_(0),
145 last_gc_end_timestamp_(0.0),
148 incremental_marking_(this),
149 number_idle_notifications_(0),
150 last_idle_notification_gc_count_(0),
151 last_idle_notification_gc_count_init_(false),
152 mark_sweeps_since_idle_round_started_(0),
153 ms_count_at_last_idle_notification_(0),
154 gc_count_at_last_idle_gc_(0),
155 scavenges_since_last_idle_round_(kIdleScavengeThreshold),
156 promotion_queue_(this),
158 chunks_queued_for_free_(NULL) {
159 // Allow build-time customization of the max semispace size. Building
160 // V8 with snapshots and a non-default max semispace size is much
161 // easier if you can define it as part of the build environment.
162 #if defined(V8_MAX_SEMISPACE_SIZE)
163 max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
166 intptr_t max_virtual = OS::MaxVirtualMemory();
168 if (max_virtual > 0) {
169 if (code_range_size_ > 0) {
170 // Reserve no more than 1/8 of the memory for the code range.
171 code_range_size_ = Min(code_range_size_, max_virtual >> 3);
175 memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
176 global_contexts_list_ = NULL;
177 mark_compact_collector_.heap_ = this;
178 external_string_table_.heap_ = this;
179 // Put a dummy entry in the remembered pages so we can find the list the
180 // minidump even if there are no real unmapped pages.
181 RememberUnmappedPage(NULL, false);
185 intptr_t Heap::Capacity() {
186 if (!HasBeenSetUp()) return 0;
188 return new_space_.Capacity() +
189 old_pointer_space_->Capacity() +
190 old_data_space_->Capacity() +
191 code_space_->Capacity() +
192 map_space_->Capacity() +
193 cell_space_->Capacity();
197 intptr_t Heap::CommittedMemory() {
198 if (!HasBeenSetUp()) return 0;
200 return new_space_.CommittedMemory() +
201 old_pointer_space_->CommittedMemory() +
202 old_data_space_->CommittedMemory() +
203 code_space_->CommittedMemory() +
204 map_space_->CommittedMemory() +
205 cell_space_->CommittedMemory() +
209 intptr_t Heap::CommittedMemoryExecutable() {
210 if (!HasBeenSetUp()) return 0;
212 return isolate()->memory_allocator()->SizeExecutable();
216 intptr_t Heap::Available() {
217 if (!HasBeenSetUp()) return 0;
219 return new_space_.Available() +
220 old_pointer_space_->Available() +
221 old_data_space_->Available() +
222 code_space_->Available() +
223 map_space_->Available() +
224 cell_space_->Available();
228 bool Heap::HasBeenSetUp() {
229 return old_pointer_space_ != NULL &&
230 old_data_space_ != NULL &&
231 code_space_ != NULL &&
232 map_space_ != NULL &&
233 cell_space_ != NULL &&
238 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
239 if (IntrusiveMarking::IsMarked(object)) {
240 return IntrusiveMarking::SizeOfMarkedObject(object);
242 return object->SizeFromMap(object->map());
246 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
247 const char** reason) {
248 // Is global GC requested?
249 if (space != NEW_SPACE) {
250 isolate_->counters()->gc_compactor_caused_by_request()->Increment();
251 *reason = "GC in old space requested";
252 return MARK_COMPACTOR;
255 if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
256 *reason = "GC in old space forced by flags";
257 return MARK_COMPACTOR;
260 // Is enough data promoted to justify a global GC?
261 if (OldGenerationPromotionLimitReached()) {
262 isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
263 *reason = "promotion limit reached";
264 return MARK_COMPACTOR;
267 // Have allocation in OLD and LO failed?
268 if (old_gen_exhausted_) {
269 isolate_->counters()->
270 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
271 *reason = "old generations exhausted";
272 return MARK_COMPACTOR;
275 // Is there enough space left in OLD to guarantee that a scavenge can
278 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
279 // for object promotion. It counts only the bytes that the memory
280 // allocator has not yet allocated from the OS and assigned to any space,
281 // and does not count available bytes already in the old space or code
282 // space. Undercounting is safe---we may get an unrequested full GC when
283 // a scavenge would have succeeded.
284 if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
285 isolate_->counters()->
286 gc_compactor_caused_by_oldspace_exhaustion()->Increment();
287 *reason = "scavenge might not succeed";
288 return MARK_COMPACTOR;
297 // TODO(1238405): Combine the infrastructure for --heap-stats and
298 // --log-gc to avoid the complicated preprocessor and flag testing.
299 void Heap::ReportStatisticsBeforeGC() {
300 // Heap::ReportHeapStatistics will also log NewSpace statistics when
301 // compiled --log-gc is set. The following logic is used to avoid
304 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
305 if (FLAG_heap_stats) {
306 ReportHeapStatistics("Before GC");
307 } else if (FLAG_log_gc) {
308 new_space_.ReportStatistics();
310 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
313 new_space_.CollectStatistics();
314 new_space_.ReportStatistics();
315 new_space_.ClearHistograms();
321 void Heap::PrintShortHeapStatistics() {
322 if (!FLAG_trace_gc_verbose) return;
323 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
324 ", available: %8" V8_PTR_PREFIX "d\n",
325 isolate_->memory_allocator()->Size(),
326 isolate_->memory_allocator()->Available());
327 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
328 ", available: %8" V8_PTR_PREFIX "d\n",
329 Heap::new_space_.Size(),
330 new_space_.Available());
331 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
332 ", available: %8" V8_PTR_PREFIX "d"
333 ", waste: %8" V8_PTR_PREFIX "d\n",
334 old_pointer_space_->Size(),
335 old_pointer_space_->Available(),
336 old_pointer_space_->Waste());
337 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
338 ", available: %8" V8_PTR_PREFIX "d"
339 ", waste: %8" V8_PTR_PREFIX "d\n",
340 old_data_space_->Size(),
341 old_data_space_->Available(),
342 old_data_space_->Waste());
343 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
344 ", available: %8" V8_PTR_PREFIX "d"
345 ", waste: %8" V8_PTR_PREFIX "d\n",
347 code_space_->Available(),
348 code_space_->Waste());
349 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
350 ", available: %8" V8_PTR_PREFIX "d"
351 ", waste: %8" V8_PTR_PREFIX "d\n",
353 map_space_->Available(),
354 map_space_->Waste());
355 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
356 ", available: %8" V8_PTR_PREFIX "d"
357 ", waste: %8" V8_PTR_PREFIX "d\n",
359 cell_space_->Available(),
360 cell_space_->Waste());
361 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
362 ", available: %8" V8_PTR_PREFIX "d\n",
364 lo_space_->Available());
368 // TODO(1238405): Combine the infrastructure for --heap-stats and
369 // --log-gc to avoid the complicated preprocessor and flag testing.
370 void Heap::ReportStatisticsAfterGC() {
371 // Similar to the before GC, we use some complicated logic to ensure that
372 // NewSpace statistics are logged exactly once when --log-gc is turned on.
374 if (FLAG_heap_stats) {
375 new_space_.CollectStatistics();
376 ReportHeapStatistics("After GC");
377 } else if (FLAG_log_gc) {
378 new_space_.ReportStatistics();
381 if (FLAG_log_gc) new_space_.ReportStatistics();
386 void Heap::GarbageCollectionPrologue() {
387 isolate_->transcendental_cache()->Clear();
388 ClearJSFunctionResultCaches();
390 unflattened_strings_length_ = 0;
392 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
393 allow_allocation(false);
395 if (FLAG_verify_heap) {
399 if (FLAG_gc_verbose) Print();
403 ReportStatisticsBeforeGC();
406 LiveObjectList::GCPrologue();
407 store_buffer()->GCPrologue();
410 intptr_t Heap::SizeOfObjects() {
413 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
414 total += space->SizeOfObjects();
419 void Heap::GarbageCollectionEpilogue() {
420 store_buffer()->GCEpilogue();
421 LiveObjectList::GCEpilogue();
423 allow_allocation(true);
426 if (FLAG_verify_heap) {
430 if (FLAG_print_global_handles) isolate_->global_handles()->Print();
431 if (FLAG_print_handles) PrintHandles();
432 if (FLAG_gc_verbose) Print();
433 if (FLAG_code_stats) ReportCodeStatistics("After GC");
436 isolate_->counters()->alive_after_last_gc()->Set(
437 static_cast<int>(SizeOfObjects()));
439 isolate_->counters()->symbol_table_capacity()->Set(
440 symbol_table()->Capacity());
441 isolate_->counters()->number_of_symbols()->Set(
442 symbol_table()->NumberOfElements());
444 ReportStatisticsAfterGC();
446 #ifdef ENABLE_DEBUGGER_SUPPORT
447 isolate_->debug()->AfterGarbageCollection();
448 #endif // ENABLE_DEBUGGER_SUPPORT
452 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
453 // Since we are ignoring the return value, the exact choice of space does
454 // not matter, so long as we do not specify NEW_SPACE, which would not
456 mark_compact_collector_.SetFlags(flags);
457 CollectGarbage(OLD_POINTER_SPACE, gc_reason);
458 mark_compact_collector_.SetFlags(kNoGCFlags);
462 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
463 // Since we are ignoring the return value, the exact choice of space does
464 // not matter, so long as we do not specify NEW_SPACE, which would not
466 // Major GC would invoke weak handle callbacks on weakly reachable
467 // handles, but won't collect weakly reachable objects until next
468 // major GC. Therefore if we collect aggressively and weak handle callback
469 // has been invoked, we rerun major GC to release objects which become
471 // Note: as weak callbacks can execute arbitrary code, we cannot
472 // hope that eventually there will be no weak callbacks invocations.
473 // Therefore stop recollecting after several attempts.
474 mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
475 kReduceMemoryFootprintMask);
476 isolate_->compilation_cache()->Clear();
477 const int kMaxNumberOfAttempts = 7;
478 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
479 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
483 mark_compact_collector()->SetFlags(kNoGCFlags);
487 incremental_marking()->UncommitMarkingDeque();
491 bool Heap::CollectGarbage(AllocationSpace space,
492 GarbageCollector collector,
493 const char* gc_reason,
494 const char* collector_reason) {
495 // The VM is in the GC state until exiting this function.
496 VMState state(isolate_, GC);
499 // Reset the allocation timeout to the GC interval, but make sure to
500 // allow at least a few allocations after a collection. The reason
501 // for this is that we have a lot of allocation sequences and we
502 // assume that a garbage collection will allow the subsequent
503 // allocation attempts to go through.
504 allocation_timeout_ = Max(6, FLAG_gc_interval);
507 if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
508 if (FLAG_trace_incremental_marking) {
509 PrintF("[IncrementalMarking] Scavenge during marking.\n");
513 if (collector == MARK_COMPACTOR &&
514 !mark_compact_collector()->abort_incremental_marking_ &&
515 !incremental_marking()->IsStopped() &&
516 !incremental_marking()->should_hurry() &&
517 FLAG_incremental_marking_steps) {
518 // Make progress in incremental marking.
519 const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
520 incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
521 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
522 if (!incremental_marking()->IsComplete()) {
523 if (FLAG_trace_incremental_marking) {
524 PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
526 collector = SCAVENGER;
527 collector_reason = "incremental marking delaying mark-sweep";
531 bool next_gc_likely_to_collect_more = false;
533 { GCTracer tracer(this, gc_reason, collector_reason);
534 GarbageCollectionPrologue();
535 // The GC count was incremented in the prologue. Tell the tracer about
537 tracer.set_gc_count(gc_count_);
539 // Tell the tracer which collector we've selected.
540 tracer.set_collector(collector);
542 HistogramTimer* rate = (collector == SCAVENGER)
543 ? isolate_->counters()->gc_scavenger()
544 : isolate_->counters()->gc_compactor();
546 next_gc_likely_to_collect_more =
547 PerformGarbageCollection(collector, &tracer);
550 GarbageCollectionEpilogue();
553 ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
554 if (incremental_marking()->IsStopped()) {
555 if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
556 incremental_marking()->Start();
560 return next_gc_likely_to_collect_more;
564 void Heap::PerformScavenge() {
565 GCTracer tracer(this, NULL, NULL);
566 if (incremental_marking()->IsStopped()) {
567 PerformGarbageCollection(SCAVENGER, &tracer);
569 PerformGarbageCollection(MARK_COMPACTOR, &tracer);
575 // Helper class for verifying the symbol table.
576 class SymbolTableVerifier : public ObjectVisitor {
578 void VisitPointers(Object** start, Object** end) {
579 // Visit all HeapObject pointers in [start, end).
580 for (Object** p = start; p < end; p++) {
581 if ((*p)->IsHeapObject()) {
582 // Check that the symbol is actually a symbol.
583 ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
591 static void VerifySymbolTable() {
593 SymbolTableVerifier verifier;
594 HEAP->symbol_table()->IterateElements(&verifier);
599 static bool AbortIncrementalMarkingAndCollectGarbage(
601 AllocationSpace space,
602 const char* gc_reason = NULL) {
603 heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
604 bool result = heap->CollectGarbage(space, gc_reason);
605 heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
610 void Heap::ReserveSpace(
612 int pointer_space_size,
617 int large_object_size) {
618 NewSpace* new_space = Heap::new_space();
619 PagedSpace* old_pointer_space = Heap::old_pointer_space();
620 PagedSpace* old_data_space = Heap::old_data_space();
621 PagedSpace* code_space = Heap::code_space();
622 PagedSpace* map_space = Heap::map_space();
623 PagedSpace* cell_space = Heap::cell_space();
624 LargeObjectSpace* lo_space = Heap::lo_space();
625 bool gc_performed = true;
627 static const int kThreshold = 20;
628 while (gc_performed && counter++ < kThreshold) {
629 gc_performed = false;
630 if (!new_space->ReserveSpace(new_space_size)) {
631 Heap::CollectGarbage(NEW_SPACE,
632 "failed to reserve space in the new space");
635 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
636 AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
637 "failed to reserve space in the old pointer space");
640 if (!(old_data_space->ReserveSpace(data_space_size))) {
641 AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
642 "failed to reserve space in the old data space");
645 if (!(code_space->ReserveSpace(code_space_size))) {
646 AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
647 "failed to reserve space in the code space");
650 if (!(map_space->ReserveSpace(map_space_size))) {
651 AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
652 "failed to reserve space in the map space");
655 if (!(cell_space->ReserveSpace(cell_space_size))) {
656 AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
657 "failed to reserve space in the cell space");
660 // We add a slack-factor of 2 in order to have space for a series of
661 // large-object allocations that are only just larger than the page size.
662 large_object_size *= 2;
663 // The ReserveSpace method on the large object space checks how much
664 // we can expand the old generation. This includes expansion caused by
665 // allocation in the other spaces.
666 large_object_size += cell_space_size + map_space_size + code_space_size +
667 data_space_size + pointer_space_size;
668 if (!(lo_space->ReserveSpace(large_object_size))) {
669 AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
670 "failed to reserve space in the large object space");
676 // Failed to reserve the space after several attempts.
677 V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
682 void Heap::EnsureFromSpaceIsCommitted() {
683 if (new_space_.CommitFromSpaceIfNeeded()) return;
685 // Committing memory to from space failed.
686 // Try shrinking and try again.
688 if (new_space_.CommitFromSpaceIfNeeded()) return;
690 // Committing memory to from space failed again.
691 // Memory is exhausted and we will die.
692 V8::FatalProcessOutOfMemory("Committing semi space failed.");
696 void Heap::ClearJSFunctionResultCaches() {
697 if (isolate_->bootstrapper()->IsActive()) return;
699 Object* context = global_contexts_list_;
700 while (!context->IsUndefined()) {
701 // Get the caches for this context. GC can happen when the context
702 // is not fully initialized, so the caches can be undefined.
703 Object* caches_or_undefined =
704 Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
705 if (!caches_or_undefined->IsUndefined()) {
706 FixedArray* caches = FixedArray::cast(caches_or_undefined);
708 int length = caches->length();
709 for (int i = 0; i < length; i++) {
710 JSFunctionResultCache::cast(caches->get(i))->Clear();
713 // Get the next context:
714 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
720 void Heap::ClearNormalizedMapCaches() {
721 if (isolate_->bootstrapper()->IsActive() &&
722 !incremental_marking()->IsMarking()) {
726 Object* context = global_contexts_list_;
727 while (!context->IsUndefined()) {
728 // GC can happen when the context is not fully initialized,
729 // so the cache can be undefined.
731 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
732 if (!cache->IsUndefined()) {
733 NormalizedMapCache::cast(cache)->Clear();
735 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
740 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
741 double survival_rate =
742 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
743 start_new_space_size;
745 if (survival_rate > kYoungSurvivalRateHighThreshold) {
746 high_survival_rate_period_length_++;
748 high_survival_rate_period_length_ = 0;
751 if (survival_rate < kYoungSurvivalRateLowThreshold) {
752 low_survival_rate_period_length_++;
754 low_survival_rate_period_length_ = 0;
757 double survival_rate_diff = survival_rate_ - survival_rate;
759 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
760 set_survival_rate_trend(DECREASING);
761 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
762 set_survival_rate_trend(INCREASING);
764 set_survival_rate_trend(STABLE);
767 survival_rate_ = survival_rate;
770 bool Heap::PerformGarbageCollection(GarbageCollector collector,
772 bool next_gc_likely_to_collect_more = false;
774 if (collector != SCAVENGER) {
775 PROFILE(isolate_, CodeMovingGCEvent());
778 if (FLAG_verify_heap) {
781 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
782 ASSERT(!allocation_allowed_);
783 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
784 global_gc_prologue_callback_();
788 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
790 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
791 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
792 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
796 EnsureFromSpaceIsCommitted();
798 int start_new_space_size = Heap::new_space()->SizeAsInt();
800 if (IsHighSurvivalRate()) {
801 // We speed up the incremental marker if it is running so that it
802 // does not fall behind the rate of promotion, which would cause a
803 // constantly growing old space.
804 incremental_marking()->NotifyOfHighPromotionRate();
807 if (collector == MARK_COMPACTOR) {
808 // Perform mark-sweep with optional compaction.
811 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
812 IsStableOrIncreasingSurvivalTrend();
814 UpdateSurvivalRateTrend(start_new_space_size);
816 size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
818 if (high_survival_rate_during_scavenges &&
819 IsStableOrIncreasingSurvivalTrend()) {
820 // Stable high survival rates of young objects both during partial and
821 // full collection indicate that mutator is either building or modifying
822 // a structure with a long lifetime.
823 // In this case we aggressively raise old generation memory limits to
824 // postpone subsequent mark-sweep collection and thus trade memory
825 // space for the mutation speed.
826 old_gen_limit_factor_ = 2;
828 old_gen_limit_factor_ = 1;
831 old_gen_promotion_limit_ =
832 OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
833 old_gen_allocation_limit_ =
834 OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
836 old_gen_exhausted_ = false;
842 UpdateSurvivalRateTrend(start_new_space_size);
845 if (!new_space_high_promotion_mode_active_ &&
846 new_space_.Capacity() == new_space_.MaximumCapacity() &&
847 IsStableOrIncreasingSurvivalTrend() &&
848 IsHighSurvivalRate()) {
849 // Stable high survival rates even though young generation is at
850 // maximum capacity indicates that most objects will be promoted.
851 // To decrease scavenger pauses and final mark-sweep pauses, we
852 // have to limit maximal capacity of the young generation.
853 new_space_high_promotion_mode_active_ = true;
855 PrintF("Limited new space size due to high promotion rate: %d MB\n",
856 new_space_.InitialCapacity() / MB);
858 } else if (new_space_high_promotion_mode_active_ &&
859 IsStableOrDecreasingSurvivalTrend() &&
860 IsLowSurvivalRate()) {
861 // Decreasing low survival rates might indicate that the above high
862 // promotion mode is over and we should allow the young generation
864 new_space_high_promotion_mode_active_ = false;
866 PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
867 new_space_.MaximumCapacity() / MB);
871 if (new_space_high_promotion_mode_active_ &&
872 new_space_.Capacity() > new_space_.InitialCapacity()) {
876 isolate_->counters()->objs_since_last_young()->Set(0);
878 gc_post_processing_depth_++;
879 { DisableAssertNoAllocation allow_allocation;
880 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
881 next_gc_likely_to_collect_more =
882 isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
884 gc_post_processing_depth_--;
886 // Update relocatables.
887 Relocatable::PostGarbageCollectionProcessing();
889 if (collector == MARK_COMPACTOR) {
890 // Register the amount of external allocated memory.
891 amount_of_external_allocated_memory_at_last_global_gc_ =
892 amount_of_external_allocated_memory_;
895 GCCallbackFlags callback_flags = kNoGCCallbackFlags;
896 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
897 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
898 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
902 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
903 ASSERT(!allocation_allowed_);
904 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
905 global_gc_epilogue_callback_();
907 if (FLAG_verify_heap) {
911 return next_gc_likely_to_collect_more;
915 void Heap::MarkCompact(GCTracer* tracer) {
916 gc_state_ = MARK_COMPACT;
917 LOG(isolate_, ResourceEvent("markcompact", "begin"));
919 mark_compact_collector_.Prepare(tracer);
922 tracer->set_full_gc_count(ms_count_);
924 MarkCompactPrologue();
926 mark_compact_collector_.CollectGarbage();
928 LOG(isolate_, ResourceEvent("markcompact", "end"));
930 gc_state_ = NOT_IN_GC;
932 isolate_->counters()->objs_since_last_full()->Set(0);
934 contexts_disposed_ = 0;
936 isolate_->set_context_exit_happened(false);
940 void Heap::MarkCompactPrologue() {
941 // At any old GC clear the keyed lookup cache to enable collection of unused
943 isolate_->keyed_lookup_cache()->Clear();
944 isolate_->context_slot_cache()->Clear();
945 isolate_->descriptor_lookup_cache()->Clear();
946 StringSplitCache::Clear(string_split_cache());
948 isolate_->compilation_cache()->MarkCompactPrologue();
950 CompletelyClearInstanceofCache();
952 FlushNumberStringCache();
953 if (FLAG_cleanup_code_caches_at_gc) {
954 polymorphic_code_cache()->set_cache(undefined_value());
957 ClearNormalizedMapCaches();
961 Object* Heap::FindCodeObject(Address a) {
962 return isolate()->inner_pointer_to_code_cache()->
963 GcSafeFindCodeForInnerPointer(a);
967 // Helper class for copying HeapObjects
968 class ScavengeVisitor: public ObjectVisitor {
970 explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
972 void VisitPointer(Object** p) { ScavengePointer(p); }
974 void VisitPointers(Object** start, Object** end) {
975 // Copy all HeapObject pointers in [start, end)
976 for (Object** p = start; p < end; p++) ScavengePointer(p);
980 void ScavengePointer(Object** p) {
982 if (!heap_->InNewSpace(object)) return;
983 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
984 reinterpret_cast<HeapObject*>(object));
992 // Visitor class to verify pointers in code or data space do not point into
994 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
996 void VisitPointers(Object** start, Object**end) {
997 for (Object** current = start; current < end; current++) {
998 if ((*current)->IsHeapObject()) {
999 ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
1006 static void VerifyNonPointerSpacePointers() {
1007 // Verify that there are no pointers to new space in spaces where we
1008 // do not expect them.
1009 VerifyNonPointerSpacePointersVisitor v;
1010 HeapObjectIterator code_it(HEAP->code_space());
1011 for (HeapObject* object = code_it.Next();
1012 object != NULL; object = code_it.Next())
1013 object->Iterate(&v);
1015 // The old data space was normally swept conservatively so that the iterator
1016 // doesn't work, so we normally skip the next bit.
1017 if (!HEAP->old_data_space()->was_swept_conservatively()) {
1018 HeapObjectIterator data_it(HEAP->old_data_space());
1019 for (HeapObject* object = data_it.Next();
1020 object != NULL; object = data_it.Next())
1021 object->Iterate(&v);
1027 void Heap::CheckNewSpaceExpansionCriteria() {
1028 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1029 survived_since_last_expansion_ > new_space_.Capacity() &&
1030 !new_space_high_promotion_mode_active_) {
1031 // Grow the size of new space if there is room to grow, enough data
1032 // has survived scavenge since the last expansion and we are not in
1033 // high promotion mode.
1035 survived_since_last_expansion_ = 0;
1040 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1041 return heap->InNewSpace(*p) &&
1042 !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1046 void Heap::ScavengeStoreBufferCallback(
1049 StoreBufferEvent event) {
1050 heap->store_buffer_rebuilder_.Callback(page, event);
1054 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1055 if (event == kStoreBufferStartScanningPagesEvent) {
1056 start_of_current_page_ = NULL;
1057 current_page_ = NULL;
1058 } else if (event == kStoreBufferScanningPageEvent) {
1059 if (current_page_ != NULL) {
1060 // If this page already overflowed the store buffer during this iteration.
1061 if (current_page_->scan_on_scavenge()) {
1062 // Then we should wipe out the entries that have been added for it.
1063 store_buffer_->SetTop(start_of_current_page_);
1064 } else if (store_buffer_->Top() - start_of_current_page_ >=
1065 (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1066 // Did we find too many pointers in the previous page? The heuristic is
1067 // that no page can take more then 1/5 the remaining slots in the store
1069 current_page_->set_scan_on_scavenge(true);
1070 store_buffer_->SetTop(start_of_current_page_);
1072 // In this case the page we scanned took a reasonable number of slots in
1073 // the store buffer. It has now been rehabilitated and is no longer
1074 // marked scan_on_scavenge.
1075 ASSERT(!current_page_->scan_on_scavenge());
1078 start_of_current_page_ = store_buffer_->Top();
1079 current_page_ = page;
1080 } else if (event == kStoreBufferFullEvent) {
1081 // The current page overflowed the store buffer again. Wipe out its entries
1082 // in the store buffer and mark it scan-on-scavenge again. This may happen
1083 // several times while scanning.
1084 if (current_page_ == NULL) {
1085 // Store Buffer overflowed while scanning promoted objects. These are not
1086 // in any particular page, though they are likely to be clustered by the
1087 // allocation routines.
1088 store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1090 // Store Buffer overflowed while scanning a particular old space page for
1091 // pointers to new space.
1092 ASSERT(current_page_ == page);
1093 ASSERT(page != NULL);
1094 current_page_->set_scan_on_scavenge(true);
1095 ASSERT(start_of_current_page_ != store_buffer_->Top());
1096 store_buffer_->SetTop(start_of_current_page_);
1104 void PromotionQueue::Initialize() {
1105 // Assumes that a NewSpacePage exactly fits a number of promotion queue
1106 // entries (where each is a pair of intptr_t). This allows us to simplify
1107 // the test fpr when to switch pages.
1108 ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1110 limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1112 reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1113 emergency_stack_ = NULL;
1118 void PromotionQueue::RelocateQueueHead() {
1119 ASSERT(emergency_stack_ == NULL);
1121 Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1122 intptr_t* head_start = rear_;
1123 intptr_t* head_end =
1124 Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1127 static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1129 emergency_stack_ = new List<Entry>(2 * entries_count);
1131 while (head_start != head_end) {
1132 int size = static_cast<int>(*(head_start++));
1133 HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1134 emergency_stack_->Add(Entry(obj, size));
1140 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1142 explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
1144 virtual Object* RetainAs(Object* object) {
1145 if (!heap_->InFromSpace(object)) {
1149 MapWord map_word = HeapObject::cast(object)->map_word();
1150 if (map_word.IsForwardingAddress()) {
1151 return map_word.ToForwardingAddress();
1161 void Heap::Scavenge() {
1163 if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1166 gc_state_ = SCAVENGE;
1168 // Implements Cheney's copying algorithm
1169 LOG(isolate_, ResourceEvent("scavenge", "begin"));
1171 // Clear descriptor cache.
1172 isolate_->descriptor_lookup_cache()->Clear();
1174 // Used for updating survived_since_last_expansion_ at function end.
1175 intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1177 CheckNewSpaceExpansionCriteria();
1179 SelectScavengingVisitorsTable();
1181 incremental_marking()->PrepareForScavenge();
1183 AdvanceSweepers(static_cast<int>(new_space_.Size()));
1185 // Flip the semispaces. After flipping, to space is empty, from space has
1188 new_space_.ResetAllocationInfo();
1190 // We need to sweep newly copied objects which can be either in the
1191 // to space or promoted to the old generation. For to-space
1192 // objects, we treat the bottom of the to space as a queue. Newly
1193 // copied and unswept objects lie between a 'front' mark and the
1194 // allocation pointer.
1196 // Promoted objects can go into various old-generation spaces, and
1197 // can be allocated internally in the spaces (from the free list).
1198 // We treat the top of the to space as a queue of addresses of
1199 // promoted objects. The addresses of newly promoted and unswept
1200 // objects lie between a 'front' mark and a 'rear' mark that is
1201 // updated as a side effect of promoting an object.
1203 // There is guaranteed to be enough room at the top of the to space
1204 // for the addresses of promoted objects: every object promoted
1205 // frees up its size in bytes from the top of the new space, and
1206 // objects are at least one pointer in size.
1207 Address new_space_front = new_space_.ToSpaceStart();
1208 promotion_queue_.Initialize();
1211 store_buffer()->Clean();
1214 ScavengeVisitor scavenge_visitor(this);
1216 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1218 // Copy objects reachable from the old generation.
1220 StoreBufferRebuildScope scope(this,
1222 &ScavengeStoreBufferCallback);
1223 store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1226 // Copy objects reachable from cells by scavenging cell values directly.
1227 HeapObjectIterator cell_iterator(cell_space_);
1228 for (HeapObject* cell = cell_iterator.Next();
1229 cell != NULL; cell = cell_iterator.Next()) {
1230 if (cell->IsJSGlobalPropertyCell()) {
1231 Address value_address =
1232 reinterpret_cast<Address>(cell) +
1233 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1234 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1238 // Scavenge object reachable from the global contexts list directly.
1239 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1241 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1242 isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1243 &IsUnscavengedHeapObject);
1244 isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1246 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1248 UpdateNewSpaceReferencesInExternalStringTable(
1249 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1251 promotion_queue_.Destroy();
1253 LiveObjectList::UpdateReferencesForScavengeGC();
1254 if (!FLAG_watch_ic_patching) {
1255 isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1257 incremental_marking()->UpdateMarkingDequeAfterScavenge();
1259 ScavengeWeakObjectRetainer weak_object_retainer(this);
1260 ProcessWeakReferences(&weak_object_retainer);
1262 ASSERT(new_space_front == new_space_.top());
1265 new_space_.set_age_mark(new_space_.top());
1267 new_space_.LowerInlineAllocationLimit(
1268 new_space_.inline_allocation_limit_step());
1270 // Update how much has survived scavenge.
1271 IncrementYoungSurvivorsCounter(static_cast<int>(
1272 (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1274 LOG(isolate_, ResourceEvent("scavenge", "end"));
1276 gc_state_ = NOT_IN_GC;
1278 scavenges_since_last_idle_round_++;
1282 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1284 MapWord first_word = HeapObject::cast(*p)->map_word();
1286 if (!first_word.IsForwardingAddress()) {
1287 // Unreachable external string can be finalized.
1288 heap->FinalizeExternalString(String::cast(*p));
1292 // String is still reachable.
1293 return String::cast(first_word.ToForwardingAddress());
1297 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1298 ExternalStringTableUpdaterCallback updater_func) {
1299 if (FLAG_verify_heap) {
1300 external_string_table_.Verify();
1303 if (external_string_table_.new_space_strings_.is_empty()) return;
1305 Object** start = &external_string_table_.new_space_strings_[0];
1306 Object** end = start + external_string_table_.new_space_strings_.length();
1307 Object** last = start;
1309 for (Object** p = start; p < end; ++p) {
1310 ASSERT(InFromSpace(*p));
1311 String* target = updater_func(this, p);
1313 if (target == NULL) continue;
1315 ASSERT(target->IsExternalString());
1317 if (InNewSpace(target)) {
1318 // String is still in new space. Update the table entry.
1322 // String got promoted. Move it to the old string list.
1323 external_string_table_.AddOldString(target);
1327 ASSERT(last <= end);
1328 external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1332 void Heap::UpdateReferencesInExternalStringTable(
1333 ExternalStringTableUpdaterCallback updater_func) {
1335 // Update old space string references.
1336 if (external_string_table_.old_space_strings_.length() > 0) {
1337 Object** start = &external_string_table_.old_space_strings_[0];
1338 Object** end = start + external_string_table_.old_space_strings_.length();
1339 for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1342 UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1346 static Object* ProcessFunctionWeakReferences(Heap* heap,
1348 WeakObjectRetainer* retainer,
1349 bool record_slots) {
1350 Object* undefined = heap->undefined_value();
1351 Object* head = undefined;
1352 JSFunction* tail = NULL;
1353 Object* candidate = function;
1354 while (candidate != undefined) {
1355 // Check whether to keep the candidate in the list.
1356 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1357 Object* retain = retainer->RetainAs(candidate);
1358 if (retain != NULL) {
1359 if (head == undefined) {
1360 // First element in the list.
1363 // Subsequent elements in the list.
1364 ASSERT(tail != NULL);
1365 tail->set_next_function_link(retain);
1367 Object** next_function =
1368 HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
1369 heap->mark_compact_collector()->RecordSlot(
1370 next_function, next_function, retain);
1373 // Retained function is new tail.
1374 candidate_function = reinterpret_cast<JSFunction*>(retain);
1375 tail = candidate_function;
1377 ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1379 if (retain == undefined) break;
1382 // Move to next element in the list.
1383 candidate = candidate_function->next_function_link();
1386 // Terminate the list if there is one or more elements.
1388 tail->set_next_function_link(undefined);
1395 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1396 Object* undefined = undefined_value();
1397 Object* head = undefined;
1398 Context* tail = NULL;
1399 Object* candidate = global_contexts_list_;
1401 // We don't record weak slots during marking or scavenges.
1402 // Instead we do it once when we complete mark-compact cycle.
1403 // Note that write barrier has no effect if we are already in the middle of
1404 // compacting mark-sweep cycle and we have to record slots manually.
1406 gc_state() == MARK_COMPACT &&
1407 mark_compact_collector()->is_compacting();
1409 while (candidate != undefined) {
1410 // Check whether to keep the candidate in the list.
1411 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1412 Object* retain = retainer->RetainAs(candidate);
1413 if (retain != NULL) {
1414 if (head == undefined) {
1415 // First element in the list.
1418 // Subsequent elements in the list.
1419 ASSERT(tail != NULL);
1420 tail->set_unchecked(this,
1421 Context::NEXT_CONTEXT_LINK,
1423 UPDATE_WRITE_BARRIER);
1426 Object** next_context =
1427 HeapObject::RawField(
1428 tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
1429 mark_compact_collector()->RecordSlot(
1430 next_context, next_context, retain);
1433 // Retained context is new tail.
1434 candidate_context = reinterpret_cast<Context*>(retain);
1435 tail = candidate_context;
1437 if (retain == undefined) break;
1439 // Process the weak list of optimized functions for the context.
1440 Object* function_list_head =
1441 ProcessFunctionWeakReferences(
1443 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1446 candidate_context->set_unchecked(this,
1447 Context::OPTIMIZED_FUNCTIONS_LIST,
1449 UPDATE_WRITE_BARRIER);
1451 Object** optimized_functions =
1452 HeapObject::RawField(
1453 tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
1454 mark_compact_collector()->RecordSlot(
1455 optimized_functions, optimized_functions, function_list_head);
1459 // Move to next element in the list.
1460 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1463 // Terminate the list if there is one or more elements.
1465 tail->set_unchecked(this,
1466 Context::NEXT_CONTEXT_LINK,
1467 Heap::undefined_value(),
1468 UPDATE_WRITE_BARRIER);
1471 // Update the head of the list of contexts.
1472 global_contexts_list_ = head;
1476 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1477 AssertNoAllocation no_allocation;
1479 class VisitorAdapter : public ObjectVisitor {
1481 explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1482 : visitor_(visitor) {}
1483 virtual void VisitPointers(Object** start, Object** end) {
1484 for (Object** p = start; p < end; p++) {
1485 if ((*p)->IsExternalString()) {
1486 visitor_->VisitExternalString(Utils::ToLocal(
1487 Handle<String>(String::cast(*p))));
1492 v8::ExternalResourceVisitor* visitor_;
1493 } visitor_adapter(visitor);
1494 external_string_table_.Iterate(&visitor_adapter);
1498 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1500 static inline void VisitPointer(Heap* heap, Object** p) {
1501 Object* object = *p;
1502 if (!heap->InNewSpace(object)) return;
1503 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1504 reinterpret_cast<HeapObject*>(object));
1509 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1510 Address new_space_front) {
1512 SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1513 // The addresses new_space_front and new_space_.top() define a
1514 // queue of unprocessed copied objects. Process them until the
1516 while (new_space_front != new_space_.top()) {
1517 if (!NewSpacePage::IsAtEnd(new_space_front)) {
1518 HeapObject* object = HeapObject::FromAddress(new_space_front);
1520 NewSpaceScavenger::IterateBody(object->map(), object);
1523 NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1527 // Promote and process all the to-be-promoted objects.
1529 StoreBufferRebuildScope scope(this,
1531 &ScavengeStoreBufferCallback);
1532 while (!promotion_queue()->is_empty()) {
1535 promotion_queue()->remove(&target, &size);
1537 // Promoted object might be already partially visited
1538 // during old space pointer iteration. Thus we search specificly
1539 // for pointers to from semispace instead of looking for pointers
1541 ASSERT(!target->IsMap());
1542 IterateAndMarkPointersToFromSpace(target->address(),
1543 target->address() + size,
1548 // Take another spin if there are now unswept objects in new space
1549 // (there are currently no more unswept promoted objects).
1550 } while (new_space_front != new_space_.top());
1552 return new_space_front;
1556 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
1559 INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
1563 static HeapObject* EnsureDoubleAligned(Heap* heap,
1566 if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
1567 heap->CreateFillerObjectAt(object->address(), kPointerSize);
1568 return HeapObject::FromAddress(object->address() + kPointerSize);
1570 heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
1577 enum LoggingAndProfiling {
1578 LOGGING_AND_PROFILING_ENABLED,
1579 LOGGING_AND_PROFILING_DISABLED
1583 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1586 template<MarksHandling marks_handling,
1587 LoggingAndProfiling logging_and_profiling_mode>
1588 class ScavengingVisitor : public StaticVisitorBase {
1590 static void Initialize() {
1591 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1592 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1593 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1594 table_.Register(kVisitByteArray, &EvacuateByteArray);
1595 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1596 table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1598 table_.Register(kVisitGlobalContext,
1599 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1600 template VisitSpecialized<Context::kSize>);
1602 table_.Register(kVisitConsString,
1603 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1604 template VisitSpecialized<ConsString::kSize>);
1606 table_.Register(kVisitSlicedString,
1607 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1608 template VisitSpecialized<SlicedString::kSize>);
1610 table_.Register(kVisitSharedFunctionInfo,
1611 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1612 template VisitSpecialized<SharedFunctionInfo::kSize>);
1614 table_.Register(kVisitJSWeakMap,
1615 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1618 table_.Register(kVisitJSRegExp,
1619 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1622 if (marks_handling == IGNORE_MARKS) {
1623 table_.Register(kVisitJSFunction,
1624 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1625 template VisitSpecialized<JSFunction::kSize>);
1627 table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1630 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1632 kVisitDataObjectGeneric>();
1634 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1636 kVisitJSObjectGeneric>();
1638 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1640 kVisitStructGeneric>();
1643 static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1648 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1649 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1651 static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1652 bool should_record = false;
1654 should_record = FLAG_heap_stats;
1656 should_record = should_record || FLAG_log_gc;
1657 if (should_record) {
1658 if (heap->new_space()->Contains(obj)) {
1659 heap->new_space()->RecordAllocation(obj);
1661 heap->new_space()->RecordPromotion(obj);
1666 // Helper function used by CopyObject to copy a source object to an
1667 // allocated target object and update the forwarding pointer in the source
1668 // object. Returns the target object.
1669 INLINE(static void MigrateObject(Heap* heap,
1673 // Copy the content of source to target.
1674 heap->CopyBlock(target->address(), source->address(), size);
1676 // Set the forwarding address.
1677 source->set_map_word(MapWord::FromForwardingAddress(target));
1679 if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1680 // Update NewSpace stats if necessary.
1681 RecordCopiedObject(heap, target);
1682 HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1683 Isolate* isolate = heap->isolate();
1684 if (isolate->logger()->is_logging() ||
1685 CpuProfiler::is_profiling(isolate)) {
1686 if (target->IsSharedFunctionInfo()) {
1687 PROFILE(isolate, SharedFunctionInfoMoveEvent(
1688 source->address(), target->address()));
1693 if (marks_handling == TRANSFER_MARKS) {
1694 if (Marking::TransferColor(source, target)) {
1695 MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1701 template<ObjectContents object_contents,
1702 SizeRestriction size_restriction,
1704 static inline void EvacuateObject(Map* map,
1708 SLOW_ASSERT((size_restriction != SMALL) ||
1709 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1710 SLOW_ASSERT(object->Size() == object_size);
1712 int allocation_size = object_size;
1713 if (alignment != kObjectAlignment) {
1714 ASSERT(alignment == kDoubleAlignment);
1715 allocation_size += kPointerSize;
1718 Heap* heap = map->GetHeap();
1719 if (heap->ShouldBePromoted(object->address(), object_size)) {
1720 MaybeObject* maybe_result;
1722 if ((size_restriction != SMALL) &&
1723 (allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
1724 maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
1727 if (object_contents == DATA_OBJECT) {
1728 maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
1731 heap->old_pointer_space()->AllocateRaw(allocation_size);
1735 Object* result = NULL; // Initialization to please compiler.
1736 if (maybe_result->ToObject(&result)) {
1737 HeapObject* target = HeapObject::cast(result);
1739 if (alignment != kObjectAlignment) {
1740 target = EnsureDoubleAligned(heap, target, allocation_size);
1743 // Order is important: slot might be inside of the target if target
1744 // was allocated over a dead object and slot comes from the store
1747 MigrateObject(heap, object, target, object_size);
1749 if (object_contents == POINTER_OBJECT) {
1750 if (map->instance_type() == JS_FUNCTION_TYPE) {
1751 heap->promotion_queue()->insert(
1752 target, JSFunction::kNonWeakFieldsEndOffset);
1754 heap->promotion_queue()->insert(target, object_size);
1758 heap->tracer()->increment_promoted_objects_size(object_size);
1762 MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
1763 heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1764 Object* result = allocation->ToObjectUnchecked();
1765 HeapObject* target = HeapObject::cast(result);
1767 if (alignment != kObjectAlignment) {
1768 target = EnsureDoubleAligned(heap, target, allocation_size);
1771 // Order is important: slot might be inside of the target if target
1772 // was allocated over a dead object and slot comes from the store
1775 MigrateObject(heap, object, target, object_size);
1780 static inline void EvacuateJSFunction(Map* map,
1782 HeapObject* object) {
1783 ObjectEvacuationStrategy<POINTER_OBJECT>::
1784 template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1786 HeapObject* target = *slot;
1787 MarkBit mark_bit = Marking::MarkBitFrom(target);
1788 if (Marking::IsBlack(mark_bit)) {
1789 // This object is black and it might not be rescanned by marker.
1790 // We should explicitly record code entry slot for compaction because
1791 // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1792 // miss it as it is not HeapObject-tagged.
1793 Address code_entry_slot =
1794 target->address() + JSFunction::kCodeEntryOffset;
1795 Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1796 map->GetHeap()->mark_compact_collector()->
1797 RecordCodeEntrySlot(code_entry_slot, code);
1802 static inline void EvacuateFixedArray(Map* map,
1804 HeapObject* object) {
1805 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1806 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
1813 static inline void EvacuateFixedDoubleArray(Map* map,
1815 HeapObject* object) {
1816 int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1817 int object_size = FixedDoubleArray::SizeFor(length);
1818 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
1826 static inline void EvacuateByteArray(Map* map,
1828 HeapObject* object) {
1829 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1830 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1831 map, slot, object, object_size);
1835 static inline void EvacuateSeqAsciiString(Map* map,
1837 HeapObject* object) {
1838 int object_size = SeqAsciiString::cast(object)->
1839 SeqAsciiStringSize(map->instance_type());
1840 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1841 map, slot, object, object_size);
1845 static inline void EvacuateSeqTwoByteString(Map* map,
1847 HeapObject* object) {
1848 int object_size = SeqTwoByteString::cast(object)->
1849 SeqTwoByteStringSize(map->instance_type());
1850 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1851 map, slot, object, object_size);
1855 static inline bool IsShortcutCandidate(int type) {
1856 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1859 static inline void EvacuateShortcutCandidate(Map* map,
1861 HeapObject* object) {
1862 ASSERT(IsShortcutCandidate(map->instance_type()));
1864 Heap* heap = map->GetHeap();
1866 if (marks_handling == IGNORE_MARKS &&
1867 ConsString::cast(object)->unchecked_second() ==
1868 heap->empty_string()) {
1870 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1874 if (!heap->InNewSpace(first)) {
1875 object->set_map_word(MapWord::FromForwardingAddress(first));
1879 MapWord first_word = first->map_word();
1880 if (first_word.IsForwardingAddress()) {
1881 HeapObject* target = first_word.ToForwardingAddress();
1884 object->set_map_word(MapWord::FromForwardingAddress(target));
1888 heap->DoScavengeObject(first->map(), slot, first);
1889 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1893 int object_size = ConsString::kSize;
1894 EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
1895 map, slot, object, object_size);
1898 template<ObjectContents object_contents>
1899 class ObjectEvacuationStrategy {
1901 template<int object_size>
1902 static inline void VisitSpecialized(Map* map,
1904 HeapObject* object) {
1905 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1906 map, slot, object, object_size);
1909 static inline void Visit(Map* map,
1911 HeapObject* object) {
1912 int object_size = map->instance_size();
1913 EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1914 map, slot, object, object_size);
1918 static VisitorDispatchTable<ScavengingCallback> table_;
1922 template<MarksHandling marks_handling,
1923 LoggingAndProfiling logging_and_profiling_mode>
1924 VisitorDispatchTable<ScavengingCallback>
1925 ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1928 static void InitializeScavengingVisitorsTables() {
1929 ScavengingVisitor<TRANSFER_MARKS,
1930 LOGGING_AND_PROFILING_DISABLED>::Initialize();
1931 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1932 ScavengingVisitor<TRANSFER_MARKS,
1933 LOGGING_AND_PROFILING_ENABLED>::Initialize();
1934 ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1938 void Heap::SelectScavengingVisitorsTable() {
1939 bool logging_and_profiling =
1940 isolate()->logger()->is_logging() ||
1941 CpuProfiler::is_profiling(isolate()) ||
1942 (isolate()->heap_profiler() != NULL &&
1943 isolate()->heap_profiler()->is_profiling());
1945 if (!incremental_marking()->IsMarking()) {
1946 if (!logging_and_profiling) {
1947 scavenging_visitors_table_.CopyFrom(
1948 ScavengingVisitor<IGNORE_MARKS,
1949 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1951 scavenging_visitors_table_.CopyFrom(
1952 ScavengingVisitor<IGNORE_MARKS,
1953 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1956 if (!logging_and_profiling) {
1957 scavenging_visitors_table_.CopyFrom(
1958 ScavengingVisitor<TRANSFER_MARKS,
1959 LOGGING_AND_PROFILING_DISABLED>::GetTable());
1961 scavenging_visitors_table_.CopyFrom(
1962 ScavengingVisitor<TRANSFER_MARKS,
1963 LOGGING_AND_PROFILING_ENABLED>::GetTable());
1966 if (incremental_marking()->IsCompacting()) {
1967 // When compacting forbid short-circuiting of cons-strings.
1968 // Scavenging code relies on the fact that new space object
1969 // can't be evacuated into evacuation candidate but
1970 // short-circuiting violates this assumption.
1971 scavenging_visitors_table_.Register(
1972 StaticVisitorBase::kVisitShortcutCandidate,
1973 scavenging_visitors_table_.GetVisitorById(
1974 StaticVisitorBase::kVisitConsString));
1980 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1981 SLOW_ASSERT(HEAP->InFromSpace(object));
1982 MapWord first_word = object->map_word();
1983 SLOW_ASSERT(!first_word.IsForwardingAddress());
1984 Map* map = first_word.ToMap();
1985 map->GetHeap()->DoScavengeObject(map, p, object);
1989 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1990 int instance_size) {
1992 { MaybeObject* maybe_result = AllocateRawMap();
1993 if (!maybe_result->ToObject(&result)) return maybe_result;
1996 // Map::cast cannot be used due to uninitialized map field.
1997 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1998 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1999 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2000 reinterpret_cast<Map*>(result)->set_visitor_id(
2001 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2002 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2003 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
2004 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2005 reinterpret_cast<Map*>(result)->set_bit_field(0);
2006 reinterpret_cast<Map*>(result)->set_bit_field2(0);
2011 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
2013 ElementsKind elements_kind) {
2015 { MaybeObject* maybe_result = AllocateRawMap();
2016 if (!maybe_result->ToObject(&result)) return maybe_result;
2019 Map* map = reinterpret_cast<Map*>(result);
2020 map->set_map_no_write_barrier(meta_map());
2021 map->set_instance_type(instance_type);
2022 map->set_visitor_id(
2023 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2024 map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2025 map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
2026 map->set_instance_size(instance_size);
2027 map->set_inobject_properties(0);
2028 map->set_pre_allocated_property_fields(0);
2029 map->init_instance_descriptors();
2030 map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2031 map->init_prototype_transitions(undefined_value());
2032 map->set_unused_property_fields(0);
2033 map->set_bit_field(0);
2034 map->set_bit_field2(1 << Map::kIsExtensible);
2035 map->set_elements_kind(elements_kind);
2037 // If the map object is aligned fill the padding area with Smi 0 objects.
2038 if (Map::kPadStart < Map::kSize) {
2039 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
2041 Map::kSize - Map::kPadStart);
2047 MaybeObject* Heap::AllocateCodeCache() {
2048 CodeCache* code_cache;
2049 { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
2050 if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
2052 code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2053 code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
2058 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
2059 return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
2063 MaybeObject* Heap::AllocateAccessorPair() {
2064 AccessorPair* accessors;
2065 { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
2066 if (!maybe_accessors->To(&accessors)) return maybe_accessors;
2068 accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
2069 accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
2074 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
2075 TypeFeedbackInfo* info;
2076 { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
2077 if (!maybe_info->To(&info)) return maybe_info;
2079 info->set_ic_total_count(0);
2080 info->set_ic_with_type_info_count(0);
2081 info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
2082 SKIP_WRITE_BARRIER);
2087 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
2088 AliasedArgumentsEntry* entry;
2089 { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
2090 if (!maybe_entry->To(&entry)) return maybe_entry;
2092 entry->set_aliased_context_slot(aliased_context_slot);
2097 const Heap::StringTypeTable Heap::string_type_table[] = {
2098 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
2099 {type, size, k##camel_name##MapRootIndex},
2100 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2101 #undef STRING_TYPE_ELEMENT
2105 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
2106 #define CONSTANT_SYMBOL_ELEMENT(name, contents) \
2107 {contents, k##name##RootIndex},
2108 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
2109 #undef CONSTANT_SYMBOL_ELEMENT
2113 const Heap::StructTable Heap::struct_table[] = {
2114 #define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
2115 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
2116 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2117 #undef STRUCT_TABLE_ELEMENT
2121 bool Heap::CreateInitialMaps() {
2123 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2124 if (!maybe_obj->ToObject(&obj)) return false;
2126 // Map::cast cannot be used due to uninitialized map field.
2127 Map* new_meta_map = reinterpret_cast<Map*>(obj);
2128 set_meta_map(new_meta_map);
2129 new_meta_map->set_map(new_meta_map);
2131 { MaybeObject* maybe_obj =
2132 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2133 if (!maybe_obj->ToObject(&obj)) return false;
2135 set_fixed_array_map(Map::cast(obj));
2137 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2138 if (!maybe_obj->ToObject(&obj)) return false;
2140 set_oddball_map(Map::cast(obj));
2142 // Allocate the empty array.
2143 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2144 if (!maybe_obj->ToObject(&obj)) return false;
2146 set_empty_fixed_array(FixedArray::cast(obj));
2148 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2149 if (!maybe_obj->ToObject(&obj)) return false;
2151 set_null_value(Oddball::cast(obj));
2152 Oddball::cast(obj)->set_kind(Oddball::kNull);
2154 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2155 if (!maybe_obj->ToObject(&obj)) return false;
2157 set_undefined_value(Oddball::cast(obj));
2158 Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2159 ASSERT(!InNewSpace(undefined_value()));
2161 // Allocate the empty descriptor array.
2162 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2163 if (!maybe_obj->ToObject(&obj)) return false;
2165 set_empty_descriptor_array(DescriptorArray::cast(obj));
2167 // Fix the instance_descriptors for the existing maps.
2168 meta_map()->init_instance_descriptors();
2169 meta_map()->set_code_cache(empty_fixed_array());
2170 meta_map()->init_prototype_transitions(undefined_value());
2172 fixed_array_map()->init_instance_descriptors();
2173 fixed_array_map()->set_code_cache(empty_fixed_array());
2174 fixed_array_map()->init_prototype_transitions(undefined_value());
2176 oddball_map()->init_instance_descriptors();
2177 oddball_map()->set_code_cache(empty_fixed_array());
2178 oddball_map()->init_prototype_transitions(undefined_value());
2180 // Fix prototype object for existing maps.
2181 meta_map()->set_prototype(null_value());
2182 meta_map()->set_constructor(null_value());
2184 fixed_array_map()->set_prototype(null_value());
2185 fixed_array_map()->set_constructor(null_value());
2187 oddball_map()->set_prototype(null_value());
2188 oddball_map()->set_constructor(null_value());
2190 { MaybeObject* maybe_obj =
2191 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2192 if (!maybe_obj->ToObject(&obj)) return false;
2194 set_fixed_cow_array_map(Map::cast(obj));
2195 ASSERT(fixed_array_map() != fixed_cow_array_map());
2197 { MaybeObject* maybe_obj =
2198 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2199 if (!maybe_obj->ToObject(&obj)) return false;
2201 set_scope_info_map(Map::cast(obj));
2203 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2204 if (!maybe_obj->ToObject(&obj)) return false;
2206 set_heap_number_map(Map::cast(obj));
2208 { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2209 if (!maybe_obj->ToObject(&obj)) return false;
2211 set_foreign_map(Map::cast(obj));
2213 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2214 const StringTypeTable& entry = string_type_table[i];
2215 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2216 if (!maybe_obj->ToObject(&obj)) return false;
2218 roots_[entry.index] = Map::cast(obj);
2221 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2222 if (!maybe_obj->ToObject(&obj)) return false;
2224 set_undetectable_string_map(Map::cast(obj));
2225 Map::cast(obj)->set_is_undetectable();
2227 { MaybeObject* maybe_obj =
2228 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2229 if (!maybe_obj->ToObject(&obj)) return false;
2231 set_undetectable_ascii_string_map(Map::cast(obj));
2232 Map::cast(obj)->set_is_undetectable();
2234 { MaybeObject* maybe_obj =
2235 AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2236 if (!maybe_obj->ToObject(&obj)) return false;
2238 set_fixed_double_array_map(Map::cast(obj));
2240 { MaybeObject* maybe_obj =
2241 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2242 if (!maybe_obj->ToObject(&obj)) return false;
2244 set_byte_array_map(Map::cast(obj));
2246 { MaybeObject* maybe_obj =
2247 AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2248 if (!maybe_obj->ToObject(&obj)) return false;
2250 set_free_space_map(Map::cast(obj));
2252 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2253 if (!maybe_obj->ToObject(&obj)) return false;
2255 set_empty_byte_array(ByteArray::cast(obj));
2257 { MaybeObject* maybe_obj =
2258 AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2259 if (!maybe_obj->ToObject(&obj)) return false;
2261 set_external_pixel_array_map(Map::cast(obj));
2263 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2264 ExternalArray::kAlignedSize);
2265 if (!maybe_obj->ToObject(&obj)) return false;
2267 set_external_byte_array_map(Map::cast(obj));
2269 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2270 ExternalArray::kAlignedSize);
2271 if (!maybe_obj->ToObject(&obj)) return false;
2273 set_external_unsigned_byte_array_map(Map::cast(obj));
2275 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2276 ExternalArray::kAlignedSize);
2277 if (!maybe_obj->ToObject(&obj)) return false;
2279 set_external_short_array_map(Map::cast(obj));
2281 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2282 ExternalArray::kAlignedSize);
2283 if (!maybe_obj->ToObject(&obj)) return false;
2285 set_external_unsigned_short_array_map(Map::cast(obj));
2287 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2288 ExternalArray::kAlignedSize);
2289 if (!maybe_obj->ToObject(&obj)) return false;
2291 set_external_int_array_map(Map::cast(obj));
2293 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2294 ExternalArray::kAlignedSize);
2295 if (!maybe_obj->ToObject(&obj)) return false;
2297 set_external_unsigned_int_array_map(Map::cast(obj));
2299 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2300 ExternalArray::kAlignedSize);
2301 if (!maybe_obj->ToObject(&obj)) return false;
2303 set_external_float_array_map(Map::cast(obj));
2305 { MaybeObject* maybe_obj =
2306 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2307 if (!maybe_obj->ToObject(&obj)) return false;
2309 set_non_strict_arguments_elements_map(Map::cast(obj));
2311 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2312 ExternalArray::kAlignedSize);
2313 if (!maybe_obj->ToObject(&obj)) return false;
2315 set_external_double_array_map(Map::cast(obj));
2317 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2318 if (!maybe_obj->ToObject(&obj)) return false;
2320 set_code_map(Map::cast(obj));
2322 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2323 JSGlobalPropertyCell::kSize);
2324 if (!maybe_obj->ToObject(&obj)) return false;
2326 set_global_property_cell_map(Map::cast(obj));
2328 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2329 if (!maybe_obj->ToObject(&obj)) return false;
2331 set_one_pointer_filler_map(Map::cast(obj));
2333 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2334 if (!maybe_obj->ToObject(&obj)) return false;
2336 set_two_pointer_filler_map(Map::cast(obj));
2338 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2339 const StructTable& entry = struct_table[i];
2340 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2341 if (!maybe_obj->ToObject(&obj)) return false;
2343 roots_[entry.index] = Map::cast(obj);
2346 { MaybeObject* maybe_obj =
2347 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2348 if (!maybe_obj->ToObject(&obj)) return false;
2350 set_hash_table_map(Map::cast(obj));
2352 { MaybeObject* maybe_obj =
2353 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2354 if (!maybe_obj->ToObject(&obj)) return false;
2356 set_function_context_map(Map::cast(obj));
2358 { MaybeObject* maybe_obj =
2359 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2360 if (!maybe_obj->ToObject(&obj)) return false;
2362 set_catch_context_map(Map::cast(obj));
2364 { MaybeObject* maybe_obj =
2365 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2366 if (!maybe_obj->ToObject(&obj)) return false;
2368 set_with_context_map(Map::cast(obj));
2370 { MaybeObject* maybe_obj =
2371 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2372 if (!maybe_obj->ToObject(&obj)) return false;
2374 set_block_context_map(Map::cast(obj));
2376 { MaybeObject* maybe_obj =
2377 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2378 if (!maybe_obj->ToObject(&obj)) return false;
2380 set_module_context_map(Map::cast(obj));
2382 { MaybeObject* maybe_obj =
2383 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2384 if (!maybe_obj->ToObject(&obj)) return false;
2386 Map* global_context_map = Map::cast(obj);
2387 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2388 set_global_context_map(global_context_map);
2390 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2391 SharedFunctionInfo::kAlignedSize);
2392 if (!maybe_obj->ToObject(&obj)) return false;
2394 set_shared_function_info_map(Map::cast(obj));
2396 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2397 JSMessageObject::kSize);
2398 if (!maybe_obj->ToObject(&obj)) return false;
2400 set_message_object_map(Map::cast(obj));
2402 ASSERT(!InNewSpace(empty_fixed_array()));
2407 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2408 // Statically ensure that it is safe to allocate heap numbers in paged
2410 STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2411 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2414 { MaybeObject* maybe_result =
2415 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2416 if (!maybe_result->ToObject(&result)) return maybe_result;
2419 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2420 HeapNumber::cast(result)->set_value(value);
2425 MaybeObject* Heap::AllocateHeapNumber(double value) {
2426 // Use general version, if we're forced to always allocate.
2427 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2429 // This version of AllocateHeapNumber is optimized for
2430 // allocation in new space.
2431 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2432 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2434 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2435 if (!maybe_result->ToObject(&result)) return maybe_result;
2437 HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2438 HeapNumber::cast(result)->set_value(value);
2443 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2445 { MaybeObject* maybe_result = AllocateRawCell();
2446 if (!maybe_result->ToObject(&result)) return maybe_result;
2448 HeapObject::cast(result)->set_map_no_write_barrier(
2449 global_property_cell_map());
2450 JSGlobalPropertyCell::cast(result)->set_value(value);
2455 MaybeObject* Heap::CreateOddball(const char* to_string,
2459 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2460 if (!maybe_result->ToObject(&result)) return maybe_result;
2462 return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2466 bool Heap::CreateApiObjects() {
2469 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2470 if (!maybe_obj->ToObject(&obj)) return false;
2472 // Don't use Smi-only elements optimizations for objects with the neander
2473 // map. There are too many cases where element values are set directly with a
2474 // bottleneck to trap the Smi-only -> fast elements transition, and there
2475 // appears to be no benefit for optimize this case.
2476 Map* new_neander_map = Map::cast(obj);
2477 new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
2478 set_neander_map(new_neander_map);
2480 { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2481 if (!maybe_obj->ToObject(&obj)) return false;
2484 { MaybeObject* maybe_elements = AllocateFixedArray(2);
2485 if (!maybe_elements->ToObject(&elements)) return false;
2487 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2488 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2489 set_message_listeners(JSObject::cast(obj));
2495 void Heap::CreateJSEntryStub() {
2497 set_js_entry_code(*stub.GetCode());
2501 void Heap::CreateJSConstructEntryStub() {
2502 JSConstructEntryStub stub;
2503 set_js_construct_entry_code(*stub.GetCode());
2507 void Heap::CreateFixedStubs() {
2508 // Here we create roots for fixed stubs. They are needed at GC
2509 // for cooking and uncooking (check out frames.cc).
2510 // The eliminates the need for doing dictionary lookup in the
2511 // stub cache for these stubs.
2513 // gcc-4.4 has problem generating correct code of following snippet:
2514 // { JSEntryStub stub;
2515 // js_entry_code_ = *stub.GetCode();
2517 // { JSConstructEntryStub stub;
2518 // js_construct_entry_code_ = *stub.GetCode();
2520 // To workaround the problem, make separate functions without inlining.
2521 Heap::CreateJSEntryStub();
2522 Heap::CreateJSConstructEntryStub();
2524 // Create stubs that should be there, so we don't unexpectedly have to
2525 // create them if we need them during the creation of another stub.
2526 // Stub creation mixes raw pointers and handles in an unsafe manner so
2527 // we cannot create stubs while we are creating stubs.
2528 CodeStub::GenerateStubsAheadOfTime();
2532 bool Heap::CreateInitialObjects() {
2535 // The -0 value must be set before NumberFromDouble works.
2536 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2537 if (!maybe_obj->ToObject(&obj)) return false;
2539 set_minus_zero_value(HeapNumber::cast(obj));
2540 ASSERT(signbit(minus_zero_value()->Number()) != 0);
2542 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2543 if (!maybe_obj->ToObject(&obj)) return false;
2545 set_nan_value(HeapNumber::cast(obj));
2547 { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2548 if (!maybe_obj->ToObject(&obj)) return false;
2550 set_infinity_value(HeapNumber::cast(obj));
2552 // The hole has not been created yet, but we want to put something
2553 // predictable in the gaps in the symbol table, so lets make that Smi zero.
2554 set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2556 // Allocate initial symbol table.
2557 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2558 if (!maybe_obj->ToObject(&obj)) return false;
2560 // Don't use set_symbol_table() due to asserts.
2561 roots_[kSymbolTableRootIndex] = obj;
2563 // Finish initializing oddballs after creating symboltable.
2564 { MaybeObject* maybe_obj =
2565 undefined_value()->Initialize("undefined",
2567 Oddball::kUndefined);
2568 if (!maybe_obj->ToObject(&obj)) return false;
2571 // Initialize the null_value.
2572 { MaybeObject* maybe_obj =
2573 null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2574 if (!maybe_obj->ToObject(&obj)) return false;
2577 { MaybeObject* maybe_obj = CreateOddball("true",
2580 if (!maybe_obj->ToObject(&obj)) return false;
2582 set_true_value(Oddball::cast(obj));
2584 { MaybeObject* maybe_obj = CreateOddball("false",
2587 if (!maybe_obj->ToObject(&obj)) return false;
2589 set_false_value(Oddball::cast(obj));
2591 { MaybeObject* maybe_obj = CreateOddball("hole",
2594 if (!maybe_obj->ToObject(&obj)) return false;
2596 set_the_hole_value(Oddball::cast(obj));
2598 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2600 Oddball::kArgumentMarker);
2601 if (!maybe_obj->ToObject(&obj)) return false;
2603 set_arguments_marker(Oddball::cast(obj));
2605 { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2608 if (!maybe_obj->ToObject(&obj)) return false;
2610 set_no_interceptor_result_sentinel(obj);
2612 { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2615 if (!maybe_obj->ToObject(&obj)) return false;
2617 set_termination_exception(obj);
2619 // Allocate the empty string.
2620 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2621 if (!maybe_obj->ToObject(&obj)) return false;
2623 set_empty_string(String::cast(obj));
2625 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2626 { MaybeObject* maybe_obj =
2627 LookupAsciiSymbol(constant_symbol_table[i].contents);
2628 if (!maybe_obj->ToObject(&obj)) return false;
2630 roots_[constant_symbol_table[i].index] = String::cast(obj);
2633 // Allocate the hidden symbol which is used to identify the hidden properties
2634 // in JSObjects. The hash code has a special value so that it will not match
2635 // the empty string when searching for the property. It cannot be part of the
2636 // loop above because it needs to be allocated manually with the special
2637 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2638 // that it will always be at the first entry in property descriptors.
2639 { MaybeObject* maybe_obj =
2640 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2641 if (!maybe_obj->ToObject(&obj)) return false;
2643 hidden_symbol_ = String::cast(obj);
2645 // Allocate the foreign for __proto__.
2646 { MaybeObject* maybe_obj =
2647 AllocateForeign((Address) &Accessors::ObjectPrototype);
2648 if (!maybe_obj->ToObject(&obj)) return false;
2650 set_prototype_accessors(Foreign::cast(obj));
2652 // Allocate the code_stubs dictionary. The initial size is set to avoid
2653 // expanding the dictionary during bootstrapping.
2654 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2655 if (!maybe_obj->ToObject(&obj)) return false;
2657 set_code_stubs(UnseededNumberDictionary::cast(obj));
2660 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2661 // is set to avoid expanding the dictionary during bootstrapping.
2662 { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2663 if (!maybe_obj->ToObject(&obj)) return false;
2665 set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2667 { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2668 if (!maybe_obj->ToObject(&obj)) return false;
2670 set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2672 set_instanceof_cache_function(Smi::FromInt(0));
2673 set_instanceof_cache_map(Smi::FromInt(0));
2674 set_instanceof_cache_answer(Smi::FromInt(0));
2678 // Allocate the dictionary of intrinsic function names.
2679 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2680 if (!maybe_obj->ToObject(&obj)) return false;
2682 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2684 if (!maybe_obj->ToObject(&obj)) return false;
2686 set_intrinsic_function_names(StringDictionary::cast(obj));
2688 { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2689 if (!maybe_obj->ToObject(&obj)) return false;
2691 set_number_string_cache(FixedArray::cast(obj));
2693 // Allocate cache for single character ASCII strings.
2694 { MaybeObject* maybe_obj =
2695 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2696 if (!maybe_obj->ToObject(&obj)) return false;
2698 set_single_character_string_cache(FixedArray::cast(obj));
2700 // Allocate cache for string split.
2701 { MaybeObject* maybe_obj =
2702 AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2703 if (!maybe_obj->ToObject(&obj)) return false;
2705 set_string_split_cache(FixedArray::cast(obj));
2707 // Allocate cache for external strings pointing to native source code.
2708 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2709 if (!maybe_obj->ToObject(&obj)) return false;
2711 set_natives_source_cache(FixedArray::cast(obj));
2713 // Handling of script id generation is in FACTORY->NewScript.
2714 set_last_script_id(undefined_value());
2716 // Initialize keyed lookup cache.
2717 isolate_->keyed_lookup_cache()->Clear();
2719 // Initialize context slot cache.
2720 isolate_->context_slot_cache()->Clear();
2722 // Initialize descriptor cache.
2723 isolate_->descriptor_lookup_cache()->Clear();
2725 // Initialize compilation cache.
2726 isolate_->compilation_cache()->Clear();
2732 Object* StringSplitCache::Lookup(
2733 FixedArray* cache, String* string, String* pattern) {
2734 if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2735 uint32_t hash = string->Hash();
2736 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2737 ~(kArrayEntriesPerCacheEntry - 1));
2738 if (cache->get(index + kStringOffset) == string &&
2739 cache->get(index + kPatternOffset) == pattern) {
2740 return cache->get(index + kArrayOffset);
2742 index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2743 if (cache->get(index + kStringOffset) == string &&
2744 cache->get(index + kPatternOffset) == pattern) {
2745 return cache->get(index + kArrayOffset);
2747 return Smi::FromInt(0);
2751 void StringSplitCache::Enter(Heap* heap,
2755 FixedArray* array) {
2756 if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2757 uint32_t hash = string->Hash();
2758 uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2759 ~(kArrayEntriesPerCacheEntry - 1));
2760 if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2761 cache->set(index + kStringOffset, string);
2762 cache->set(index + kPatternOffset, pattern);
2763 cache->set(index + kArrayOffset, array);
2766 ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2767 if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2768 cache->set(index2 + kStringOffset, string);
2769 cache->set(index2 + kPatternOffset, pattern);
2770 cache->set(index2 + kArrayOffset, array);
2772 cache->set(index2 + kStringOffset, Smi::FromInt(0));
2773 cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2774 cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2775 cache->set(index + kStringOffset, string);
2776 cache->set(index + kPatternOffset, pattern);
2777 cache->set(index + kArrayOffset, array);
2780 if (array->length() < 100) { // Limit how many new symbols we want to make.
2781 for (int i = 0; i < array->length(); i++) {
2782 String* str = String::cast(array->get(i));
2784 MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2785 if (maybe_symbol->ToObject(&symbol)) {
2786 array->set(i, symbol);
2790 array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2794 void StringSplitCache::Clear(FixedArray* cache) {
2795 for (int i = 0; i < kStringSplitCacheSize; i++) {
2796 cache->set(i, Smi::FromInt(0));
2801 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2802 MaybeObject* maybe_obj =
2803 AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2808 int Heap::FullSizeNumberStringCacheLength() {
2809 // Compute the size of the number string cache based on the max newspace size.
2810 // The number string cache has a minimum size based on twice the initial cache
2811 // size to ensure that it is bigger after being made 'full size'.
2812 int number_string_cache_size = max_semispace_size_ / 512;
2813 number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2814 Min(0x4000, number_string_cache_size));
2815 // There is a string and a number per entry so the length is twice the number
2817 return number_string_cache_size * 2;
2821 void Heap::AllocateFullSizeNumberStringCache() {
2822 // The idea is to have a small number string cache in the snapshot to keep
2823 // boot-time memory usage down. If we expand the number string cache already
2824 // while creating the snapshot then that didn't work out.
2825 ASSERT(!Serializer::enabled());
2826 MaybeObject* maybe_obj =
2827 AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2829 if (maybe_obj->ToObject(&new_cache)) {
2830 // We don't bother to repopulate the cache with entries from the old cache.
2831 // It will be repopulated soon enough with new strings.
2832 set_number_string_cache(FixedArray::cast(new_cache));
2834 // If allocation fails then we just return without doing anything. It is only
2835 // a cache, so best effort is OK here.
2839 void Heap::FlushNumberStringCache() {
2840 // Flush the number to string cache.
2841 int len = number_string_cache()->length();
2842 for (int i = 0; i < len; i++) {
2843 number_string_cache()->set_undefined(this, i);
2848 static inline int double_get_hash(double d) {
2849 DoubleRepresentation rep(d);
2850 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2854 static inline int smi_get_hash(Smi* smi) {
2855 return smi->value();
2859 Object* Heap::GetNumberStringCache(Object* number) {
2861 int mask = (number_string_cache()->length() >> 1) - 1;
2862 if (number->IsSmi()) {
2863 hash = smi_get_hash(Smi::cast(number)) & mask;
2865 hash = double_get_hash(number->Number()) & mask;
2867 Object* key = number_string_cache()->get(hash * 2);
2868 if (key == number) {
2869 return String::cast(number_string_cache()->get(hash * 2 + 1));
2870 } else if (key->IsHeapNumber() &&
2871 number->IsHeapNumber() &&
2872 key->Number() == number->Number()) {
2873 return String::cast(number_string_cache()->get(hash * 2 + 1));
2875 return undefined_value();
2879 void Heap::SetNumberStringCache(Object* number, String* string) {
2881 int mask = (number_string_cache()->length() >> 1) - 1;
2882 if (number->IsSmi()) {
2883 hash = smi_get_hash(Smi::cast(number)) & mask;
2885 hash = double_get_hash(number->Number()) & mask;
2887 if (number_string_cache()->get(hash * 2) != undefined_value() &&
2888 number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2889 // The first time we have a hash collision, we move to the full sized
2890 // number string cache.
2891 AllocateFullSizeNumberStringCache();
2894 number_string_cache()->set(hash * 2, number);
2895 number_string_cache()->set(hash * 2 + 1, string);
2899 MaybeObject* Heap::NumberToString(Object* number,
2900 bool check_number_string_cache) {
2901 isolate_->counters()->number_to_string_runtime()->Increment();
2902 if (check_number_string_cache) {
2903 Object* cached = GetNumberStringCache(number);
2904 if (cached != undefined_value()) {
2910 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2912 if (number->IsSmi()) {
2913 int num = Smi::cast(number)->value();
2914 str = IntToCString(num, buffer);
2916 double num = HeapNumber::cast(number)->value();
2917 str = DoubleToCString(num, buffer);
2921 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2922 if (maybe_js_string->ToObject(&js_string)) {
2923 SetNumberStringCache(number, String::cast(js_string));
2925 return maybe_js_string;
2929 MaybeObject* Heap::Uint32ToString(uint32_t value,
2930 bool check_number_string_cache) {
2932 MaybeObject* maybe = NumberFromUint32(value);
2933 if (!maybe->To<Object>(&number)) return maybe;
2934 return NumberToString(number, check_number_string_cache);
2938 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2939 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2943 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2944 ExternalArrayType array_type) {
2945 switch (array_type) {
2946 case kExternalByteArray:
2947 return kExternalByteArrayMapRootIndex;
2948 case kExternalUnsignedByteArray:
2949 return kExternalUnsignedByteArrayMapRootIndex;
2950 case kExternalShortArray:
2951 return kExternalShortArrayMapRootIndex;
2952 case kExternalUnsignedShortArray:
2953 return kExternalUnsignedShortArrayMapRootIndex;
2954 case kExternalIntArray:
2955 return kExternalIntArrayMapRootIndex;
2956 case kExternalUnsignedIntArray:
2957 return kExternalUnsignedIntArrayMapRootIndex;
2958 case kExternalFloatArray:
2959 return kExternalFloatArrayMapRootIndex;
2960 case kExternalDoubleArray:
2961 return kExternalDoubleArrayMapRootIndex;
2962 case kExternalPixelArray:
2963 return kExternalPixelArrayMapRootIndex;
2966 return kUndefinedValueRootIndex;
2971 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2972 // We need to distinguish the minus zero value and this cannot be
2973 // done after conversion to int. Doing this by comparing bit
2974 // patterns is faster than using fpclassify() et al.
2975 static const DoubleRepresentation minus_zero(-0.0);
2977 DoubleRepresentation rep(value);
2978 if (rep.bits == minus_zero.bits) {
2979 return AllocateHeapNumber(-0.0, pretenure);
2982 int int_value = FastD2I(value);
2983 if (value == int_value && Smi::IsValid(int_value)) {
2984 return Smi::FromInt(int_value);
2987 // Materialize the value in the heap.
2988 return AllocateHeapNumber(value, pretenure);
2992 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2993 // Statically ensure that it is safe to allocate foreigns in paged spaces.
2994 STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
2995 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2997 MaybeObject* maybe_result = Allocate(foreign_map(), space);
2998 if (!maybe_result->To(&result)) return maybe_result;
2999 result->set_foreign_address(address);
3004 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
3005 SharedFunctionInfo* share;
3006 MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
3007 if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
3009 // Set pointer fields.
3010 share->set_name(name);
3011 Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
3012 share->set_code(illegal);
3013 share->set_scope_info(ScopeInfo::Empty());
3014 Code* construct_stub =
3015 isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
3016 share->set_construct_stub(construct_stub);
3017 share->set_instance_class_name(Object_symbol());
3018 share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
3019 share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
3020 share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
3021 share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
3022 share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
3023 share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
3024 share->set_ast_node_count(0);
3025 share->set_stress_deopt_counter(FLAG_deopt_every_n_times);
3026 share->set_counters(0);
3028 // Set integer fields (smi or int, depending on the architecture).
3029 share->set_length(0);
3030 share->set_formal_parameter_count(0);
3031 share->set_expected_nof_properties(0);
3032 share->set_num_literals(0);
3033 share->set_start_position_and_type(0);
3034 share->set_end_position(0);
3035 share->set_function_token_position(0);
3036 // All compiler hints default to false or 0.
3037 share->set_compiler_hints(0);
3038 share->set_this_property_assignments_count(0);
3039 share->set_opt_count(0);
3045 MaybeObject* Heap::AllocateJSMessageObject(String* type,
3050 Object* stack_trace,
3051 Object* stack_frames) {
3053 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
3054 if (!maybe_result->ToObject(&result)) return maybe_result;
3056 JSMessageObject* message = JSMessageObject::cast(result);
3057 message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3058 message->initialize_elements();
3059 message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3060 message->set_type(type);
3061 message->set_arguments(arguments);
3062 message->set_start_position(start_position);
3063 message->set_end_position(end_position);
3064 message->set_script(script);
3065 message->set_stack_trace(stack_trace);
3066 message->set_stack_frames(stack_frames);
3072 // Returns true for a character in a range. Both limits are inclusive.
3073 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
3074 // This makes uses of the the unsigned wraparound.
3075 return character - from <= to - from;
3079 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
3084 // Numeric strings have a different hash algorithm not known by
3085 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
3086 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
3087 heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
3089 // Now we know the length is 2, we might as well make use of that fact
3090 // when building the new string.
3091 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
3092 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
3094 { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
3095 if (!maybe_result->ToObject(&result)) return maybe_result;
3097 char* dest = SeqAsciiString::cast(result)->GetChars();
3103 { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
3104 if (!maybe_result->ToObject(&result)) return maybe_result;
3106 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3114 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
3115 int first_length = first->length();
3116 if (first_length == 0) {
3120 int second_length = second->length();
3121 if (second_length == 0) {
3125 int length = first_length + second_length;
3127 // Optimization for 2-byte strings often used as keys in a decompression
3128 // dictionary. Check whether we already have the string in the symbol
3129 // table to prevent creation of many unneccesary strings.
3131 unsigned c1 = first->Get(0);
3132 unsigned c2 = second->Get(0);
3133 return MakeOrFindTwoCharacterString(this, c1, c2);
3136 bool first_is_ascii = first->IsAsciiRepresentation();
3137 bool second_is_ascii = second->IsAsciiRepresentation();
3138 bool is_ascii = first_is_ascii && second_is_ascii;
3140 // Make sure that an out of memory exception is thrown if the length
3141 // of the new cons string is too large.
3142 if (length > String::kMaxLength || length < 0) {
3143 isolate()->context()->mark_out_of_memory();
3144 return Failure::OutOfMemoryException();
3147 bool is_ascii_data_in_two_byte_string = false;
3149 // At least one of the strings uses two-byte representation so we
3150 // can't use the fast case code for short ASCII strings below, but
3151 // we can try to save memory if all chars actually fit in ASCII.
3152 is_ascii_data_in_two_byte_string =
3153 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3154 if (is_ascii_data_in_two_byte_string) {
3155 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3159 // If the resulting string is small make a flat string.
3160 if (length < ConsString::kMinLength) {
3161 // Note that neither of the two inputs can be a slice because:
3162 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3163 ASSERT(first->IsFlat());
3164 ASSERT(second->IsFlat());
3167 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3168 if (!maybe_result->ToObject(&result)) return maybe_result;
3170 // Copy the characters into the new object.
3171 char* dest = SeqAsciiString::cast(result)->GetChars();
3174 if (first->IsExternalString()) {
3175 src = ExternalAsciiString::cast(first)->GetChars();
3177 src = SeqAsciiString::cast(first)->GetChars();
3179 for (int i = 0; i < first_length; i++) *dest++ = src[i];
3180 // Copy second part.
3181 if (second->IsExternalString()) {
3182 src = ExternalAsciiString::cast(second)->GetChars();
3184 src = SeqAsciiString::cast(second)->GetChars();
3186 for (int i = 0; i < second_length; i++) *dest++ = src[i];
3189 if (is_ascii_data_in_two_byte_string) {
3191 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3192 if (!maybe_result->ToObject(&result)) return maybe_result;
3194 // Copy the characters into the new object.
3195 char* dest = SeqAsciiString::cast(result)->GetChars();
3196 String::WriteToFlat(first, dest, 0, first_length);
3197 String::WriteToFlat(second, dest + first_length, 0, second_length);
3198 isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3203 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3204 if (!maybe_result->ToObject(&result)) return maybe_result;
3206 // Copy the characters into the new object.
3207 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3208 String::WriteToFlat(first, dest, 0, first_length);
3209 String::WriteToFlat(second, dest + first_length, 0, second_length);
3214 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3215 cons_ascii_string_map() : cons_string_map();
3218 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3219 if (!maybe_result->ToObject(&result)) return maybe_result;
3222 AssertNoAllocation no_gc;
3223 ConsString* cons_string = ConsString::cast(result);
3224 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3225 cons_string->set_length(length);
3226 cons_string->set_hash_field(String::kEmptyHashField);
3227 cons_string->set_first(first, mode);
3228 cons_string->set_second(second, mode);
3233 MaybeObject* Heap::AllocateSubString(String* buffer,
3236 PretenureFlag pretenure) {
3237 int length = end - start;
3239 return empty_string();
3240 } else if (length == 1) {
3241 return LookupSingleCharacterStringFromCode(buffer->Get(start));
3242 } else if (length == 2) {
3243 // Optimization for 2-byte strings often used as keys in a decompression
3244 // dictionary. Check whether we already have the string in the symbol
3245 // table to prevent creation of many unneccesary strings.
3246 unsigned c1 = buffer->Get(start);
3247 unsigned c2 = buffer->Get(start + 1);
3248 return MakeOrFindTwoCharacterString(this, c1, c2);
3251 // Make an attempt to flatten the buffer to reduce access time.
3252 buffer = buffer->TryFlattenGetString();
3254 if (!FLAG_string_slices ||
3255 !buffer->IsFlat() ||
3256 length < SlicedString::kMinLength ||
3257 pretenure == TENURED) {
3259 // WriteToFlat takes care of the case when an indirect string has a
3260 // different encoding from its underlying string. These encodings may
3261 // differ because of externalization.
3262 bool is_ascii = buffer->IsAsciiRepresentation();
3263 { MaybeObject* maybe_result = is_ascii
3264 ? AllocateRawAsciiString(length, pretenure)
3265 : AllocateRawTwoByteString(length, pretenure);
3266 if (!maybe_result->ToObject(&result)) return maybe_result;
3268 String* string_result = String::cast(result);
3269 // Copy the characters into the new object.
3271 ASSERT(string_result->IsAsciiRepresentation());
3272 char* dest = SeqAsciiString::cast(string_result)->GetChars();
3273 String::WriteToFlat(buffer, dest, start, end);
3275 ASSERT(string_result->IsTwoByteRepresentation());
3276 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3277 String::WriteToFlat(buffer, dest, start, end);
3282 ASSERT(buffer->IsFlat());
3284 if (FLAG_verify_heap) {
3285 buffer->StringVerify();
3290 // When slicing an indirect string we use its encoding for a newly created
3291 // slice and don't check the encoding of the underlying string. This is safe
3292 // even if the encodings are different because of externalization. If an
3293 // indirect ASCII string is pointing to a two-byte string, the two-byte char
3294 // codes of the underlying string must still fit into ASCII (because
3295 // externalization must not change char codes).
3296 { Map* map = buffer->IsAsciiRepresentation()
3297 ? sliced_ascii_string_map()
3298 : sliced_string_map();
3299 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3300 if (!maybe_result->ToObject(&result)) return maybe_result;
3303 AssertNoAllocation no_gc;
3304 SlicedString* sliced_string = SlicedString::cast(result);
3305 sliced_string->set_length(length);
3306 sliced_string->set_hash_field(String::kEmptyHashField);
3307 if (buffer->IsConsString()) {
3308 ConsString* cons = ConsString::cast(buffer);
3309 ASSERT(cons->second()->length() == 0);
3310 sliced_string->set_parent(cons->first());
3311 sliced_string->set_offset(start);
3312 } else if (buffer->IsSlicedString()) {
3313 // Prevent nesting sliced strings.
3314 SlicedString* parent_slice = SlicedString::cast(buffer);
3315 sliced_string->set_parent(parent_slice->parent());
3316 sliced_string->set_offset(start + parent_slice->offset());
3318 sliced_string->set_parent(buffer);
3319 sliced_string->set_offset(start);
3321 ASSERT(sliced_string->parent()->IsSeqString() ||
3322 sliced_string->parent()->IsExternalString());
3327 MaybeObject* Heap::AllocateExternalStringFromAscii(
3328 const ExternalAsciiString::Resource* resource) {
3329 size_t length = resource->length();
3330 if (length > static_cast<size_t>(String::kMaxLength)) {
3331 isolate()->context()->mark_out_of_memory();
3332 return Failure::OutOfMemoryException();
3335 ASSERT(String::IsAscii(resource->data(), static_cast<int>(length)));
3337 Map* map = external_ascii_string_map();
3339 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3340 if (!maybe_result->ToObject(&result)) return maybe_result;
3343 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3344 external_string->set_length(static_cast<int>(length));
3345 external_string->set_hash_field(String::kEmptyHashField);
3346 external_string->set_resource(resource);
3352 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3353 const ExternalTwoByteString::Resource* resource) {
3354 size_t length = resource->length();
3355 if (length > static_cast<size_t>(String::kMaxLength)) {
3356 isolate()->context()->mark_out_of_memory();
3357 return Failure::OutOfMemoryException();
3360 // For small strings we check whether the resource contains only
3361 // ASCII characters. If yes, we use a different string map.
3362 static const size_t kAsciiCheckLengthLimit = 32;
3363 bool is_ascii = length <= kAsciiCheckLengthLimit &&
3364 String::IsAscii(resource->data(), static_cast<int>(length));
3365 Map* map = is_ascii ?
3366 external_string_with_ascii_data_map() : external_string_map();
3368 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3369 if (!maybe_result->ToObject(&result)) return maybe_result;
3372 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3373 external_string->set_length(static_cast<int>(length));
3374 external_string->set_hash_field(String::kEmptyHashField);
3375 external_string->set_resource(resource);
3381 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3382 if (code <= String::kMaxAsciiCharCode) {
3383 Object* value = single_character_string_cache()->get(code);
3384 if (value != undefined_value()) return value;
3387 buffer[0] = static_cast<char>(code);
3389 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3391 if (!maybe_result->ToObject(&result)) return maybe_result;
3392 single_character_string_cache()->set(code, result);
3397 { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3398 if (!maybe_result->ToObject(&result)) return maybe_result;
3400 String* answer = String::cast(result);
3401 answer->Set(0, code);
3406 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3407 if (length < 0 || length > ByteArray::kMaxLength) {
3408 return Failure::OutOfMemoryException();
3410 if (pretenure == NOT_TENURED) {
3411 return AllocateByteArray(length);
3413 int size = ByteArray::SizeFor(length);
3415 { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3416 ? old_data_space_->AllocateRaw(size)
3417 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3418 if (!maybe_result->ToObject(&result)) return maybe_result;
3421 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3423 reinterpret_cast<ByteArray*>(result)->set_length(length);
3428 MaybeObject* Heap::AllocateByteArray(int length) {
3429 if (length < 0 || length > ByteArray::kMaxLength) {
3430 return Failure::OutOfMemoryException();
3432 int size = ByteArray::SizeFor(length);
3433 AllocationSpace space =
3434 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3436 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3437 if (!maybe_result->ToObject(&result)) return maybe_result;
3440 reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3442 reinterpret_cast<ByteArray*>(result)->set_length(length);
3447 void Heap::CreateFillerObjectAt(Address addr, int size) {
3448 if (size == 0) return;
3449 HeapObject* filler = HeapObject::FromAddress(addr);
3450 if (size == kPointerSize) {
3451 filler->set_map_no_write_barrier(one_pointer_filler_map());
3452 } else if (size == 2 * kPointerSize) {
3453 filler->set_map_no_write_barrier(two_pointer_filler_map());
3455 filler->set_map_no_write_barrier(free_space_map());
3456 FreeSpace::cast(filler)->set_size(size);
3461 MaybeObject* Heap::AllocateExternalArray(int length,
3462 ExternalArrayType array_type,
3463 void* external_pointer,
3464 PretenureFlag pretenure) {
3465 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3467 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3470 if (!maybe_result->ToObject(&result)) return maybe_result;
3473 reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3474 MapForExternalArrayType(array_type));
3475 reinterpret_cast<ExternalArray*>(result)->set_length(length);
3476 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3483 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3485 Handle<Object> self_reference,
3487 // Allocate ByteArray before the Code object, so that we do not risk
3488 // leaving uninitialized Code object (and breaking the heap).
3489 ByteArray* reloc_info;
3490 MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3491 if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3494 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3495 int obj_size = Code::SizeFor(body_size);
3496 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3497 MaybeObject* maybe_result;
3498 // Large code objects and code objects which should stay at a fixed address
3499 // are allocated in large object space.
3500 if (obj_size > code_space()->AreaSize() || immovable) {
3501 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3503 maybe_result = code_space_->AllocateRaw(obj_size);
3507 if (!maybe_result->ToObject(&result)) return maybe_result;
3509 // Initialize the object
3510 HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3511 Code* code = Code::cast(result);
3512 ASSERT(!isolate_->code_range()->exists() ||
3513 isolate_->code_range()->contains(code->address()));
3514 code->set_instruction_size(desc.instr_size);
3515 code->set_relocation_info(reloc_info);
3516 code->set_flags(flags);
3517 if (code->is_call_stub() || code->is_keyed_call_stub()) {
3518 code->set_check_type(RECEIVER_MAP_CHECK);
3520 code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3521 code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3522 code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3523 code->set_gc_metadata(Smi::FromInt(0));
3524 code->set_ic_age(global_ic_age_);
3525 // Allow self references to created code object by patching the handle to
3526 // point to the newly allocated Code object.
3527 if (!self_reference.is_null()) {
3528 *(self_reference.location()) = code;
3530 // Migrate generated code.
3531 // The generated code can contain Object** values (typically from handles)
3532 // that are dereferenced during the copy to point directly to the actual heap
3533 // objects. These pointers can include references to the code object itself,
3534 // through the self_reference parameter.
3535 code->CopyFrom(desc);
3538 if (FLAG_verify_heap) {
3546 MaybeObject* Heap::CopyCode(Code* code) {
3547 // Allocate an object the same size as the code object.
3548 int obj_size = code->Size();
3549 MaybeObject* maybe_result;
3550 if (obj_size > code_space()->AreaSize()) {
3551 maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3553 maybe_result = code_space_->AllocateRaw(obj_size);
3557 if (!maybe_result->ToObject(&result)) return maybe_result;
3559 // Copy code object.
3560 Address old_addr = code->address();
3561 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3562 CopyBlock(new_addr, old_addr, obj_size);
3563 // Relocate the copy.
3564 Code* new_code = Code::cast(result);
3565 ASSERT(!isolate_->code_range()->exists() ||
3566 isolate_->code_range()->contains(code->address()));
3567 new_code->Relocate(new_addr - old_addr);
3572 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3573 // Allocate ByteArray before the Code object, so that we do not risk
3574 // leaving uninitialized Code object (and breaking the heap).
3575 Object* reloc_info_array;
3576 { MaybeObject* maybe_reloc_info_array =
3577 AllocateByteArray(reloc_info.length(), TENURED);
3578 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3579 return maybe_reloc_info_array;
3583 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3585 int new_obj_size = Code::SizeFor(new_body_size);
3587 Address old_addr = code->address();
3589 size_t relocation_offset =
3590 static_cast<size_t>(code->instruction_end() - old_addr);
3592 MaybeObject* maybe_result;
3593 if (new_obj_size > code_space()->AreaSize()) {
3594 maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3596 maybe_result = code_space_->AllocateRaw(new_obj_size);
3600 if (!maybe_result->ToObject(&result)) return maybe_result;
3602 // Copy code object.
3603 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3605 // Copy header and instructions.
3606 memcpy(new_addr, old_addr, relocation_offset);
3608 Code* new_code = Code::cast(result);
3609 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3611 // Copy patched rinfo.
3612 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3614 // Relocate the copy.
3615 ASSERT(!isolate_->code_range()->exists() ||
3616 isolate_->code_range()->contains(code->address()));
3617 new_code->Relocate(new_addr - old_addr);
3620 if (FLAG_verify_heap) {
3628 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3629 ASSERT(gc_state_ == NOT_IN_GC);
3630 ASSERT(map->instance_type() != MAP_TYPE);
3631 // If allocation failures are disallowed, we may allocate in a different
3632 // space when new space is full and the object is not a large object.
3633 AllocationSpace retry_space =
3634 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3636 { MaybeObject* maybe_result =
3637 AllocateRaw(map->instance_size(), space, retry_space);
3638 if (!maybe_result->ToObject(&result)) return maybe_result;
3640 // No need for write barrier since object is white and map is in old space.
3641 HeapObject::cast(result)->set_map_no_write_barrier(map);
3646 void Heap::InitializeFunction(JSFunction* function,
3647 SharedFunctionInfo* shared,
3648 Object* prototype) {
3649 ASSERT(!prototype->IsMap());
3650 function->initialize_properties();
3651 function->initialize_elements();
3652 function->set_shared(shared);
3653 function->set_code(shared->code());
3654 function->set_prototype_or_initial_map(prototype);
3655 function->set_context(undefined_value());
3656 function->set_literals_or_bindings(empty_fixed_array());
3657 function->set_next_function_link(undefined_value());
3661 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3662 // Allocate the prototype. Make sure to use the object function
3663 // from the function's context, since the function can be from a
3664 // different context.
3665 JSFunction* object_function =
3666 function->context()->global_context()->object_function();
3668 // Each function prototype gets a copy of the object function map.
3669 // This avoid unwanted sharing of maps between prototypes of different
3672 ASSERT(object_function->has_initial_map());
3673 { MaybeObject* maybe_map =
3674 object_function->initial_map()->CopyDropTransitions(
3675 DescriptorArray::MAY_BE_SHARED);
3676 if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3679 { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3680 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3682 // When creating the prototype for the function we must set its
3683 // constructor to the function.
3685 { MaybeObject* maybe_result =
3686 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3687 constructor_symbol(), function, DONT_ENUM);
3688 if (!maybe_result->ToObject(&result)) return maybe_result;
3694 MaybeObject* Heap::AllocateFunction(Map* function_map,
3695 SharedFunctionInfo* shared,
3697 PretenureFlag pretenure) {
3698 AllocationSpace space =
3699 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3701 { MaybeObject* maybe_result = Allocate(function_map, space);
3702 if (!maybe_result->ToObject(&result)) return maybe_result;
3704 InitializeFunction(JSFunction::cast(result), shared, prototype);
3709 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3710 // To get fast allocation and map sharing for arguments objects we
3711 // allocate them based on an arguments boilerplate.
3713 JSObject* boilerplate;
3714 int arguments_object_size;
3715 bool strict_mode_callee = callee->IsJSFunction() &&
3716 !JSFunction::cast(callee)->shared()->is_classic_mode();
3717 if (strict_mode_callee) {
3719 isolate()->context()->global_context()->
3720 strict_mode_arguments_boilerplate();
3721 arguments_object_size = kArgumentsObjectSizeStrict;
3724 isolate()->context()->global_context()->arguments_boilerplate();
3725 arguments_object_size = kArgumentsObjectSize;
3728 // This calls Copy directly rather than using Heap::AllocateRaw so we
3729 // duplicate the check here.
3730 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3732 // Check that the size of the boilerplate matches our
3733 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3734 // on the size being a known constant.
3735 ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3737 // Do the allocation.
3739 { MaybeObject* maybe_result =
3740 AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3741 if (!maybe_result->ToObject(&result)) return maybe_result;
3744 // Copy the content. The arguments boilerplate doesn't have any
3745 // fields that point to new space so it's safe to skip the write
3747 CopyBlock(HeapObject::cast(result)->address(),
3748 boilerplate->address(),
3749 JSObject::kHeaderSize);
3751 // Set the length property.
3752 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3753 Smi::FromInt(length),
3754 SKIP_WRITE_BARRIER);
3755 // Set the callee property for non-strict mode arguments object only.
3756 if (!strict_mode_callee) {
3757 JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3761 // Check the state of the object
3762 ASSERT(JSObject::cast(result)->HasFastProperties());
3763 ASSERT(JSObject::cast(result)->HasFastObjectElements());
3769 static bool HasDuplicates(DescriptorArray* descriptors) {
3770 int count = descriptors->number_of_descriptors();
3772 String* prev_key = descriptors->GetKey(0);
3773 for (int i = 1; i != count; i++) {
3774 String* current_key = descriptors->GetKey(i);
3775 if (prev_key == current_key) return true;
3776 prev_key = current_key;
3783 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3784 ASSERT(!fun->has_initial_map());
3786 // First create a new map with the size and number of in-object properties
3787 // suggested by the function.
3788 int instance_size = fun->shared()->CalculateInstanceSize();
3789 int in_object_properties = fun->shared()->CalculateInObjectProperties();
3791 { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3792 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3795 // Fetch or allocate prototype.
3797 if (fun->has_instance_prototype()) {
3798 prototype = fun->instance_prototype();
3800 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3801 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3804 Map* map = Map::cast(map_obj);
3805 map->set_inobject_properties(in_object_properties);
3806 map->set_unused_property_fields(in_object_properties);
3807 map->set_prototype(prototype);
3808 ASSERT(map->has_fast_object_elements());
3810 // If the function has only simple this property assignments add
3811 // field descriptors for these to the initial map as the object
3812 // cannot be constructed without having these properties. Guard by
3813 // the inline_new flag so we only change the map if we generate a
3814 // specialized construct stub.
3815 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3816 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3817 int count = fun->shared()->this_property_assignments_count();
3818 if (count > in_object_properties) {
3819 // Inline constructor can only handle inobject properties.
3820 fun->shared()->ForbidInlineConstructor();
3822 DescriptorArray* descriptors;
3823 { MaybeObject* maybe_descriptors_obj =
3824 DescriptorArray::Allocate(count, DescriptorArray::MAY_BE_SHARED);
3825 if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
3826 return maybe_descriptors_obj;
3829 DescriptorArray::WhitenessWitness witness(descriptors);
3830 for (int i = 0; i < count; i++) {
3831 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3832 ASSERT(name->IsSymbol());
3833 FieldDescriptor field(name, i, NONE);
3834 field.SetEnumerationIndex(i);
3835 descriptors->Set(i, &field, witness);
3837 descriptors->SetNextEnumerationIndex(count);
3838 descriptors->SortUnchecked(witness);
3840 // The descriptors may contain duplicates because the compiler does not
3841 // guarantee the uniqueness of property names (it would have required
3842 // quadratic time). Once the descriptors are sorted we can check for
3843 // duplicates in linear time.
3844 if (HasDuplicates(descriptors)) {
3845 fun->shared()->ForbidInlineConstructor();
3847 map->set_instance_descriptors(descriptors);
3848 map->set_pre_allocated_property_fields(count);
3849 map->set_unused_property_fields(in_object_properties - count);
3854 fun->shared()->StartInobjectSlackTracking(map);
3860 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3861 FixedArray* properties,
3863 obj->set_properties(properties);
3864 obj->initialize_elements();
3865 // TODO(1240798): Initialize the object's body using valid initial values
3866 // according to the object's initial map. For example, if the map's
3867 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3868 // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3869 // fixed array (e.g. Heap::empty_fixed_array()). Currently, the object
3870 // verification code has to cope with (temporarily) invalid objects. See
3871 // for example, JSArray::JSArrayVerify).
3873 // We cannot always fill with one_pointer_filler_map because objects
3874 // created from API functions expect their internal fields to be initialized
3875 // with undefined_value.
3876 // Pre-allocated fields need to be initialized with undefined_value as well
3877 // so that object accesses before the constructor completes (e.g. in the
3878 // debugger) will not cause a crash.
3879 if (map->constructor()->IsJSFunction() &&
3880 JSFunction::cast(map->constructor())->shared()->
3881 IsInobjectSlackTrackingInProgress()) {
3882 // We might want to shrink the object later.
3883 ASSERT(obj->GetInternalFieldCount() == 0);
3884 filler = Heap::one_pointer_filler_map();
3886 filler = Heap::undefined_value();
3888 obj->InitializeBody(map, Heap::undefined_value(), filler);
3892 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3893 // JSFunctions should be allocated using AllocateFunction to be
3894 // properly initialized.
3895 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3897 // Both types of global objects should be allocated using
3898 // AllocateGlobalObject to be properly initialized.
3899 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3900 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3902 // Allocate the backing storage for the properties.
3904 map->pre_allocated_property_fields() +
3905 map->unused_property_fields() -
3906 map->inobject_properties();
3907 ASSERT(prop_size >= 0);
3909 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3910 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3913 // Allocate the JSObject.
3914 AllocationSpace space =
3915 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3916 if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
3918 { MaybeObject* maybe_obj = Allocate(map, space);
3919 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3922 // Initialize the JSObject.
3923 InitializeJSObjectFromMap(JSObject::cast(obj),
3924 FixedArray::cast(properties),
3926 ASSERT(JSObject::cast(obj)->HasFastSmiOrObjectElements());
3931 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3932 PretenureFlag pretenure) {
3933 // Allocate the initial map if absent.
3934 if (!constructor->has_initial_map()) {
3935 Object* initial_map;
3936 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3937 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3939 constructor->set_initial_map(Map::cast(initial_map));
3940 Map::cast(initial_map)->set_constructor(constructor);
3942 // Allocate the object based on the constructors initial map.
3943 MaybeObject* result = AllocateJSObjectFromMap(
3944 constructor->initial_map(), pretenure);
3946 // Make sure result is NOT a global object if valid.
3947 Object* non_failure;
3948 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3954 MaybeObject* Heap::AllocateJSModule() {
3955 // Allocate a fresh map. Modules do not have a prototype.
3957 MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
3958 if (!maybe_map->To(&map)) return maybe_map;
3959 // Allocate the object based on the map.
3960 return AllocateJSObjectFromMap(map, TENURED);
3964 MaybeObject* Heap::AllocateJSArrayAndStorage(
3965 ElementsKind elements_kind,
3968 ArrayStorageAllocationMode mode,
3969 PretenureFlag pretenure) {
3970 ASSERT(capacity >= length);
3971 if (length != 0 && mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE) {
3972 elements_kind = GetHoleyElementsKind(elements_kind);
3974 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3976 if (!maybe_array->To(&array)) return maybe_array;
3978 if (capacity == 0) {
3979 array->set_length(Smi::FromInt(0));
3980 array->set_elements(empty_fixed_array());
3984 FixedArrayBase* elms;
3985 MaybeObject* maybe_elms = NULL;
3986 if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3987 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3988 maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3990 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3991 maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3994 ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
3995 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3996 maybe_elms = AllocateUninitializedFixedArray(capacity);
3998 ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3999 maybe_elms = AllocateFixedArrayWithHoles(capacity);
4002 if (!maybe_elms->To(&elms)) return maybe_elms;
4004 array->set_elements(elms);
4005 array->set_length(Smi::FromInt(length));
4010 MaybeObject* Heap::AllocateJSArrayWithElements(
4011 FixedArrayBase* elements,
4012 ElementsKind elements_kind,
4013 PretenureFlag pretenure) {
4014 MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4016 if (!maybe_array->To(&array)) return maybe_array;
4018 array->set_elements(elements);
4019 array->set_length(Smi::FromInt(elements->length()));
4020 array->ValidateElements();
4025 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
4027 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4028 // maps. Will probably depend on the identity of the handler object, too.
4030 MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
4031 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4032 map->set_prototype(prototype);
4034 // Allocate the proxy object.
4036 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4037 if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
4038 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4039 result->set_handler(handler);
4040 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4045 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
4047 Object* construct_trap,
4048 Object* prototype) {
4050 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4051 // maps. Will probably depend on the identity of the handler object, too.
4053 MaybeObject* maybe_map_obj =
4054 AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
4055 if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4056 map->set_prototype(prototype);
4058 // Allocate the proxy object.
4059 JSFunctionProxy* result;
4060 MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4061 if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
4062 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4063 result->set_handler(handler);
4064 result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4065 result->set_call_trap(call_trap);
4066 result->set_construct_trap(construct_trap);
4071 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
4072 ASSERT(constructor->has_initial_map());
4073 Map* map = constructor->initial_map();
4075 // Make sure no field properties are described in the initial map.
4076 // This guarantees us that normalizing the properties does not
4077 // require us to change property values to JSGlobalPropertyCells.
4078 ASSERT(map->NextFreePropertyIndex() == 0);
4080 // Make sure we don't have a ton of pre-allocated slots in the
4081 // global objects. They will be unused once we normalize the object.
4082 ASSERT(map->unused_property_fields() == 0);
4083 ASSERT(map->inobject_properties() == 0);
4085 // Initial size of the backing store to avoid resize of the storage during
4086 // bootstrapping. The size differs between the JS global object ad the
4088 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
4090 // Allocate a dictionary object for backing storage.
4092 { MaybeObject* maybe_obj =
4093 StringDictionary::Allocate(
4094 map->NumberOfDescribedProperties() * 2 + initial_size);
4095 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4097 StringDictionary* dictionary = StringDictionary::cast(obj);
4099 // The global object might be created from an object template with accessors.
4100 // Fill these accessors into the dictionary.
4101 DescriptorArray* descs = map->instance_descriptors();
4102 for (int i = 0; i < descs->number_of_descriptors(); i++) {
4103 PropertyDetails details = descs->GetDetails(i);
4104 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
4106 PropertyDetails(details.attributes(), CALLBACKS, details.index());
4107 Object* value = descs->GetCallbacksObject(i);
4108 { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
4109 if (!maybe_value->ToObject(&value)) return maybe_value;
4113 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
4114 if (!maybe_result->ToObject(&result)) return maybe_result;
4116 dictionary = StringDictionary::cast(result);
4119 // Allocate the global object and initialize it with the backing store.
4120 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
4121 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4123 JSObject* global = JSObject::cast(obj);
4124 InitializeJSObjectFromMap(global, dictionary, map);
4126 // Create a new map for the global object.
4127 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
4128 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4130 Map* new_map = Map::cast(obj);
4132 // Set up the global object as a normalized object.
4133 global->set_map(new_map);
4134 global->map()->clear_instance_descriptors();
4135 global->set_properties(dictionary);
4137 // Make sure result is a global object with properties in dictionary.
4138 ASSERT(global->IsGlobalObject());
4139 ASSERT(!global->HasFastProperties());
4144 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4145 // Never used to copy functions. If functions need to be copied we
4146 // have to be careful to clear the literals array.
4147 SLOW_ASSERT(!source->IsJSFunction());
4150 Map* map = source->map();
4151 int object_size = map->instance_size();
4154 WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4156 // If we're forced to always allocate, we use the general allocation
4157 // functions which may leave us with an object in old space.
4158 if (always_allocate()) {
4159 { MaybeObject* maybe_clone =
4160 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4161 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4163 Address clone_address = HeapObject::cast(clone)->address();
4164 CopyBlock(clone_address,
4167 // Update write barrier for all fields that lie beyond the header.
4168 RecordWrites(clone_address,
4169 JSObject::kHeaderSize,
4170 (object_size - JSObject::kHeaderSize) / kPointerSize);
4172 wb_mode = SKIP_WRITE_BARRIER;
4173 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4174 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4176 SLOW_ASSERT(InNewSpace(clone));
4177 // Since we know the clone is allocated in new space, we can copy
4178 // the contents without worrying about updating the write barrier.
4179 CopyBlock(HeapObject::cast(clone)->address(),
4185 JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4186 FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4187 FixedArray* properties = FixedArray::cast(source->properties());
4188 // Update elements if necessary.
4189 if (elements->length() > 0) {
4191 { MaybeObject* maybe_elem;
4192 if (elements->map() == fixed_cow_array_map()) {
4193 maybe_elem = FixedArray::cast(elements);
4194 } else if (source->HasFastDoubleElements()) {
4195 maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4197 maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4199 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4201 JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4203 // Update properties if necessary.
4204 if (properties->length() > 0) {
4206 { MaybeObject* maybe_prop = CopyFixedArray(properties);
4207 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4209 JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4211 // Return the new clone.
4216 MaybeObject* Heap::ReinitializeJSReceiver(
4217 JSReceiver* object, InstanceType type, int size) {
4218 ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4220 // Allocate fresh map.
4221 // TODO(rossberg): Once we optimize proxies, cache these maps.
4223 MaybeObject* maybe = AllocateMap(type, size);
4224 if (!maybe->To<Map>(&map)) return maybe;
4226 // Check that the receiver has at least the size of the fresh object.
4227 int size_difference = object->map()->instance_size() - map->instance_size();
4228 ASSERT(size_difference >= 0);
4230 map->set_prototype(object->map()->prototype());
4232 // Allocate the backing storage for the properties.
4233 int prop_size = map->unused_property_fields() - map->inobject_properties();
4235 maybe = AllocateFixedArray(prop_size, TENURED);
4236 if (!maybe->ToObject(&properties)) return maybe;
4238 // Functions require some allocation, which might fail here.
4239 SharedFunctionInfo* shared = NULL;
4240 if (type == JS_FUNCTION_TYPE) {
4242 maybe = LookupAsciiSymbol("<freezing call trap>");
4243 if (!maybe->To<String>(&name)) return maybe;
4244 maybe = AllocateSharedFunctionInfo(name);
4245 if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4248 // Because of possible retries of this function after failure,
4249 // we must NOT fail after this point, where we have changed the type!
4251 // Reset the map for the object.
4252 object->set_map(map);
4253 JSObject* jsobj = JSObject::cast(object);
4255 // Reinitialize the object from the constructor map.
4256 InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4258 // Functions require some minimal initialization.
4259 if (type == JS_FUNCTION_TYPE) {
4260 map->set_function_with_prototype(true);
4261 InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4262 JSFunction::cast(object)->set_context(
4263 isolate()->context()->global_context());
4266 // Put in filler if the new object is smaller than the old.
4267 if (size_difference > 0) {
4268 CreateFillerObjectAt(
4269 object->address() + map->instance_size(), size_difference);
4276 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4277 JSGlobalProxy* object) {
4278 ASSERT(constructor->has_initial_map());
4279 Map* map = constructor->initial_map();
4281 // Check that the already allocated object has the same size and type as
4282 // objects allocated using the constructor.
4283 ASSERT(map->instance_size() == object->map()->instance_size());
4284 ASSERT(map->instance_type() == object->map()->instance_type());
4286 // Allocate the backing storage for the properties.
4287 int prop_size = map->unused_property_fields() - map->inobject_properties();
4289 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4290 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4293 // Reset the map for the object.
4294 object->set_map(constructor->initial_map());
4296 // Reinitialize the object from the constructor map.
4297 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4302 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4303 PretenureFlag pretenure) {
4304 if (string.length() == 1) {
4305 return Heap::LookupSingleCharacterStringFromCode(string[0]);
4308 { MaybeObject* maybe_result =
4309 AllocateRawAsciiString(string.length(), pretenure);
4310 if (!maybe_result->ToObject(&result)) return maybe_result;
4313 // Copy the characters into the new object.
4314 SeqAsciiString* string_result = SeqAsciiString::cast(result);
4315 for (int i = 0; i < string.length(); i++) {
4316 string_result->SeqAsciiStringSet(i, string[i]);
4322 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4323 PretenureFlag pretenure) {
4324 // Count the number of characters in the UTF-8 string and check if
4325 // it is an ASCII string.
4326 Access<UnicodeCache::Utf8Decoder>
4327 decoder(isolate_->unicode_cache()->utf8_decoder());
4328 decoder->Reset(string.start(), string.length());
4330 while (decoder->has_more()) {
4331 uint32_t r = decoder->GetNext();
4332 if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4340 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4341 if (!maybe_result->ToObject(&result)) return maybe_result;
4344 // Convert and copy the characters into the new object.
4345 String* string_result = String::cast(result);
4346 decoder->Reset(string.start(), string.length());
4349 uint32_t r = decoder->GetNext();
4350 if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4351 string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4352 string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4354 string_result->Set(i++, r);
4361 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4362 PretenureFlag pretenure) {
4363 // Check if the string is an ASCII string.
4364 MaybeObject* maybe_result;
4365 if (String::IsAscii(string.start(), string.length())) {
4366 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4367 } else { // It's not an ASCII string.
4368 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4371 if (!maybe_result->ToObject(&result)) return maybe_result;
4373 // Copy the characters into the new object, which may be either ASCII or
4375 String* string_result = String::cast(result);
4376 for (int i = 0; i < string.length(); i++) {
4377 string_result->Set(i, string[i]);
4383 Map* Heap::SymbolMapForString(String* string) {
4384 // If the string is in new space it cannot be used as a symbol.
4385 if (InNewSpace(string)) return NULL;
4387 // Find the corresponding symbol map for strings.
4388 switch (string->map()->instance_type()) {
4389 case STRING_TYPE: return symbol_map();
4390 case ASCII_STRING_TYPE: return ascii_symbol_map();
4391 case CONS_STRING_TYPE: return cons_symbol_map();
4392 case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4393 case EXTERNAL_STRING_TYPE: return external_symbol_map();
4394 case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4395 case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4396 return external_symbol_with_ascii_data_map();
4397 case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4398 case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4399 return short_external_ascii_symbol_map();
4400 case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4401 return short_external_symbol_with_ascii_data_map();
4402 default: return NULL; // No match found.
4407 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4409 uint32_t hash_field) {
4411 // Ensure the chars matches the number of characters in the buffer.
4412 ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4413 // Determine whether the string is ASCII.
4414 bool is_ascii = true;
4415 while (buffer->has_more()) {
4416 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4423 // Compute map and object size.
4428 if (chars > SeqAsciiString::kMaxLength) {
4429 return Failure::OutOfMemoryException();
4431 map = ascii_symbol_map();
4432 size = SeqAsciiString::SizeFor(chars);
4434 if (chars > SeqTwoByteString::kMaxLength) {
4435 return Failure::OutOfMemoryException();
4438 size = SeqTwoByteString::SizeFor(chars);
4443 { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4444 ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4445 : old_data_space_->AllocateRaw(size);
4446 if (!maybe_result->ToObject(&result)) return maybe_result;
4449 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4450 // Set length and hash fields of the allocated string.
4451 String* answer = String::cast(result);
4452 answer->set_length(chars);
4453 answer->set_hash_field(hash_field);
4455 ASSERT_EQ(size, answer->Size());
4457 // Fill in the characters.
4460 uint32_t character = buffer->GetNext();
4461 if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4462 answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4463 answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4465 answer->Set(i++, character);
4472 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4473 if (length < 0 || length > SeqAsciiString::kMaxLength) {
4474 return Failure::OutOfMemoryException();
4477 int size = SeqAsciiString::SizeFor(length);
4478 ASSERT(size <= SeqAsciiString::kMaxSize);
4480 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4481 AllocationSpace retry_space = OLD_DATA_SPACE;
4483 if (space == NEW_SPACE) {
4484 if (size > kMaxObjectSizeInNewSpace) {
4485 // Allocate in large object space, retry space will be ignored.
4487 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4488 // Allocate in new space, retry in large object space.
4489 retry_space = LO_SPACE;
4491 } else if (space == OLD_DATA_SPACE &&
4492 size > Page::kMaxNonCodeHeapObjectSize) {
4496 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4497 if (!maybe_result->ToObject(&result)) return maybe_result;
4500 // Partially initialize the object.
4501 HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4502 String::cast(result)->set_length(length);
4503 String::cast(result)->set_hash_field(String::kEmptyHashField);
4504 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4507 if (FLAG_verify_heap) {
4508 // Initialize string's content to ensure ASCII-ness (character range 0-127)
4509 // as required when verifying the heap.
4510 char* dest = SeqAsciiString::cast(result)->GetChars();
4511 memset(dest, 0x0F, length * kCharSize);
4519 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4520 PretenureFlag pretenure) {
4521 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4522 return Failure::OutOfMemoryException();
4524 int size = SeqTwoByteString::SizeFor(length);
4525 ASSERT(size <= SeqTwoByteString::kMaxSize);
4526 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4527 AllocationSpace retry_space = OLD_DATA_SPACE;
4529 if (space == NEW_SPACE) {
4530 if (size > kMaxObjectSizeInNewSpace) {
4531 // Allocate in large object space, retry space will be ignored.
4533 } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4534 // Allocate in new space, retry in large object space.
4535 retry_space = LO_SPACE;
4537 } else if (space == OLD_DATA_SPACE &&
4538 size > Page::kMaxNonCodeHeapObjectSize) {
4542 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4543 if (!maybe_result->ToObject(&result)) return maybe_result;
4546 // Partially initialize the object.
4547 HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4548 String::cast(result)->set_length(length);
4549 String::cast(result)->set_hash_field(String::kEmptyHashField);
4550 ASSERT_EQ(size, HeapObject::cast(result)->Size());
4555 MaybeObject* Heap::AllocateJSArray(
4556 ElementsKind elements_kind,
4557 PretenureFlag pretenure) {
4558 Context* global_context = isolate()->context()->global_context();
4559 JSFunction* array_function = global_context->array_function();
4560 Map* map = array_function->initial_map();
4561 Object* maybe_map_array = global_context->js_array_maps();
4562 if (!maybe_map_array->IsUndefined()) {
4563 Object* maybe_transitioned_map =
4564 FixedArray::cast(maybe_map_array)->get(elements_kind);
4565 if (!maybe_transitioned_map->IsUndefined()) {
4566 map = Map::cast(maybe_transitioned_map);
4570 return AllocateJSObjectFromMap(map, pretenure);
4574 MaybeObject* Heap::AllocateEmptyFixedArray() {
4575 int size = FixedArray::SizeFor(0);
4577 { MaybeObject* maybe_result =
4578 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4579 if (!maybe_result->ToObject(&result)) return maybe_result;
4581 // Initialize the object.
4582 reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4584 reinterpret_cast<FixedArray*>(result)->set_length(0);
4589 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4590 if (length < 0 || length > FixedArray::kMaxLength) {
4591 return Failure::OutOfMemoryException();
4594 // Use the general function if we're forced to always allocate.
4595 if (always_allocate()) return AllocateFixedArray(length, TENURED);
4596 // Allocate the raw data for a fixed array.
4597 int size = FixedArray::SizeFor(length);
4598 return size <= kMaxObjectSizeInNewSpace
4599 ? new_space_.AllocateRaw(size)
4600 : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4604 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4605 int len = src->length();
4607 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4608 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4610 if (InNewSpace(obj)) {
4611 HeapObject* dst = HeapObject::cast(obj);
4612 dst->set_map_no_write_barrier(map);
4613 CopyBlock(dst->address() + kPointerSize,
4614 src->address() + kPointerSize,
4615 FixedArray::SizeFor(len) - kPointerSize);
4618 HeapObject::cast(obj)->set_map_no_write_barrier(map);
4619 FixedArray* result = FixedArray::cast(obj);
4620 result->set_length(len);
4623 AssertNoAllocation no_gc;
4624 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4625 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4630 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4632 int len = src->length();
4634 { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4635 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4637 HeapObject* dst = HeapObject::cast(obj);
4638 dst->set_map_no_write_barrier(map);
4640 dst->address() + FixedDoubleArray::kLengthOffset,
4641 src->address() + FixedDoubleArray::kLengthOffset,
4642 FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4647 MaybeObject* Heap::AllocateFixedArray(int length) {
4648 ASSERT(length >= 0);
4649 if (length == 0) return empty_fixed_array();
4651 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4652 if (!maybe_result->ToObject(&result)) return maybe_result;
4654 // Initialize header.
4655 FixedArray* array = reinterpret_cast<FixedArray*>(result);
4656 array->set_map_no_write_barrier(fixed_array_map());
4657 array->set_length(length);
4659 ASSERT(!InNewSpace(undefined_value()));
4660 MemsetPointer(array->data_start(), undefined_value(), length);
4665 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4666 if (length < 0 || length > FixedArray::kMaxLength) {
4667 return Failure::OutOfMemoryException();
4670 AllocationSpace space =
4671 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4672 int size = FixedArray::SizeFor(length);
4673 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4674 // Too big for new space.
4676 } else if (space == OLD_POINTER_SPACE &&
4677 size > Page::kMaxNonCodeHeapObjectSize) {
4678 // Too big for old pointer space.
4682 AllocationSpace retry_space =
4683 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4685 return AllocateRaw(size, space, retry_space);
4689 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4692 PretenureFlag pretenure,
4694 ASSERT(length >= 0);
4695 ASSERT(heap->empty_fixed_array()->IsFixedArray());
4696 if (length == 0) return heap->empty_fixed_array();
4698 ASSERT(!heap->InNewSpace(filler));
4700 { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4701 if (!maybe_result->ToObject(&result)) return maybe_result;
4704 HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4705 FixedArray* array = FixedArray::cast(result);
4706 array->set_length(length);
4707 MemsetPointer(array->data_start(), filler, length);
4712 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4713 return AllocateFixedArrayWithFiller(this,
4720 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4721 PretenureFlag pretenure) {
4722 return AllocateFixedArrayWithFiller(this,
4729 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4730 if (length == 0) return empty_fixed_array();
4733 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4734 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4737 reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4739 FixedArray::cast(obj)->set_length(length);
4744 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4745 int size = FixedDoubleArray::SizeFor(0);
4747 { MaybeObject* maybe_result =
4748 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4749 if (!maybe_result->ToObject(&result)) return maybe_result;
4751 // Initialize the object.
4752 reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4753 fixed_double_array_map());
4754 reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4759 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4761 PretenureFlag pretenure) {
4762 if (length == 0) return empty_fixed_array();
4764 Object* elements_object;
4765 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4766 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4767 FixedDoubleArray* elements =
4768 reinterpret_cast<FixedDoubleArray*>(elements_object);
4770 elements->set_map_no_write_barrier(fixed_double_array_map());
4771 elements->set_length(length);
4776 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4778 PretenureFlag pretenure) {
4779 if (length == 0) return empty_fixed_array();
4781 Object* elements_object;
4782 MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4783 if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4784 FixedDoubleArray* elements =
4785 reinterpret_cast<FixedDoubleArray*>(elements_object);
4787 for (int i = 0; i < length; ++i) {
4788 elements->set_the_hole(i);
4791 elements->set_map_no_write_barrier(fixed_double_array_map());
4792 elements->set_length(length);
4797 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4798 PretenureFlag pretenure) {
4799 if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4800 return Failure::OutOfMemoryException();
4803 AllocationSpace space =
4804 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4805 int size = FixedDoubleArray::SizeFor(length);
4807 #ifndef V8_HOST_ARCH_64_BIT
4808 size += kPointerSize;
4811 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4812 // Too big for new space.
4814 } else if (space == OLD_DATA_SPACE &&
4815 size > Page::kMaxNonCodeHeapObjectSize) {
4816 // Too big for old data space.
4820 AllocationSpace retry_space =
4821 (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4824 { MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
4825 if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
4828 return EnsureDoubleAligned(this, object, size);
4832 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4834 { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4835 if (!maybe_result->ToObject(&result)) return maybe_result;
4837 reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4839 ASSERT(result->IsHashTable());
4844 MaybeObject* Heap::AllocateGlobalContext() {
4846 { MaybeObject* maybe_result =
4847 AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4848 if (!maybe_result->ToObject(&result)) return maybe_result;
4850 Context* context = reinterpret_cast<Context*>(result);
4851 context->set_map_no_write_barrier(global_context_map());
4852 context->set_js_array_maps(undefined_value());
4853 ASSERT(context->IsGlobalContext());
4854 ASSERT(result->IsContext());
4859 MaybeObject* Heap::AllocateModuleContext(Context* previous,
4860 ScopeInfo* scope_info) {
4862 { MaybeObject* maybe_result =
4863 AllocateFixedArrayWithHoles(scope_info->ContextLength(), TENURED);
4864 if (!maybe_result->ToObject(&result)) return maybe_result;
4866 Context* context = reinterpret_cast<Context*>(result);
4867 context->set_map_no_write_barrier(module_context_map());
4868 context->set_previous(previous);
4869 context->set_extension(scope_info);
4870 context->set_global(previous->global());
4875 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4876 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4878 { MaybeObject* maybe_result = AllocateFixedArray(length);
4879 if (!maybe_result->ToObject(&result)) return maybe_result;
4881 Context* context = reinterpret_cast<Context*>(result);
4882 context->set_map_no_write_barrier(function_context_map());
4883 context->set_closure(function);
4884 context->set_previous(function->context());
4885 context->set_extension(NULL);
4886 context->set_global(function->context()->global());
4891 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4894 Object* thrown_object) {
4895 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4897 { MaybeObject* maybe_result =
4898 AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4899 if (!maybe_result->ToObject(&result)) return maybe_result;
4901 Context* context = reinterpret_cast<Context*>(result);
4902 context->set_map_no_write_barrier(catch_context_map());
4903 context->set_closure(function);
4904 context->set_previous(previous);
4905 context->set_extension(name);
4906 context->set_global(previous->global());
4907 context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4912 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4914 JSObject* extension) {
4916 { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4917 if (!maybe_result->ToObject(&result)) return maybe_result;
4919 Context* context = reinterpret_cast<Context*>(result);
4920 context->set_map_no_write_barrier(with_context_map());
4921 context->set_closure(function);
4922 context->set_previous(previous);
4923 context->set_extension(extension);
4924 context->set_global(previous->global());
4929 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4931 ScopeInfo* scope_info) {
4933 { MaybeObject* maybe_result =
4934 AllocateFixedArrayWithHoles(scope_info->ContextLength());
4935 if (!maybe_result->ToObject(&result)) return maybe_result;
4937 Context* context = reinterpret_cast<Context*>(result);
4938 context->set_map_no_write_barrier(block_context_map());
4939 context->set_closure(function);
4940 context->set_previous(previous);
4941 context->set_extension(scope_info);
4942 context->set_global(previous->global());
4947 MaybeObject* Heap::AllocateScopeInfo(int length) {
4948 FixedArray* scope_info;
4949 MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4950 if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4951 scope_info->set_map_no_write_barrier(scope_info_map());
4956 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4959 #define MAKE_CASE(NAME, Name, name) \
4960 case NAME##_TYPE: map = name##_map(); break;
4961 STRUCT_LIST(MAKE_CASE)
4965 return Failure::InternalError();
4967 int size = map->instance_size();
4968 AllocationSpace space =
4969 (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
4971 { MaybeObject* maybe_result = Allocate(map, space);
4972 if (!maybe_result->ToObject(&result)) return maybe_result;
4974 Struct::cast(result)->InitializeBody(size);
4979 bool Heap::IsHeapIterable() {
4980 return (!old_pointer_space()->was_swept_conservatively() &&
4981 !old_data_space()->was_swept_conservatively());
4985 void Heap::EnsureHeapIsIterable() {
4986 ASSERT(IsAllocationAllowed());
4987 if (!IsHeapIterable()) {
4988 CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
4990 ASSERT(IsHeapIterable());
4994 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
4995 incremental_marking()->Step(step_size,
4996 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
4998 if (incremental_marking()->IsComplete()) {
4999 bool uncommit = false;
5000 if (gc_count_at_last_idle_gc_ == gc_count_) {
5001 // No GC since the last full GC, the mutator is probably not active.
5002 isolate_->compilation_cache()->Clear();
5005 CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
5006 gc_count_at_last_idle_gc_ = gc_count_;
5008 new_space_.Shrink();
5009 UncommitFromSpace();
5015 bool Heap::IdleNotification(int hint) {
5016 // Hints greater than this value indicate that
5017 // the embedder is requesting a lot of GC work.
5018 const int kMaxHint = 1000;
5019 // Minimal hint that allows to do full GC.
5020 const int kMinHintForFullGC = 100;
5021 intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
5022 // The size factor is in range [5..250]. The numbers here are chosen from
5023 // experiments. If you changes them, make sure to test with
5024 // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
5025 intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
5027 if (contexts_disposed_ > 0) {
5028 if (hint >= kMaxHint) {
5029 // The embedder is requesting a lot of GC work after context disposal,
5030 // we age inline caches so that they don't keep objects from
5031 // the old context alive.
5034 int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
5035 if (hint >= mark_sweep_time && !FLAG_expose_gc &&
5036 incremental_marking()->IsStopped()) {
5037 HistogramTimerScope scope(isolate_->counters()->gc_context());
5038 CollectAllGarbage(kReduceMemoryFootprintMask,
5039 "idle notification: contexts disposed");
5041 AdvanceIdleIncrementalMarking(step_size);
5042 contexts_disposed_ = 0;
5044 // Make sure that we have no pending context disposals.
5045 // Take into account that we might have decided to delay full collection
5046 // because incremental marking is in progress.
5047 ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
5048 // After context disposal there is likely a lot of garbage remaining, reset
5049 // the idle notification counters in order to trigger more incremental GCs
5050 // on subsequent idle notifications.
5055 if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
5056 return IdleGlobalGC();
5059 // By doing small chunks of GC work in each IdleNotification,
5060 // perform a round of incremental GCs and after that wait until
5061 // the mutator creates enough garbage to justify a new round.
5062 // An incremental GC progresses as follows:
5063 // 1. many incremental marking steps,
5064 // 2. one old space mark-sweep-compact,
5065 // 3. many lazy sweep steps.
5066 // Use mark-sweep-compact events to count incremental GCs in a round.
5069 if (incremental_marking()->IsStopped()) {
5070 if (!IsSweepingComplete() &&
5071 !AdvanceSweepers(static_cast<int>(step_size))) {
5076 if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5077 if (EnoughGarbageSinceLastIdleRound()) {
5084 int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
5085 mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
5086 ms_count_at_last_idle_notification_ = ms_count_;
5088 int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound -
5089 mark_sweeps_since_idle_round_started_;
5091 if (remaining_mark_sweeps <= 0) {
5096 if (incremental_marking()->IsStopped()) {
5097 // If there are no more than two GCs left in this idle round and we are
5098 // allowed to do a full GC, then make those GCs full in order to compact
5100 // TODO(ulan): Once we enable code compaction for incremental marking,
5101 // we can get rid of this special case and always start incremental marking.
5102 if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) {
5103 CollectAllGarbage(kReduceMemoryFootprintMask,
5104 "idle notification: finalize idle round");
5106 incremental_marking()->Start();
5109 if (!incremental_marking()->IsStopped()) {
5110 AdvanceIdleIncrementalMarking(step_size);
5116 bool Heap::IdleGlobalGC() {
5117 static const int kIdlesBeforeScavenge = 4;
5118 static const int kIdlesBeforeMarkSweep = 7;
5119 static const int kIdlesBeforeMarkCompact = 8;
5120 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
5121 static const unsigned int kGCsBetweenCleanup = 4;
5123 if (!last_idle_notification_gc_count_init_) {
5124 last_idle_notification_gc_count_ = gc_count_;
5125 last_idle_notification_gc_count_init_ = true;
5128 bool uncommit = true;
5129 bool finished = false;
5131 // Reset the number of idle notifications received when a number of
5132 // GCs have taken place. This allows another round of cleanup based
5133 // on idle notifications if enough work has been carried out to
5134 // provoke a number of garbage collections.
5135 if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
5136 number_idle_notifications_ =
5137 Min(number_idle_notifications_ + 1, kMaxIdleCount);
5139 number_idle_notifications_ = 0;
5140 last_idle_notification_gc_count_ = gc_count_;
5143 if (number_idle_notifications_ == kIdlesBeforeScavenge) {
5144 CollectGarbage(NEW_SPACE, "idle notification");
5145 new_space_.Shrink();
5146 last_idle_notification_gc_count_ = gc_count_;
5147 } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
5148 // Before doing the mark-sweep collections we clear the
5149 // compilation cache to avoid hanging on to source code and
5150 // generated code for cached functions.
5151 isolate_->compilation_cache()->Clear();
5153 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5154 new_space_.Shrink();
5155 last_idle_notification_gc_count_ = gc_count_;
5157 } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
5158 CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5159 new_space_.Shrink();
5160 last_idle_notification_gc_count_ = gc_count_;
5161 number_idle_notifications_ = 0;
5163 } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
5164 // If we have received more than kIdlesBeforeMarkCompact idle
5165 // notifications we do not perform any cleanup because we don't
5166 // expect to gain much by doing so.
5170 if (uncommit) UncommitFromSpace();
5178 void Heap::Print() {
5179 if (!HasBeenSetUp()) return;
5180 isolate()->PrintStack();
5182 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
5187 void Heap::ReportCodeStatistics(const char* title) {
5188 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5189 PagedSpace::ResetCodeStatistics();
5190 // We do not look for code in new space, map space, or old space. If code
5191 // somehow ends up in those spaces, we would miss it here.
5192 code_space_->CollectCodeStatistics();
5193 lo_space_->CollectCodeStatistics();
5194 PagedSpace::ReportCodeStatistics();
5198 // This function expects that NewSpace's allocated objects histogram is
5199 // populated (via a call to CollectStatistics or else as a side effect of a
5200 // just-completed scavenge collection).
5201 void Heap::ReportHeapStatistics(const char* title) {
5203 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5205 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5206 old_gen_promotion_limit_);
5207 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5208 old_gen_allocation_limit_);
5209 PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5212 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5213 isolate_->global_handles()->PrintStats();
5216 PrintF("Heap statistics : ");
5217 isolate_->memory_allocator()->ReportStatistics();
5218 PrintF("To space : ");
5219 new_space_.ReportStatistics();
5220 PrintF("Old pointer space : ");
5221 old_pointer_space_->ReportStatistics();
5222 PrintF("Old data space : ");
5223 old_data_space_->ReportStatistics();
5224 PrintF("Code space : ");
5225 code_space_->ReportStatistics();
5226 PrintF("Map space : ");
5227 map_space_->ReportStatistics();
5228 PrintF("Cell space : ");
5229 cell_space_->ReportStatistics();
5230 PrintF("Large object space : ");
5231 lo_space_->ReportStatistics();
5232 PrintF(">>>>>> ========================================= >>>>>>\n");
5237 bool Heap::Contains(HeapObject* value) {
5238 return Contains(value->address());
5242 bool Heap::Contains(Address addr) {
5243 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5244 return HasBeenSetUp() &&
5245 (new_space_.ToSpaceContains(addr) ||
5246 old_pointer_space_->Contains(addr) ||
5247 old_data_space_->Contains(addr) ||
5248 code_space_->Contains(addr) ||
5249 map_space_->Contains(addr) ||
5250 cell_space_->Contains(addr) ||
5251 lo_space_->SlowContains(addr));
5255 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5256 return InSpace(value->address(), space);
5260 bool Heap::InSpace(Address addr, AllocationSpace space) {
5261 if (OS::IsOutsideAllocatedSpace(addr)) return false;
5262 if (!HasBeenSetUp()) return false;
5266 return new_space_.ToSpaceContains(addr);
5267 case OLD_POINTER_SPACE:
5268 return old_pointer_space_->Contains(addr);
5269 case OLD_DATA_SPACE:
5270 return old_data_space_->Contains(addr);
5272 return code_space_->Contains(addr);
5274 return map_space_->Contains(addr);
5276 return cell_space_->Contains(addr);
5278 return lo_space_->SlowContains(addr);
5286 void Heap::Verify() {
5287 ASSERT(HasBeenSetUp());
5289 store_buffer()->Verify();
5291 VerifyPointersVisitor visitor;
5292 IterateRoots(&visitor, VISIT_ONLY_STRONG);
5294 new_space_.Verify();
5296 old_pointer_space_->Verify(&visitor);
5297 map_space_->Verify(&visitor);
5299 VerifyPointersVisitor no_dirty_regions_visitor;
5300 old_data_space_->Verify(&no_dirty_regions_visitor);
5301 code_space_->Verify(&no_dirty_regions_visitor);
5302 cell_space_->Verify(&no_dirty_regions_visitor);
5304 lo_space_->Verify();
5306 VerifyNoAccessorPairSharing();
5310 void Heap::VerifyNoAccessorPairSharing() {
5311 // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5312 // that we mark only unmarked pairs, then we clear all marks, restoring the
5313 // initial state. We use the Smi tag of the AccessorPair's getter as the
5314 // marking bit, because we can never see a Smi as the getter.
5315 for (int phase = 0; phase < 2; phase++) {
5316 HeapObjectIterator iter(map_space());
5317 for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5319 DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5320 for (int i = 0; i < descs->number_of_descriptors(); i++) {
5321 if (descs->GetType(i) == CALLBACKS &&
5322 descs->GetValue(i)->IsAccessorPair()) {
5323 AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5324 uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5325 uintptr_t after = (phase == 0) ?
5326 ((before & ~kSmiTagMask) | kSmiTag) :
5327 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5328 CHECK(before != after);
5329 accessors->set_getter(reinterpret_cast<Object*>(after));
5339 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5340 Object* symbol = NULL;
5342 { MaybeObject* maybe_new_table =
5343 symbol_table()->LookupSymbol(string, &symbol);
5344 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5346 // Can't use set_symbol_table because SymbolTable::cast knows that
5347 // SymbolTable is a singleton and checks for identity.
5348 roots_[kSymbolTableRootIndex] = new_table;
5349 ASSERT(symbol != NULL);
5354 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5355 Object* symbol = NULL;
5357 { MaybeObject* maybe_new_table =
5358 symbol_table()->LookupAsciiSymbol(string, &symbol);
5359 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5361 // Can't use set_symbol_table because SymbolTable::cast knows that
5362 // SymbolTable is a singleton and checks for identity.
5363 roots_[kSymbolTableRootIndex] = new_table;
5364 ASSERT(symbol != NULL);
5369 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5372 Object* symbol = NULL;
5374 { MaybeObject* maybe_new_table =
5375 symbol_table()->LookupSubStringAsciiSymbol(string,
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 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5390 Object* symbol = NULL;
5392 { MaybeObject* maybe_new_table =
5393 symbol_table()->LookupTwoByteSymbol(string, &symbol);
5394 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5396 // Can't use set_symbol_table because SymbolTable::cast knows that
5397 // SymbolTable is a singleton and checks for identity.
5398 roots_[kSymbolTableRootIndex] = new_table;
5399 ASSERT(symbol != NULL);
5404 MaybeObject* Heap::LookupSymbol(String* string) {
5405 if (string->IsSymbol()) return string;
5406 Object* symbol = NULL;
5408 { MaybeObject* maybe_new_table =
5409 symbol_table()->LookupString(string, &symbol);
5410 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5412 // Can't use set_symbol_table because SymbolTable::cast knows that
5413 // SymbolTable is a singleton and checks for identity.
5414 roots_[kSymbolTableRootIndex] = new_table;
5415 ASSERT(symbol != NULL);
5420 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5421 if (string->IsSymbol()) {
5425 return symbol_table()->LookupSymbolIfExists(string, symbol);
5430 void Heap::ZapFromSpace() {
5431 NewSpacePageIterator it(new_space_.FromSpaceStart(),
5432 new_space_.FromSpaceEnd());
5433 while (it.has_next()) {
5434 NewSpacePage* page = it.next();
5435 for (Address cursor = page->area_start(), limit = page->area_end();
5437 cursor += kPointerSize) {
5438 Memory::Address_at(cursor) = kFromSpaceZapValue;
5445 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5447 ObjectSlotCallback callback) {
5448 Address slot_address = start;
5450 // We are not collecting slots on new space objects during mutation
5451 // thus we have to scan for pointers to evacuation candidates when we
5452 // promote objects. But we should not record any slots in non-black
5453 // objects. Grey object's slots would be rescanned.
5454 // White object might not survive until the end of collection
5455 // it would be a violation of the invariant to record it's slots.
5456 bool record_slots = false;
5457 if (incremental_marking()->IsCompacting()) {
5458 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5459 record_slots = Marking::IsBlack(mark_bit);
5462 while (slot_address < end) {
5463 Object** slot = reinterpret_cast<Object**>(slot_address);
5464 Object* object = *slot;
5465 // If the store buffer becomes overfull we mark pages as being exempt from
5466 // the store buffer. These pages are scanned to find pointers that point
5467 // to the new space. In that case we may hit newly promoted objects and
5468 // fix the pointers before the promotion queue gets to them. Thus the 'if'.
5469 if (object->IsHeapObject()) {
5470 if (Heap::InFromSpace(object)) {
5471 callback(reinterpret_cast<HeapObject**>(slot),
5472 HeapObject::cast(object));
5473 Object* new_object = *slot;
5474 if (InNewSpace(new_object)) {
5475 SLOW_ASSERT(Heap::InToSpace(new_object));
5476 SLOW_ASSERT(new_object->IsHeapObject());
5477 store_buffer_.EnterDirectlyIntoStoreBuffer(
5478 reinterpret_cast<Address>(slot));
5480 SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5481 } else if (record_slots &&
5482 MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5483 mark_compact_collector()->RecordSlot(slot, slot, object);
5486 slot_address += kPointerSize;
5492 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5495 bool IsAMapPointerAddress(Object** addr) {
5496 uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5497 int mod = a % Map::kSize;
5498 return mod >= Map::kPointerFieldsBeginOffset &&
5499 mod < Map::kPointerFieldsEndOffset;
5503 bool EverythingsAPointer(Object** addr) {
5508 static void CheckStoreBuffer(Heap* heap,
5511 Object**** store_buffer_position,
5512 Object*** store_buffer_top,
5513 CheckStoreBufferFilter filter,
5514 Address special_garbage_start,
5515 Address special_garbage_end) {
5516 Map* free_space_map = heap->free_space_map();
5517 for ( ; current < limit; current++) {
5518 Object* o = *current;
5519 Address current_address = reinterpret_cast<Address>(current);
5521 if (o == free_space_map) {
5522 Address current_address = reinterpret_cast<Address>(current);
5523 FreeSpace* free_space =
5524 FreeSpace::cast(HeapObject::FromAddress(current_address));
5525 int skip = free_space->Size();
5526 ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5528 current_address += skip - kPointerSize;
5529 current = reinterpret_cast<Object**>(current_address);
5532 // Skip the current linear allocation space between top and limit which is
5533 // unmarked with the free space map, but can contain junk.
5534 if (current_address == special_garbage_start &&
5535 special_garbage_end != special_garbage_start) {
5536 current_address = special_garbage_end - kPointerSize;
5537 current = reinterpret_cast<Object**>(current_address);
5540 if (!(*filter)(current)) continue;
5541 ASSERT(current_address < special_garbage_start ||
5542 current_address >= special_garbage_end);
5543 ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5544 // We have to check that the pointer does not point into new space
5545 // without trying to cast it to a heap object since the hash field of
5546 // a string can contain values like 1 and 3 which are tagged null
5548 if (!heap->InNewSpace(o)) continue;
5549 while (**store_buffer_position < current &&
5550 *store_buffer_position < store_buffer_top) {
5551 (*store_buffer_position)++;
5553 if (**store_buffer_position != current ||
5554 *store_buffer_position == store_buffer_top) {
5555 Object** obj_start = current;
5556 while (!(*obj_start)->IsMap()) obj_start--;
5563 // Check that the store buffer contains all intergenerational pointers by
5564 // scanning a page and ensuring that all pointers to young space are in the
5566 void Heap::OldPointerSpaceCheckStoreBuffer() {
5567 OldSpace* space = old_pointer_space();
5568 PageIterator pages(space);
5570 store_buffer()->SortUniq();
5572 while (pages.has_next()) {
5573 Page* page = pages.next();
5574 Object** current = reinterpret_cast<Object**>(page->area_start());
5576 Address end = page->area_end();
5578 Object*** store_buffer_position = store_buffer()->Start();
5579 Object*** store_buffer_top = store_buffer()->Top();
5581 Object** limit = reinterpret_cast<Object**>(end);
5582 CheckStoreBuffer(this,
5585 &store_buffer_position,
5587 &EverythingsAPointer,
5594 void Heap::MapSpaceCheckStoreBuffer() {
5595 MapSpace* space = map_space();
5596 PageIterator pages(space);
5598 store_buffer()->SortUniq();
5600 while (pages.has_next()) {
5601 Page* page = pages.next();
5602 Object** current = reinterpret_cast<Object**>(page->area_start());
5604 Address end = page->area_end();
5606 Object*** store_buffer_position = store_buffer()->Start();
5607 Object*** store_buffer_top = store_buffer()->Top();
5609 Object** limit = reinterpret_cast<Object**>(end);
5610 CheckStoreBuffer(this,
5613 &store_buffer_position,
5615 &IsAMapPointerAddress,
5622 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5623 LargeObjectIterator it(lo_space());
5624 for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5625 // We only have code, sequential strings, or fixed arrays in large
5626 // object space, and only fixed arrays can possibly contain pointers to
5627 // the young generation.
5628 if (object->IsFixedArray()) {
5629 Object*** store_buffer_position = store_buffer()->Start();
5630 Object*** store_buffer_top = store_buffer()->Top();
5631 Object** current = reinterpret_cast<Object**>(object->address());
5633 reinterpret_cast<Object**>(object->address() + object->Size());
5634 CheckStoreBuffer(this,
5637 &store_buffer_position,
5639 &EverythingsAPointer,
5648 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5649 IterateStrongRoots(v, mode);
5650 IterateWeakRoots(v, mode);
5654 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5655 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5656 v->Synchronize(VisitorSynchronization::kSymbolTable);
5657 if (mode != VISIT_ALL_IN_SCAVENGE &&
5658 mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5659 // Scavenge collections have special processing for this.
5660 external_string_table_.Iterate(v);
5662 v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5666 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5667 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5668 v->Synchronize(VisitorSynchronization::kStrongRootList);
5670 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5671 v->Synchronize(VisitorSynchronization::kSymbol);
5673 isolate_->bootstrapper()->Iterate(v);
5674 v->Synchronize(VisitorSynchronization::kBootstrapper);
5675 isolate_->Iterate(v);
5676 v->Synchronize(VisitorSynchronization::kTop);
5677 Relocatable::Iterate(v);
5678 v->Synchronize(VisitorSynchronization::kRelocatable);
5680 #ifdef ENABLE_DEBUGGER_SUPPORT
5681 isolate_->debug()->Iterate(v);
5682 if (isolate_->deoptimizer_data() != NULL) {
5683 isolate_->deoptimizer_data()->Iterate(v);
5686 v->Synchronize(VisitorSynchronization::kDebug);
5687 isolate_->compilation_cache()->Iterate(v);
5688 v->Synchronize(VisitorSynchronization::kCompilationCache);
5690 // Iterate over local handles in handle scopes.
5691 isolate_->handle_scope_implementer()->Iterate(v);
5692 v->Synchronize(VisitorSynchronization::kHandleScope);
5694 // Iterate over the builtin code objects and code stubs in the
5695 // heap. Note that it is not necessary to iterate over code objects
5696 // on scavenge collections.
5697 if (mode != VISIT_ALL_IN_SCAVENGE) {
5698 isolate_->builtins()->IterateBuiltins(v);
5700 v->Synchronize(VisitorSynchronization::kBuiltins);
5702 // Iterate over global handles.
5704 case VISIT_ONLY_STRONG:
5705 isolate_->global_handles()->IterateStrongRoots(v);
5707 case VISIT_ALL_IN_SCAVENGE:
5708 isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5710 case VISIT_ALL_IN_SWEEP_NEWSPACE:
5712 isolate_->global_handles()->IterateAllRoots(v);
5715 v->Synchronize(VisitorSynchronization::kGlobalHandles);
5717 // Iterate over pointers being held by inactive threads.
5718 isolate_->thread_manager()->Iterate(v);
5719 v->Synchronize(VisitorSynchronization::kThreadManager);
5721 // Iterate over the pointers the Serialization/Deserialization code is
5723 // During garbage collection this keeps the partial snapshot cache alive.
5724 // During deserialization of the startup snapshot this creates the partial
5725 // snapshot cache and deserializes the objects it refers to. During
5726 // serialization this does nothing, since the partial snapshot cache is
5727 // empty. However the next thing we do is create the partial snapshot,
5728 // filling up the partial snapshot cache with objects it needs as we go.
5729 SerializerDeserializer::Iterate(v);
5730 // We don't do a v->Synchronize call here, because in debug mode that will
5731 // output a flag to the snapshot. However at this point the serializer and
5732 // deserializer are deliberately a little unsynchronized (see above) so the
5733 // checking of the sync flag in the snapshot would fail.
5737 // TODO(1236194): Since the heap size is configurable on the command line
5738 // and through the API, we should gracefully handle the case that the heap
5739 // size is not big enough to fit all the initial objects.
5740 bool Heap::ConfigureHeap(int max_semispace_size,
5741 intptr_t max_old_gen_size,
5742 intptr_t max_executable_size) {
5743 if (HasBeenSetUp()) return false;
5745 if (FLAG_stress_compaction) {
5746 // This will cause more frequent GCs when stressing.
5747 max_semispace_size_ = Page::kPageSize;
5750 if (max_semispace_size > 0) {
5751 if (max_semispace_size < Page::kPageSize) {
5752 max_semispace_size = Page::kPageSize;
5753 if (FLAG_trace_gc) {
5754 PrintF("Max semispace size cannot be less than %dkbytes\n",
5755 Page::kPageSize >> 10);
5758 max_semispace_size_ = max_semispace_size;
5761 if (Snapshot::IsEnabled()) {
5762 // If we are using a snapshot we always reserve the default amount
5763 // of memory for each semispace because code in the snapshot has
5764 // write-barrier code that relies on the size and alignment of new
5765 // space. We therefore cannot use a larger max semispace size
5766 // than the default reserved semispace size.
5767 if (max_semispace_size_ > reserved_semispace_size_) {
5768 max_semispace_size_ = reserved_semispace_size_;
5769 if (FLAG_trace_gc) {
5770 PrintF("Max semispace size cannot be more than %dkbytes\n",
5771 reserved_semispace_size_ >> 10);
5775 // If we are not using snapshots we reserve space for the actual
5776 // max semispace size.
5777 reserved_semispace_size_ = max_semispace_size_;
5780 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5781 if (max_executable_size > 0) {
5782 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5785 // The max executable size must be less than or equal to the max old
5787 if (max_executable_size_ > max_old_generation_size_) {
5788 max_executable_size_ = max_old_generation_size_;
5791 // The new space size must be a power of two to support single-bit testing
5793 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5794 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5795 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5796 external_allocation_limit_ = 10 * max_semispace_size_;
5798 // The old generation is paged and needs at least one page for each space.
5799 int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5800 max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5802 RoundUp(max_old_generation_size_,
5810 bool Heap::ConfigureHeapDefault() {
5811 return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5812 static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5813 static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5817 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5818 *stats->start_marker = HeapStats::kStartMarker;
5819 *stats->end_marker = HeapStats::kEndMarker;
5820 *stats->new_space_size = new_space_.SizeAsInt();
5821 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5822 *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5823 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5824 *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5825 *stats->old_data_space_capacity = old_data_space_->Capacity();
5826 *stats->code_space_size = code_space_->SizeOfObjects();
5827 *stats->code_space_capacity = code_space_->Capacity();
5828 *stats->map_space_size = map_space_->SizeOfObjects();
5829 *stats->map_space_capacity = map_space_->Capacity();
5830 *stats->cell_space_size = cell_space_->SizeOfObjects();
5831 *stats->cell_space_capacity = cell_space_->Capacity();
5832 *stats->lo_space_size = lo_space_->Size();
5833 isolate_->global_handles()->RecordStats(stats);
5834 *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5835 *stats->memory_allocator_capacity =
5836 isolate()->memory_allocator()->Size() +
5837 isolate()->memory_allocator()->Available();
5838 *stats->os_error = OS::GetLastError();
5839 isolate()->memory_allocator()->Available();
5840 if (take_snapshot) {
5841 HeapIterator iterator;
5842 for (HeapObject* obj = iterator.next();
5844 obj = iterator.next()) {
5845 InstanceType type = obj->map()->instance_type();
5846 ASSERT(0 <= type && type <= LAST_TYPE);
5847 stats->objects_per_type[type]++;
5848 stats->size_per_type[type] += obj->Size();
5854 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5855 return old_pointer_space_->SizeOfObjects()
5856 + old_data_space_->SizeOfObjects()
5857 + code_space_->SizeOfObjects()
5858 + map_space_->SizeOfObjects()
5859 + cell_space_->SizeOfObjects()
5860 + lo_space_->SizeOfObjects();
5864 intptr_t Heap::PromotedExternalMemorySize() {
5865 if (amount_of_external_allocated_memory_
5866 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5867 return amount_of_external_allocated_memory_
5868 - amount_of_external_allocated_memory_at_last_global_gc_;
5873 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5874 static const int kMarkTag = 2;
5877 class HeapDebugUtils {
5879 explicit HeapDebugUtils(Heap* heap)
5880 : search_for_any_global_(false),
5881 search_target_(NULL),
5882 found_target_(false),
5887 class MarkObjectVisitor : public ObjectVisitor {
5889 explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5891 void VisitPointers(Object** start, Object** end) {
5892 // Copy all HeapObject pointers in [start, end)
5893 for (Object** p = start; p < end; p++) {
5894 if ((*p)->IsHeapObject())
5895 utils_->MarkObjectRecursively(p);
5899 HeapDebugUtils* utils_;
5902 void MarkObjectRecursively(Object** p) {
5903 if (!(*p)->IsHeapObject()) return;
5905 HeapObject* obj = HeapObject::cast(*p);
5907 Object* map = obj->map();
5909 if (!map->IsHeapObject()) return; // visited before
5911 if (found_target_) return; // stop if target found
5912 object_stack_.Add(obj);
5913 if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5914 (!search_for_any_global_ && (obj == search_target_))) {
5915 found_target_ = true;
5920 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5922 Address map_addr = map_p->address();
5924 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
5926 MarkObjectRecursively(&map);
5928 MarkObjectVisitor mark_visitor(this);
5930 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5933 if (!found_target_) // don't pop if found the target
5934 object_stack_.RemoveLast();
5938 class UnmarkObjectVisitor : public ObjectVisitor {
5940 explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5942 void VisitPointers(Object** start, Object** end) {
5943 // Copy all HeapObject pointers in [start, end)
5944 for (Object** p = start; p < end; p++) {
5945 if ((*p)->IsHeapObject())
5946 utils_->UnmarkObjectRecursively(p);
5950 HeapDebugUtils* utils_;
5954 void UnmarkObjectRecursively(Object** p) {
5955 if (!(*p)->IsHeapObject()) return;
5957 HeapObject* obj = HeapObject::cast(*p);
5959 Object* map = obj->map();
5961 if (map->IsHeapObject()) return; // unmarked already
5963 Address map_addr = reinterpret_cast<Address>(map);
5965 map_addr -= kMarkTag;
5967 ASSERT_TAG_ALIGNED(map_addr);
5969 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5971 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
5973 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5975 UnmarkObjectVisitor unmark_visitor(this);
5977 obj->IterateBody(Map::cast(map_p)->instance_type(),
5978 obj->SizeFromMap(Map::cast(map_p)),
5983 void MarkRootObjectRecursively(Object** root) {
5984 if (search_for_any_global_) {
5985 ASSERT(search_target_ == NULL);
5987 ASSERT(search_target_->IsHeapObject());
5989 found_target_ = false;
5990 object_stack_.Clear();
5992 MarkObjectRecursively(root);
5993 UnmarkObjectRecursively(root);
5995 if (found_target_) {
5996 PrintF("=====================================\n");
5997 PrintF("==== Path to object ====\n");
5998 PrintF("=====================================\n\n");
6000 ASSERT(!object_stack_.is_empty());
6001 for (int i = 0; i < object_stack_.length(); i++) {
6002 if (i > 0) PrintF("\n |\n |\n V\n\n");
6003 Object* obj = object_stack_[i];
6006 PrintF("=====================================\n");
6010 // Helper class for visiting HeapObjects recursively.
6011 class MarkRootVisitor: public ObjectVisitor {
6013 explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6015 void VisitPointers(Object** start, Object** end) {
6016 // Visit all HeapObject pointers in [start, end)
6017 for (Object** p = start; p < end; p++) {
6018 if ((*p)->IsHeapObject())
6019 utils_->MarkRootObjectRecursively(p);
6023 HeapDebugUtils* utils_;
6026 bool search_for_any_global_;
6027 Object* search_target_;
6029 List<Object*> object_stack_;
6038 V8_DECLARE_ONCE(initialize_gc_once);
6040 static void InitializeGCOnce() {
6041 InitializeScavengingVisitorsTables();
6042 NewSpaceScavenger::Initialize();
6043 MarkCompactCollector::Initialize();
6046 bool Heap::SetUp(bool create_heap_objects) {
6048 allocation_timeout_ = FLAG_gc_interval;
6049 debug_utils_ = new HeapDebugUtils(this);
6052 // Initialize heap spaces and initial maps and objects. Whenever something
6053 // goes wrong, just return false. The caller should check the results and
6054 // call Heap::TearDown() to release allocated memory.
6056 // If the heap is not yet configured (e.g. through the API), configure it.
6057 // Configuration is based on the flags new-space-size (really the semispace
6058 // size) and old-space-size if set or the initial values of semispace_size_
6059 // and old_generation_size_ otherwise.
6061 if (!ConfigureHeapDefault()) return false;
6064 CallOnce(&initialize_gc_once, &InitializeGCOnce);
6066 MarkMapPointersAsEncoded(false);
6068 // Set up memory allocator.
6069 if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
6072 // Set up new space.
6073 if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
6077 // Initialize old pointer space.
6078 old_pointer_space_ =
6080 max_old_generation_size_,
6083 if (old_pointer_space_ == NULL) return false;
6084 if (!old_pointer_space_->SetUp()) return false;
6086 // Initialize old data space.
6089 max_old_generation_size_,
6092 if (old_data_space_ == NULL) return false;
6093 if (!old_data_space_->SetUp()) return false;
6095 // Initialize the code space, set its maximum capacity to the old
6096 // generation size. It needs executable memory.
6097 // On 64-bit platform(s), we put all code objects in a 2 GB range of
6098 // virtual address space, so that they can call each other with near calls.
6099 if (code_range_size_ > 0) {
6100 if (!isolate_->code_range()->SetUp(code_range_size_)) {
6106 new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
6107 if (code_space_ == NULL) return false;
6108 if (!code_space_->SetUp()) return false;
6110 // Initialize map space.
6111 map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
6112 if (map_space_ == NULL) return false;
6113 if (!map_space_->SetUp()) return false;
6115 // Initialize global property cell space.
6116 cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
6117 if (cell_space_ == NULL) return false;
6118 if (!cell_space_->SetUp()) return false;
6120 // The large object code space may contain code or data. We set the memory
6121 // to be non-executable here for safety, but this means we need to enable it
6122 // explicitly when allocating large code objects.
6123 lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
6124 if (lo_space_ == NULL) return false;
6125 if (!lo_space_->SetUp()) return false;
6127 // Set up the seed that is used to randomize the string hash function.
6128 ASSERT(hash_seed() == 0);
6129 if (FLAG_randomize_hashes) {
6130 if (FLAG_hash_seed == 0) {
6132 Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
6134 set_hash_seed(Smi::FromInt(FLAG_hash_seed));
6138 if (create_heap_objects) {
6139 // Create initial maps.
6140 if (!CreateInitialMaps()) return false;
6141 if (!CreateApiObjects()) return false;
6143 // Create initial objects
6144 if (!CreateInitialObjects()) return false;
6146 global_contexts_list_ = undefined_value();
6149 LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
6150 LOG(isolate_, IntPtrTEvent("heap-available", Available()));
6152 store_buffer()->SetUp();
6158 void Heap::SetStackLimits() {
6159 ASSERT(isolate_ != NULL);
6160 ASSERT(isolate_ == isolate());
6161 // On 64 bit machines, pointers are generally out of range of Smis. We write
6162 // something that looks like an out of range Smi to the GC.
6164 // Set up the special root array entries containing the stack limits.
6165 // These are actually addresses, but the tag makes the GC ignore it.
6166 roots_[kStackLimitRootIndex] =
6167 reinterpret_cast<Object*>(
6168 (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
6169 roots_[kRealStackLimitRootIndex] =
6170 reinterpret_cast<Object*>(
6171 (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
6175 void Heap::TearDown() {
6177 if (FLAG_verify_heap) {
6181 if (FLAG_print_cumulative_gc_stat) {
6183 PrintF("gc_count=%d ", gc_count_);
6184 PrintF("mark_sweep_count=%d ", ms_count_);
6185 PrintF("max_gc_pause=%d ", get_max_gc_pause());
6186 PrintF("min_in_mutator=%d ", get_min_in_mutator());
6187 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
6188 get_max_alive_after_gc());
6192 isolate_->global_handles()->TearDown();
6194 external_string_table_.TearDown();
6196 new_space_.TearDown();
6198 if (old_pointer_space_ != NULL) {
6199 old_pointer_space_->TearDown();
6200 delete old_pointer_space_;
6201 old_pointer_space_ = NULL;
6204 if (old_data_space_ != NULL) {
6205 old_data_space_->TearDown();
6206 delete old_data_space_;
6207 old_data_space_ = NULL;
6210 if (code_space_ != NULL) {
6211 code_space_->TearDown();
6216 if (map_space_ != NULL) {
6217 map_space_->TearDown();
6222 if (cell_space_ != NULL) {
6223 cell_space_->TearDown();
6228 if (lo_space_ != NULL) {
6229 lo_space_->TearDown();
6234 store_buffer()->TearDown();
6235 incremental_marking()->TearDown();
6237 isolate_->memory_allocator()->TearDown();
6240 delete debug_utils_;
6241 debug_utils_ = NULL;
6246 void Heap::Shrink() {
6247 // Try to shrink all paged spaces.
6249 for (PagedSpace* space = spaces.next();
6251 space = spaces.next()) {
6252 space->ReleaseAllUnusedPages();
6257 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6258 ASSERT(callback != NULL);
6259 GCPrologueCallbackPair pair(callback, gc_type);
6260 ASSERT(!gc_prologue_callbacks_.Contains(pair));
6261 return gc_prologue_callbacks_.Add(pair);
6265 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6266 ASSERT(callback != NULL);
6267 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6268 if (gc_prologue_callbacks_[i].callback == callback) {
6269 gc_prologue_callbacks_.Remove(i);
6277 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6278 ASSERT(callback != NULL);
6279 GCEpilogueCallbackPair pair(callback, gc_type);
6280 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6281 return gc_epilogue_callbacks_.Add(pair);
6285 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6286 ASSERT(callback != NULL);
6287 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6288 if (gc_epilogue_callbacks_[i].callback == callback) {
6289 gc_epilogue_callbacks_.Remove(i);
6299 class PrintHandleVisitor: public ObjectVisitor {
6301 void VisitPointers(Object** start, Object** end) {
6302 for (Object** p = start; p < end; p++)
6303 PrintF(" handle %p to %p\n",
6304 reinterpret_cast<void*>(p),
6305 reinterpret_cast<void*>(*p));
6309 void Heap::PrintHandles() {
6310 PrintF("Handles:\n");
6311 PrintHandleVisitor v;
6312 isolate_->handle_scope_implementer()->Iterate(&v);
6318 Space* AllSpaces::next() {
6319 switch (counter_++) {
6321 return HEAP->new_space();
6322 case OLD_POINTER_SPACE:
6323 return HEAP->old_pointer_space();
6324 case OLD_DATA_SPACE:
6325 return HEAP->old_data_space();
6327 return HEAP->code_space();
6329 return HEAP->map_space();
6331 return HEAP->cell_space();
6333 return HEAP->lo_space();
6340 PagedSpace* PagedSpaces::next() {
6341 switch (counter_++) {
6342 case OLD_POINTER_SPACE:
6343 return HEAP->old_pointer_space();
6344 case OLD_DATA_SPACE:
6345 return HEAP->old_data_space();
6347 return HEAP->code_space();
6349 return HEAP->map_space();
6351 return HEAP->cell_space();
6359 OldSpace* OldSpaces::next() {
6360 switch (counter_++) {
6361 case OLD_POINTER_SPACE:
6362 return HEAP->old_pointer_space();
6363 case OLD_DATA_SPACE:
6364 return HEAP->old_data_space();
6366 return HEAP->code_space();
6373 SpaceIterator::SpaceIterator()
6374 : current_space_(FIRST_SPACE),
6380 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6381 : current_space_(FIRST_SPACE),
6383 size_func_(size_func) {
6387 SpaceIterator::~SpaceIterator() {
6388 // Delete active iterator if any.
6393 bool SpaceIterator::has_next() {
6394 // Iterate until no more spaces.
6395 return current_space_ != LAST_SPACE;
6399 ObjectIterator* SpaceIterator::next() {
6400 if (iterator_ != NULL) {
6403 // Move to the next space
6405 if (current_space_ > LAST_SPACE) {
6410 // Return iterator for the new current space.
6411 return CreateIterator();
6415 // Create an iterator for the space to iterate.
6416 ObjectIterator* SpaceIterator::CreateIterator() {
6417 ASSERT(iterator_ == NULL);
6419 switch (current_space_) {
6421 iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6423 case OLD_POINTER_SPACE:
6424 iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6426 case OLD_DATA_SPACE:
6427 iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6430 iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6433 iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6436 iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6439 iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6443 // Return the newly allocated iterator;
6444 ASSERT(iterator_ != NULL);
6449 class HeapObjectsFilter {
6451 virtual ~HeapObjectsFilter() {}
6452 virtual bool SkipObject(HeapObject* object) = 0;
6456 class UnreachableObjectsFilter : public HeapObjectsFilter {
6458 UnreachableObjectsFilter() {
6459 MarkReachableObjects();
6462 ~UnreachableObjectsFilter() {
6463 Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6466 bool SkipObject(HeapObject* object) {
6467 MarkBit mark_bit = Marking::MarkBitFrom(object);
6468 return !mark_bit.Get();
6472 class MarkingVisitor : public ObjectVisitor {
6474 MarkingVisitor() : marking_stack_(10) {}
6476 void VisitPointers(Object** start, Object** end) {
6477 for (Object** p = start; p < end; p++) {
6478 if (!(*p)->IsHeapObject()) continue;
6479 HeapObject* obj = HeapObject::cast(*p);
6480 MarkBit mark_bit = Marking::MarkBitFrom(obj);
6481 if (!mark_bit.Get()) {
6483 marking_stack_.Add(obj);
6488 void TransitiveClosure() {
6489 while (!marking_stack_.is_empty()) {
6490 HeapObject* obj = marking_stack_.RemoveLast();
6496 List<HeapObject*> marking_stack_;
6499 void MarkReachableObjects() {
6500 Heap* heap = Isolate::Current()->heap();
6501 MarkingVisitor visitor;
6502 heap->IterateRoots(&visitor, VISIT_ALL);
6503 visitor.TransitiveClosure();
6506 AssertNoAllocation no_alloc;
6510 HeapIterator::HeapIterator()
6511 : filtering_(HeapIterator::kNoFiltering),
6517 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6518 : filtering_(filtering),
6524 HeapIterator::~HeapIterator() {
6529 void HeapIterator::Init() {
6530 // Start the iteration.
6531 space_iterator_ = new SpaceIterator;
6532 switch (filtering_) {
6533 case kFilterUnreachable:
6534 filter_ = new UnreachableObjectsFilter;
6539 object_iterator_ = space_iterator_->next();
6543 void HeapIterator::Shutdown() {
6545 // Assert that in filtering mode we have iterated through all
6546 // objects. Otherwise, heap will be left in an inconsistent state.
6547 if (filtering_ != kNoFiltering) {
6548 ASSERT(object_iterator_ == NULL);
6551 // Make sure the last iterator is deallocated.
6552 delete space_iterator_;
6553 space_iterator_ = NULL;
6554 object_iterator_ = NULL;
6560 HeapObject* HeapIterator::next() {
6561 if (filter_ == NULL) return NextObject();
6563 HeapObject* obj = NextObject();
6564 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6569 HeapObject* HeapIterator::NextObject() {
6570 // No iterator means we are done.
6571 if (object_iterator_ == NULL) return NULL;
6573 if (HeapObject* obj = object_iterator_->next_object()) {
6574 // If the current iterator has more objects we are fine.
6577 // Go though the spaces looking for one that has objects.
6578 while (space_iterator_->has_next()) {
6579 object_iterator_ = space_iterator_->next();
6580 if (HeapObject* obj = object_iterator_->next_object()) {
6585 // Done with the last space.
6586 object_iterator_ = NULL;
6591 void HeapIterator::reset() {
6592 // Restart the iterator.
6598 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6600 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6602 class PathTracer::MarkVisitor: public ObjectVisitor {
6604 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6605 void VisitPointers(Object** start, Object** end) {
6606 // Scan all HeapObject pointers in [start, end)
6607 for (Object** p = start; !tracer_->found() && (p < end); p++) {
6608 if ((*p)->IsHeapObject())
6609 tracer_->MarkRecursively(p, this);
6614 PathTracer* tracer_;
6618 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6620 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6621 void VisitPointers(Object** start, Object** end) {
6622 // Scan all HeapObject pointers in [start, end)
6623 for (Object** p = start; p < end; p++) {
6624 if ((*p)->IsHeapObject())
6625 tracer_->UnmarkRecursively(p, this);
6630 PathTracer* tracer_;
6634 void PathTracer::VisitPointers(Object** start, Object** end) {
6635 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6636 // Visit all HeapObject pointers in [start, end)
6637 for (Object** p = start; !done && (p < end); p++) {
6638 if ((*p)->IsHeapObject()) {
6640 done = ((what_to_find_ == FIND_FIRST) && found_target_);
6646 void PathTracer::Reset() {
6647 found_target_ = false;
6648 object_stack_.Clear();
6652 void PathTracer::TracePathFrom(Object** root) {
6653 ASSERT((search_target_ == kAnyGlobalObject) ||
6654 search_target_->IsHeapObject());
6655 found_target_in_trace_ = false;
6656 object_stack_.Clear();
6658 MarkVisitor mark_visitor(this);
6659 MarkRecursively(root, &mark_visitor);
6661 UnmarkVisitor unmark_visitor(this);
6662 UnmarkRecursively(root, &unmark_visitor);
6668 static bool SafeIsGlobalContext(HeapObject* obj) {
6669 return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6673 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6674 if (!(*p)->IsHeapObject()) return;
6676 HeapObject* obj = HeapObject::cast(*p);
6678 Object* map = obj->map();
6680 if (!map->IsHeapObject()) return; // visited before
6682 if (found_target_in_trace_) return; // stop if target found
6683 object_stack_.Add(obj);
6684 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6685 (obj == search_target_)) {
6686 found_target_in_trace_ = true;
6687 found_target_ = true;
6691 bool is_global_context = SafeIsGlobalContext(obj);
6694 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6696 Address map_addr = map_p->address();
6698 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6700 // Scan the object body.
6701 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6702 // This is specialized to scan Context's properly.
6703 Object** start = reinterpret_cast<Object**>(obj->address() +
6704 Context::kHeaderSize);
6705 Object** end = reinterpret_cast<Object**>(obj->address() +
6706 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6707 mark_visitor->VisitPointers(start, end);
6709 obj->IterateBody(map_p->instance_type(),
6710 obj->SizeFromMap(map_p),
6714 // Scan the map after the body because the body is a lot more interesting
6715 // when doing leak detection.
6716 MarkRecursively(&map, mark_visitor);
6718 if (!found_target_in_trace_) // don't pop if found the target
6719 object_stack_.RemoveLast();
6723 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6724 if (!(*p)->IsHeapObject()) return;
6726 HeapObject* obj = HeapObject::cast(*p);
6728 Object* map = obj->map();
6730 if (map->IsHeapObject()) return; // unmarked already
6732 Address map_addr = reinterpret_cast<Address>(map);
6734 map_addr -= kMarkTag;
6736 ASSERT_TAG_ALIGNED(map_addr);
6738 HeapObject* map_p = HeapObject::FromAddress(map_addr);
6740 obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6742 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6744 obj->IterateBody(Map::cast(map_p)->instance_type(),
6745 obj->SizeFromMap(Map::cast(map_p)),
6750 void PathTracer::ProcessResults() {
6751 if (found_target_) {
6752 PrintF("=====================================\n");
6753 PrintF("==== Path to object ====\n");
6754 PrintF("=====================================\n\n");
6756 ASSERT(!object_stack_.is_empty());
6757 for (int i = 0; i < object_stack_.length(); i++) {
6758 if (i > 0) PrintF("\n |\n |\n V\n\n");
6759 Object* obj = object_stack_[i];
6766 PrintF("=====================================\n");
6769 #endif // DEBUG || LIVE_OBJECT_LIST
6773 // Triggers a depth-first traversal of reachable objects from roots
6774 // and finds a path to a specific heap object and prints it.
6775 void Heap::TracePathToObject(Object* target) {
6776 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6777 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6781 // Triggers a depth-first traversal of reachable objects from roots
6782 // and finds a path to any global object and prints it. Useful for
6783 // determining the source for leaks of global objects.
6784 void Heap::TracePathToGlobal() {
6785 PathTracer tracer(PathTracer::kAnyGlobalObject,
6786 PathTracer::FIND_ALL,
6788 IterateRoots(&tracer, VISIT_ONLY_STRONG);
6793 static intptr_t CountTotalHolesSize() {
6794 intptr_t holes_size = 0;
6796 for (OldSpace* space = spaces.next();
6798 space = spaces.next()) {
6799 holes_size += space->Waste() + space->Available();
6805 GCTracer::GCTracer(Heap* heap,
6806 const char* gc_reason,
6807 const char* collector_reason)
6809 start_object_size_(0),
6810 start_memory_size_(0),
6813 allocated_since_last_gc_(0),
6814 spent_in_mutator_(0),
6815 promoted_objects_size_(0),
6817 gc_reason_(gc_reason),
6818 collector_reason_(collector_reason) {
6819 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6820 start_time_ = OS::TimeCurrentMillis();
6821 start_object_size_ = heap_->SizeOfObjects();
6822 start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6824 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6828 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6830 allocated_since_last_gc_ =
6831 heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6833 if (heap_->last_gc_end_timestamp_ > 0) {
6834 spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6837 steps_count_ = heap_->incremental_marking()->steps_count();
6838 steps_took_ = heap_->incremental_marking()->steps_took();
6839 longest_step_ = heap_->incremental_marking()->longest_step();
6840 steps_count_since_last_gc_ =
6841 heap_->incremental_marking()->steps_count_since_last_gc();
6842 steps_took_since_last_gc_ =
6843 heap_->incremental_marking()->steps_took_since_last_gc();
6847 GCTracer::~GCTracer() {
6848 // Printf ONE line iff flag is set.
6849 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6851 bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6853 heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6854 heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6856 int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6858 // Update cumulative GC statistics if required.
6859 if (FLAG_print_cumulative_gc_stat) {
6860 heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6861 heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6862 heap_->alive_after_last_gc_);
6864 heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6865 static_cast<int>(spent_in_mutator_));
6869 PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6871 if (!FLAG_trace_gc_nvp) {
6872 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6874 double end_memory_size_mb =
6875 static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6877 PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6879 static_cast<double>(start_object_size_) / MB,
6880 static_cast<double>(start_memory_size_) / MB,
6881 SizeOfHeapObjects(),
6882 end_memory_size_mb);
6884 if (external_time > 0) PrintF("%d / ", external_time);
6885 PrintF("%d ms", time);
6886 if (steps_count_ > 0) {
6887 if (collector_ == SCAVENGER) {
6888 PrintF(" (+ %d ms in %d steps since last GC)",
6889 static_cast<int>(steps_took_since_last_gc_),
6890 steps_count_since_last_gc_);
6892 PrintF(" (+ %d ms in %d steps since start of marking, "
6893 "biggest step %f ms)",
6894 static_cast<int>(steps_took_),
6900 if (gc_reason_ != NULL) {
6901 PrintF(" [%s]", gc_reason_);
6904 if (collector_reason_ != NULL) {
6905 PrintF(" [%s]", collector_reason_);
6910 PrintF("pause=%d ", time);
6911 PrintF("mutator=%d ",
6912 static_cast<int>(spent_in_mutator_));
6915 switch (collector_) {
6919 case MARK_COMPACTOR:
6927 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6928 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6929 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6930 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6931 PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6932 PrintF("new_new=%d ",
6933 static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6934 PrintF("root_new=%d ",
6935 static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6936 PrintF("old_new=%d ",
6937 static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6938 PrintF("compaction_ptrs=%d ",
6939 static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6940 PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6941 Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6942 PrintF("misc_compaction=%d ",
6943 static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
6945 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
6946 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6947 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6948 in_free_list_or_wasted_before_gc_);
6949 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6951 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6952 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6954 if (collector_ == SCAVENGER) {
6955 PrintF("stepscount=%d ", steps_count_since_last_gc_);
6956 PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6958 PrintF("stepscount=%d ", steps_count_);
6959 PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6965 heap_->PrintShortHeapStatistics();
6969 const char* GCTracer::CollectorString() {
6970 switch (collector_) {
6973 case MARK_COMPACTOR:
6974 return "Mark-sweep";
6976 return "Unknown GC";
6980 int KeyedLookupCache::Hash(Map* map, String* name) {
6981 // Uses only lower 32 bits if pointers are larger.
6982 uintptr_t addr_hash =
6983 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6984 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6988 int KeyedLookupCache::Lookup(Map* map, String* name) {
6989 int index = (Hash(map, name) & kHashMask);
6990 for (int i = 0; i < kEntriesPerBucket; i++) {
6991 Key& key = keys_[index + i];
6992 if ((key.map == map) && key.name->Equals(name)) {
6993 return field_offsets_[index + i];
7000 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
7002 if (HEAP->LookupSymbolIfExists(name, &symbol)) {
7003 int index = (Hash(map, symbol) & kHashMask);
7004 // After a GC there will be free slots, so we use them in order (this may
7005 // help to get the most frequently used one in position 0).
7006 for (int i = 0; i< kEntriesPerBucket; i++) {
7007 Key& key = keys_[index];
7008 Object* free_entry_indicator = NULL;
7009 if (key.map == free_entry_indicator) {
7012 field_offsets_[index + i] = field_offset;
7016 // No free entry found in this bucket, so we move them all down one and
7017 // put the new entry at position zero.
7018 for (int i = kEntriesPerBucket - 1; i > 0; i--) {
7019 Key& key = keys_[index + i];
7020 Key& key2 = keys_[index + i - 1];
7022 field_offsets_[index + i] = field_offsets_[index + i - 1];
7025 // Write the new first entry.
7026 Key& key = keys_[index];
7029 field_offsets_[index] = field_offset;
7034 void KeyedLookupCache::Clear() {
7035 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
7039 void DescriptorLookupCache::Clear() {
7040 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
7045 void Heap::GarbageCollectionGreedyCheck() {
7046 ASSERT(FLAG_gc_greedy);
7047 if (isolate_->bootstrapper()->IsActive()) return;
7048 if (disallow_allocation_failure()) return;
7049 CollectGarbage(NEW_SPACE);
7054 TranscendentalCache::SubCache::SubCache(Type t)
7056 isolate_(Isolate::Current()) {
7057 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
7058 uint32_t in1 = 0xffffffffu; // generated by the FPU.
7059 for (int i = 0; i < kCacheSize; i++) {
7060 elements_[i].in[0] = in0;
7061 elements_[i].in[1] = in1;
7062 elements_[i].output = NULL;
7067 void TranscendentalCache::Clear() {
7068 for (int i = 0; i < kNumberOfCaches; i++) {
7069 if (caches_[i] != NULL) {
7077 void ExternalStringTable::CleanUp() {
7079 for (int i = 0; i < new_space_strings_.length(); ++i) {
7080 if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7083 if (heap_->InNewSpace(new_space_strings_[i])) {
7084 new_space_strings_[last++] = new_space_strings_[i];
7086 old_space_strings_.Add(new_space_strings_[i]);
7089 new_space_strings_.Rewind(last);
7091 for (int i = 0; i < old_space_strings_.length(); ++i) {
7092 if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7095 ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
7096 old_space_strings_[last++] = old_space_strings_[i];
7098 old_space_strings_.Rewind(last);
7099 if (FLAG_verify_heap) {
7105 void ExternalStringTable::TearDown() {
7106 new_space_strings_.Free();
7107 old_space_strings_.Free();
7111 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
7112 chunk->set_next_chunk(chunks_queued_for_free_);
7113 chunks_queued_for_free_ = chunk;
7117 void Heap::FreeQueuedChunks() {
7118 if (chunks_queued_for_free_ == NULL) return;
7121 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7122 next = chunk->next_chunk();
7123 chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7125 if (chunk->owner()->identity() == LO_SPACE) {
7126 // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
7127 // If FromAnyPointerAddress encounters a slot that belongs to a large
7128 // chunk queued for deletion it will fail to find the chunk because
7129 // it try to perform a search in the list of pages owned by of the large
7130 // object space and queued chunks were detached from that list.
7131 // To work around this we split large chunk into normal kPageSize aligned
7132 // pieces and initialize size, owner and flags field of every piece.
7133 // If FromAnyPointerAddress encounters a slot that belongs to one of
7134 // these smaller pieces it will treat it as a slot on a normal Page.
7135 Address chunk_end = chunk->address() + chunk->size();
7136 MemoryChunk* inner = MemoryChunk::FromAddress(
7137 chunk->address() + Page::kPageSize);
7138 MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
7139 while (inner <= inner_last) {
7140 // Size of a large chunk is always a multiple of
7141 // OS::AllocateAlignment() so there is always
7142 // enough space for a fake MemoryChunk header.
7143 Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
7144 // Guard against overflow.
7145 if (area_end < inner->address()) area_end = chunk_end;
7146 inner->SetArea(inner->address(), area_end);
7147 inner->set_size(Page::kPageSize);
7148 inner->set_owner(lo_space());
7149 inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7150 inner = MemoryChunk::FromAddress(
7151 inner->address() + Page::kPageSize);
7155 isolate_->heap()->store_buffer()->Compact();
7156 isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
7157 for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7158 next = chunk->next_chunk();
7159 isolate_->memory_allocator()->Free(chunk);
7161 chunks_queued_for_free_ = NULL;
7165 void Heap::RememberUnmappedPage(Address page, bool compacted) {
7166 uintptr_t p = reinterpret_cast<uintptr_t>(page);
7167 // Tag the page pointer to make it findable in the dump file.
7169 p ^= 0xc1ead & (Page::kPageSize - 1); // Cleared.
7171 p ^= 0x1d1ed & (Page::kPageSize - 1); // I died.
7173 remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
7174 reinterpret_cast<Address>(p);
7175 remembered_unmapped_pages_index_++;
7176 remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
7179 } } // namespace v8::internal