d8b72bed5330c8899c3124a6ea523edb56ccf7f4
[platform/upstream/v8.git] / src / heap / heap.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #include "src/accessors.h"
8 #include "src/api.h"
9 #include "src/base/bits.h"
10 #include "src/base/once.h"
11 #include "src/base/utils/random-number-generator.h"
12 #include "src/bootstrapper.h"
13 #include "src/codegen.h"
14 #include "src/compilation-cache.h"
15 #include "src/conversions.h"
16 #include "src/cpu-profiler.h"
17 #include "src/debug/debug.h"
18 #include "src/deoptimizer.h"
19 #include "src/global-handles.h"
20 #include "src/heap/gc-idle-time-handler.h"
21 #include "src/heap/incremental-marking.h"
22 #include "src/heap/mark-compact-inl.h"
23 #include "src/heap/mark-compact.h"
24 #include "src/heap/memory-reducer.h"
25 #include "src/heap/objects-visiting-inl.h"
26 #include "src/heap/objects-visiting.h"
27 #include "src/heap/store-buffer.h"
28 #include "src/heap-profiler.h"
29 #include "src/interpreter/interpreter.h"
30 #include "src/runtime-profiler.h"
31 #include "src/scopeinfo.h"
32 #include "src/snapshot/natives.h"
33 #include "src/snapshot/serialize.h"
34 #include "src/snapshot/snapshot.h"
35 #include "src/utils.h"
36 #include "src/v8threads.h"
37 #include "src/vm-state-inl.h"
38
39 #if V8_TARGET_ARCH_PPC && !V8_INTERPRETED_REGEXP
40 #include "src/regexp-macro-assembler.h"          // NOLINT
41 #include "src/ppc/regexp-macro-assembler-ppc.h"  // NOLINT
42 #endif
43 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
44 #include "src/regexp-macro-assembler.h"          // NOLINT
45 #include "src/arm/regexp-macro-assembler-arm.h"  // NOLINT
46 #endif
47 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
48 #include "src/regexp-macro-assembler.h"            // NOLINT
49 #include "src/mips/regexp-macro-assembler-mips.h"  // NOLINT
50 #endif
51 #if V8_TARGET_ARCH_MIPS64 && !V8_INTERPRETED_REGEXP
52 #include "src/regexp-macro-assembler.h"
53 #include "src/mips64/regexp-macro-assembler-mips64.h"
54 #endif
55
56 namespace v8 {
57 namespace internal {
58
59
60 struct Heap::StrongRootsList {
61   Object** start;
62   Object** end;
63   StrongRootsList* next;
64 };
65
66
67 Heap::Heap()
68     : amount_of_external_allocated_memory_(0),
69       amount_of_external_allocated_memory_at_last_global_gc_(0),
70       isolate_(NULL),
71       code_range_size_(0),
72       // semispace_size_ should be a power of 2 and old_generation_size_ should
73       // be a multiple of Page::kPageSize.
74       reserved_semispace_size_(8 * (kPointerSize / 4) * MB),
75       max_semi_space_size_(8 * (kPointerSize / 4) * MB),
76       initial_semispace_size_(Page::kPageSize),
77       target_semispace_size_(Page::kPageSize),
78       max_old_generation_size_(700ul * (kPointerSize / 4) * MB),
79       initial_old_generation_size_(max_old_generation_size_ /
80                                    kInitalOldGenerationLimitFactor),
81       old_generation_size_configured_(false),
82       max_executable_size_(256ul * (kPointerSize / 4) * MB),
83       // Variables set based on semispace_size_ and old_generation_size_ in
84       // ConfigureHeap.
85       // Will be 4 * reserved_semispace_size_ to ensure that young
86       // generation can be aligned to its size.
87       maximum_committed_(0),
88       survived_since_last_expansion_(0),
89       survived_last_scavenge_(0),
90       sweep_generation_(0),
91       always_allocate_scope_depth_(0),
92       contexts_disposed_(0),
93       global_ic_age_(0),
94       scan_on_scavenge_pages_(0),
95       new_space_(this),
96       old_space_(NULL),
97       code_space_(NULL),
98       map_space_(NULL),
99       lo_space_(NULL),
100       gc_state_(NOT_IN_GC),
101       gc_post_processing_depth_(0),
102       allocations_count_(0),
103       raw_allocations_hash_(0),
104       dump_allocations_hash_countdown_(FLAG_dump_allocations_digest_at_alloc),
105       ms_count_(0),
106       gc_count_(0),
107       remembered_unmapped_pages_index_(0),
108       unflattened_strings_length_(0),
109 #ifdef DEBUG
110       allocation_timeout_(0),
111 #endif  // DEBUG
112       old_generation_allocation_limit_(initial_old_generation_size_),
113       old_gen_exhausted_(false),
114       optimize_for_memory_usage_(false),
115       inline_allocation_disabled_(false),
116       store_buffer_rebuilder_(store_buffer()),
117       hidden_string_(NULL),
118       total_regexp_code_generated_(0),
119       tracer_(this),
120       high_survival_rate_period_length_(0),
121       promoted_objects_size_(0),
122       promotion_ratio_(0),
123       semi_space_copied_object_size_(0),
124       previous_semi_space_copied_object_size_(0),
125       semi_space_copied_rate_(0),
126       nodes_died_in_new_space_(0),
127       nodes_copied_in_new_space_(0),
128       nodes_promoted_(0),
129       maximum_size_scavenges_(0),
130       max_gc_pause_(0.0),
131       total_gc_time_ms_(0.0),
132       max_alive_after_gc_(0),
133       min_in_mutator_(kMaxInt),
134       marking_time_(0.0),
135       sweeping_time_(0.0),
136       last_idle_notification_time_(0.0),
137       last_gc_time_(0.0),
138       mark_compact_collector_(this),
139       store_buffer_(this),
140       incremental_marking_(this),
141       memory_reducer_(this),
142       full_codegen_bytes_generated_(0),
143       crankshaft_codegen_bytes_generated_(0),
144       new_space_allocation_counter_(0),
145       old_generation_allocation_counter_(0),
146       old_generation_size_at_last_gc_(0),
147       gcs_since_last_deopt_(0),
148       allocation_sites_scratchpad_length_(0),
149       ring_buffer_full_(false),
150       ring_buffer_end_(0),
151       promotion_queue_(this),
152       configured_(false),
153       external_string_table_(this),
154       chunks_queued_for_free_(NULL),
155       gc_callbacks_depth_(0),
156       deserialization_complete_(false),
157       concurrent_sweeping_enabled_(false),
158       strong_roots_list_(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_semi_space_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
164 #endif
165
166   // Ensure old_generation_size_ is a multiple of kPageSize.
167   DCHECK((max_old_generation_size_ & (Page::kPageSize - 1)) == 0);
168
169   memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
170   set_native_contexts_list(NULL);
171   set_allocation_sites_list(Smi::FromInt(0));
172   set_encountered_weak_collections(Smi::FromInt(0));
173   set_encountered_weak_cells(Smi::FromInt(0));
174   // Put a dummy entry in the remembered pages so we can find the list the
175   // minidump even if there are no real unmapped pages.
176   RememberUnmappedPage(NULL, false);
177
178   ClearObjectStats(true);
179 }
180
181
182 intptr_t Heap::Capacity() {
183   if (!HasBeenSetUp()) return 0;
184
185   return new_space_.Capacity() + old_space_->Capacity() +
186          code_space_->Capacity() + map_space_->Capacity();
187 }
188
189
190 intptr_t Heap::CommittedOldGenerationMemory() {
191   if (!HasBeenSetUp()) return 0;
192
193   return old_space_->CommittedMemory() + code_space_->CommittedMemory() +
194          map_space_->CommittedMemory() + lo_space_->Size();
195 }
196
197
198 intptr_t Heap::CommittedMemory() {
199   if (!HasBeenSetUp()) return 0;
200
201   return new_space_.CommittedMemory() + CommittedOldGenerationMemory();
202 }
203
204
205 size_t Heap::CommittedPhysicalMemory() {
206   if (!HasBeenSetUp()) return 0;
207
208   return new_space_.CommittedPhysicalMemory() +
209          old_space_->CommittedPhysicalMemory() +
210          code_space_->CommittedPhysicalMemory() +
211          map_space_->CommittedPhysicalMemory() +
212          lo_space_->CommittedPhysicalMemory();
213 }
214
215
216 intptr_t Heap::CommittedMemoryExecutable() {
217   if (!HasBeenSetUp()) return 0;
218
219   return isolate()->memory_allocator()->SizeExecutable();
220 }
221
222
223 void Heap::UpdateMaximumCommitted() {
224   if (!HasBeenSetUp()) return;
225
226   intptr_t current_committed_memory = CommittedMemory();
227   if (current_committed_memory > maximum_committed_) {
228     maximum_committed_ = current_committed_memory;
229   }
230 }
231
232
233 intptr_t Heap::Available() {
234   if (!HasBeenSetUp()) return 0;
235
236   intptr_t total = 0;
237   AllSpaces spaces(this);
238   for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
239     total += space->Available();
240   }
241   return total;
242 }
243
244
245 bool Heap::HasBeenSetUp() {
246   return old_space_ != NULL && code_space_ != NULL && map_space_ != NULL &&
247          lo_space_ != NULL;
248 }
249
250
251 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
252                                               const char** reason) {
253   // Is global GC requested?
254   if (space != NEW_SPACE) {
255     isolate_->counters()->gc_compactor_caused_by_request()->Increment();
256     *reason = "GC in old space requested";
257     return MARK_COMPACTOR;
258   }
259
260   if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
261     *reason = "GC in old space forced by flags";
262     return MARK_COMPACTOR;
263   }
264
265   // Is enough data promoted to justify a global GC?
266   if (OldGenerationAllocationLimitReached()) {
267     isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
268     *reason = "promotion limit reached";
269     return MARK_COMPACTOR;
270   }
271
272   // Have allocation in OLD and LO failed?
273   if (old_gen_exhausted_) {
274     isolate_->counters()
275         ->gc_compactor_caused_by_oldspace_exhaustion()
276         ->Increment();
277     *reason = "old generations exhausted";
278     return MARK_COMPACTOR;
279   }
280
281   // Is there enough space left in OLD to guarantee that a scavenge can
282   // succeed?
283   //
284   // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
285   // for object promotion. It counts only the bytes that the memory
286   // allocator has not yet allocated from the OS and assigned to any space,
287   // and does not count available bytes already in the old space or code
288   // space.  Undercounting is safe---we may get an unrequested full GC when
289   // a scavenge would have succeeded.
290   if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
291     isolate_->counters()
292         ->gc_compactor_caused_by_oldspace_exhaustion()
293         ->Increment();
294     *reason = "scavenge might not succeed";
295     return MARK_COMPACTOR;
296   }
297
298   // Default
299   *reason = NULL;
300   return SCAVENGER;
301 }
302
303
304 // TODO(1238405): Combine the infrastructure for --heap-stats and
305 // --log-gc to avoid the complicated preprocessor and flag testing.
306 void Heap::ReportStatisticsBeforeGC() {
307 // Heap::ReportHeapStatistics will also log NewSpace statistics when
308 // compiled --log-gc is set.  The following logic is used to avoid
309 // double logging.
310 #ifdef DEBUG
311   if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
312   if (FLAG_heap_stats) {
313     ReportHeapStatistics("Before GC");
314   } else if (FLAG_log_gc) {
315     new_space_.ReportStatistics();
316   }
317   if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
318 #else
319   if (FLAG_log_gc) {
320     new_space_.CollectStatistics();
321     new_space_.ReportStatistics();
322     new_space_.ClearHistograms();
323   }
324 #endif  // DEBUG
325 }
326
327
328 void Heap::PrintShortHeapStatistics() {
329   if (!FLAG_trace_gc_verbose) return;
330   PrintIsolate(isolate_, "Memory allocator,   used: %6" V8_PTR_PREFIX
331                          "d KB"
332                          ", available: %6" V8_PTR_PREFIX "d KB\n",
333                isolate_->memory_allocator()->Size() / KB,
334                isolate_->memory_allocator()->Available() / KB);
335   PrintIsolate(isolate_, "New space,          used: %6" V8_PTR_PREFIX
336                          "d KB"
337                          ", available: %6" V8_PTR_PREFIX
338                          "d KB"
339                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
340                new_space_.Size() / KB, new_space_.Available() / KB,
341                new_space_.CommittedMemory() / KB);
342   PrintIsolate(isolate_, "Old space,          used: %6" V8_PTR_PREFIX
343                          "d KB"
344                          ", available: %6" V8_PTR_PREFIX
345                          "d KB"
346                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
347                old_space_->SizeOfObjects() / KB, old_space_->Available() / KB,
348                old_space_->CommittedMemory() / KB);
349   PrintIsolate(isolate_, "Code space,         used: %6" V8_PTR_PREFIX
350                          "d KB"
351                          ", available: %6" V8_PTR_PREFIX
352                          "d KB"
353                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
354                code_space_->SizeOfObjects() / KB, code_space_->Available() / KB,
355                code_space_->CommittedMemory() / KB);
356   PrintIsolate(isolate_, "Map space,          used: %6" V8_PTR_PREFIX
357                          "d KB"
358                          ", available: %6" V8_PTR_PREFIX
359                          "d KB"
360                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
361                map_space_->SizeOfObjects() / KB, map_space_->Available() / KB,
362                map_space_->CommittedMemory() / KB);
363   PrintIsolate(isolate_, "Large object space, used: %6" V8_PTR_PREFIX
364                          "d KB"
365                          ", available: %6" V8_PTR_PREFIX
366                          "d KB"
367                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
368                lo_space_->SizeOfObjects() / KB, lo_space_->Available() / KB,
369                lo_space_->CommittedMemory() / KB);
370   PrintIsolate(isolate_, "All spaces,         used: %6" V8_PTR_PREFIX
371                          "d KB"
372                          ", available: %6" V8_PTR_PREFIX
373                          "d KB"
374                          ", committed: %6" V8_PTR_PREFIX "d KB\n",
375                this->SizeOfObjects() / KB, this->Available() / KB,
376                this->CommittedMemory() / KB);
377   PrintIsolate(
378       isolate_, "External memory reported: %6" V8_PTR_PREFIX "d KB\n",
379       static_cast<intptr_t>(amount_of_external_allocated_memory_ / KB));
380   PrintIsolate(isolate_, "Total time spent in GC  : %.1f ms\n",
381                total_gc_time_ms_);
382 }
383
384
385 // TODO(1238405): Combine the infrastructure for --heap-stats and
386 // --log-gc to avoid the complicated preprocessor and flag testing.
387 void Heap::ReportStatisticsAfterGC() {
388 // Similar to the before GC, we use some complicated logic to ensure that
389 // NewSpace statistics are logged exactly once when --log-gc is turned on.
390 #if defined(DEBUG)
391   if (FLAG_heap_stats) {
392     new_space_.CollectStatistics();
393     ReportHeapStatistics("After GC");
394   } else if (FLAG_log_gc) {
395     new_space_.ReportStatistics();
396   }
397 #else
398   if (FLAG_log_gc) new_space_.ReportStatistics();
399 #endif  // DEBUG
400   for (int i = 0; i < static_cast<int>(v8::Isolate::kUseCounterFeatureCount);
401        ++i) {
402     int count = deferred_counters_[i];
403     deferred_counters_[i] = 0;
404     while (count > 0) {
405       count--;
406       isolate()->CountUsage(static_cast<v8::Isolate::UseCounterFeature>(i));
407     }
408   }
409 }
410
411
412 void Heap::IncrementDeferredCount(v8::Isolate::UseCounterFeature feature) {
413   deferred_counters_[feature]++;
414 }
415
416
417 void Heap::GarbageCollectionPrologue() {
418   {
419     AllowHeapAllocation for_the_first_part_of_prologue;
420     gc_count_++;
421     unflattened_strings_length_ = 0;
422
423     if (FLAG_flush_code) {
424       mark_compact_collector()->EnableCodeFlushing(true);
425     }
426
427 #ifdef VERIFY_HEAP
428     if (FLAG_verify_heap) {
429       Verify();
430     }
431 #endif
432   }
433
434   // Reset GC statistics.
435   promoted_objects_size_ = 0;
436   previous_semi_space_copied_object_size_ = semi_space_copied_object_size_;
437   semi_space_copied_object_size_ = 0;
438   nodes_died_in_new_space_ = 0;
439   nodes_copied_in_new_space_ = 0;
440   nodes_promoted_ = 0;
441
442   UpdateMaximumCommitted();
443
444 #ifdef DEBUG
445   DCHECK(!AllowHeapAllocation::IsAllowed() && gc_state_ == NOT_IN_GC);
446
447   if (FLAG_gc_verbose) Print();
448
449   ReportStatisticsBeforeGC();
450 #endif  // DEBUG
451
452   store_buffer()->GCPrologue();
453
454   if (isolate()->concurrent_osr_enabled()) {
455     isolate()->optimizing_compile_dispatcher()->AgeBufferedOsrJobs();
456   }
457
458   if (new_space_.IsAtMaximumCapacity()) {
459     maximum_size_scavenges_++;
460   } else {
461     maximum_size_scavenges_ = 0;
462   }
463   CheckNewSpaceExpansionCriteria();
464   UpdateNewSpaceAllocationCounter();
465 }
466
467
468 intptr_t Heap::SizeOfObjects() {
469   intptr_t total = 0;
470   AllSpaces spaces(this);
471   for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
472     total += space->SizeOfObjects();
473   }
474   return total;
475 }
476
477
478 const char* Heap::GetSpaceName(int idx) {
479   switch (idx) {
480     case NEW_SPACE:
481       return "new_space";
482     case OLD_SPACE:
483       return "old_space";
484     case MAP_SPACE:
485       return "map_space";
486     case CODE_SPACE:
487       return "code_space";
488     case LO_SPACE:
489       return "large_object_space";
490     default:
491       UNREACHABLE();
492   }
493   return nullptr;
494 }
495
496
497 void Heap::ClearAllICsByKind(Code::Kind kind) {
498   // TODO(mvstanton): Do not iterate the heap.
499   HeapObjectIterator it(code_space());
500
501   for (Object* object = it.Next(); object != NULL; object = it.Next()) {
502     Code* code = Code::cast(object);
503     Code::Kind current_kind = code->kind();
504     if (current_kind == Code::FUNCTION ||
505         current_kind == Code::OPTIMIZED_FUNCTION) {
506       code->ClearInlineCaches(kind);
507     }
508   }
509 }
510
511
512 void Heap::RepairFreeListsAfterDeserialization() {
513   PagedSpaces spaces(this);
514   for (PagedSpace* space = spaces.next(); space != NULL;
515        space = spaces.next()) {
516     space->RepairFreeListsAfterDeserialization();
517   }
518 }
519
520
521 bool Heap::ProcessPretenuringFeedback() {
522   bool trigger_deoptimization = false;
523   if (FLAG_allocation_site_pretenuring) {
524     int tenure_decisions = 0;
525     int dont_tenure_decisions = 0;
526     int allocation_mementos_found = 0;
527     int allocation_sites = 0;
528     int active_allocation_sites = 0;
529
530     // If the scratchpad overflowed, we have to iterate over the allocation
531     // sites list.
532     // TODO(hpayer): We iterate over the whole list of allocation sites when
533     // we grew to the maximum semi-space size to deopt maybe tenured
534     // allocation sites. We could hold the maybe tenured allocation sites
535     // in a seperate data structure if this is a performance problem.
536     bool deopt_maybe_tenured = DeoptMaybeTenuredAllocationSites();
537     bool use_scratchpad =
538         allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize &&
539         !deopt_maybe_tenured;
540
541     int i = 0;
542     Object* list_element = allocation_sites_list();
543     bool maximum_size_scavenge = MaximumSizeScavenge();
544     while (use_scratchpad ? i < allocation_sites_scratchpad_length_
545                           : list_element->IsAllocationSite()) {
546       AllocationSite* site =
547           use_scratchpad
548               ? AllocationSite::cast(allocation_sites_scratchpad()->get(i))
549               : AllocationSite::cast(list_element);
550       allocation_mementos_found += site->memento_found_count();
551       if (site->memento_found_count() > 0) {
552         active_allocation_sites++;
553         if (site->DigestPretenuringFeedback(maximum_size_scavenge)) {
554           trigger_deoptimization = true;
555         }
556         if (site->GetPretenureMode() == TENURED) {
557           tenure_decisions++;
558         } else {
559           dont_tenure_decisions++;
560         }
561         allocation_sites++;
562       }
563
564       if (deopt_maybe_tenured && site->IsMaybeTenure()) {
565         site->set_deopt_dependent_code(true);
566         trigger_deoptimization = true;
567       }
568
569       if (use_scratchpad) {
570         i++;
571       } else {
572         list_element = site->weak_next();
573       }
574     }
575
576     if (trigger_deoptimization) {
577       isolate_->stack_guard()->RequestDeoptMarkedAllocationSites();
578     }
579
580     FlushAllocationSitesScratchpad();
581
582     if (FLAG_trace_pretenuring_statistics &&
583         (allocation_mementos_found > 0 || tenure_decisions > 0 ||
584          dont_tenure_decisions > 0)) {
585       PrintF(
586           "GC: (mode, #visited allocation sites, #active allocation sites, "
587           "#mementos, #tenure decisions, #donttenure decisions) "
588           "(%s, %d, %d, %d, %d, %d)\n",
589           use_scratchpad ? "use scratchpad" : "use list", allocation_sites,
590           active_allocation_sites, allocation_mementos_found, tenure_decisions,
591           dont_tenure_decisions);
592     }
593   }
594   return trigger_deoptimization;
595 }
596
597
598 void Heap::DeoptMarkedAllocationSites() {
599   // TODO(hpayer): If iterating over the allocation sites list becomes a
600   // performance issue, use a cache heap data structure instead (similar to the
601   // allocation sites scratchpad).
602   Object* list_element = allocation_sites_list();
603   while (list_element->IsAllocationSite()) {
604     AllocationSite* site = AllocationSite::cast(list_element);
605     if (site->deopt_dependent_code()) {
606       site->dependent_code()->MarkCodeForDeoptimization(
607           isolate_, DependentCode::kAllocationSiteTenuringChangedGroup);
608       site->set_deopt_dependent_code(false);
609     }
610     list_element = site->weak_next();
611   }
612   Deoptimizer::DeoptimizeMarkedCode(isolate_);
613 }
614
615
616 void Heap::GarbageCollectionEpilogue() {
617   store_buffer()->GCEpilogue();
618
619   // In release mode, we only zap the from space under heap verification.
620   if (Heap::ShouldZapGarbage()) {
621     ZapFromSpace();
622   }
623
624 #ifdef VERIFY_HEAP
625   if (FLAG_verify_heap) {
626     Verify();
627   }
628 #endif
629
630   AllowHeapAllocation for_the_rest_of_the_epilogue;
631
632 #ifdef DEBUG
633   if (FLAG_print_global_handles) isolate_->global_handles()->Print();
634   if (FLAG_print_handles) PrintHandles();
635   if (FLAG_gc_verbose) Print();
636   if (FLAG_code_stats) ReportCodeStatistics("After GC");
637   if (FLAG_check_handle_count) CheckHandleCount();
638 #endif
639   if (FLAG_deopt_every_n_garbage_collections > 0) {
640     // TODO(jkummerow/ulan/jarin): This is not safe! We can't assume that
641     // the topmost optimized frame can be deoptimized safely, because it
642     // might not have a lazy bailout point right after its current PC.
643     if (++gcs_since_last_deopt_ == FLAG_deopt_every_n_garbage_collections) {
644       Deoptimizer::DeoptimizeAll(isolate());
645       gcs_since_last_deopt_ = 0;
646     }
647   }
648
649   UpdateMaximumCommitted();
650
651   isolate_->counters()->alive_after_last_gc()->Set(
652       static_cast<int>(SizeOfObjects()));
653
654   isolate_->counters()->string_table_capacity()->Set(
655       string_table()->Capacity());
656   isolate_->counters()->number_of_symbols()->Set(
657       string_table()->NumberOfElements());
658
659   if (full_codegen_bytes_generated_ + crankshaft_codegen_bytes_generated_ > 0) {
660     isolate_->counters()->codegen_fraction_crankshaft()->AddSample(
661         static_cast<int>((crankshaft_codegen_bytes_generated_ * 100.0) /
662                          (crankshaft_codegen_bytes_generated_ +
663                           full_codegen_bytes_generated_)));
664   }
665
666   if (CommittedMemory() > 0) {
667     isolate_->counters()->external_fragmentation_total()->AddSample(
668         static_cast<int>(100 - (SizeOfObjects() * 100.0) / CommittedMemory()));
669
670     isolate_->counters()->heap_fraction_new_space()->AddSample(static_cast<int>(
671         (new_space()->CommittedMemory() * 100.0) / CommittedMemory()));
672     isolate_->counters()->heap_fraction_old_space()->AddSample(static_cast<int>(
673         (old_space()->CommittedMemory() * 100.0) / CommittedMemory()));
674     isolate_->counters()->heap_fraction_code_space()->AddSample(
675         static_cast<int>((code_space()->CommittedMemory() * 100.0) /
676                          CommittedMemory()));
677     isolate_->counters()->heap_fraction_map_space()->AddSample(static_cast<int>(
678         (map_space()->CommittedMemory() * 100.0) / CommittedMemory()));
679     isolate_->counters()->heap_fraction_lo_space()->AddSample(static_cast<int>(
680         (lo_space()->CommittedMemory() * 100.0) / CommittedMemory()));
681
682     isolate_->counters()->heap_sample_total_committed()->AddSample(
683         static_cast<int>(CommittedMemory() / KB));
684     isolate_->counters()->heap_sample_total_used()->AddSample(
685         static_cast<int>(SizeOfObjects() / KB));
686     isolate_->counters()->heap_sample_map_space_committed()->AddSample(
687         static_cast<int>(map_space()->CommittedMemory() / KB));
688     isolate_->counters()->heap_sample_code_space_committed()->AddSample(
689         static_cast<int>(code_space()->CommittedMemory() / KB));
690
691     isolate_->counters()->heap_sample_maximum_committed()->AddSample(
692         static_cast<int>(MaximumCommittedMemory() / KB));
693   }
694
695 #define UPDATE_COUNTERS_FOR_SPACE(space)                \
696   isolate_->counters()->space##_bytes_available()->Set( \
697       static_cast<int>(space()->Available()));          \
698   isolate_->counters()->space##_bytes_committed()->Set( \
699       static_cast<int>(space()->CommittedMemory()));    \
700   isolate_->counters()->space##_bytes_used()->Set(      \
701       static_cast<int>(space()->SizeOfObjects()));
702 #define UPDATE_FRAGMENTATION_FOR_SPACE(space)                          \
703   if (space()->CommittedMemory() > 0) {                                \
704     isolate_->counters()->external_fragmentation_##space()->AddSample( \
705         static_cast<int>(100 -                                         \
706                          (space()->SizeOfObjects() * 100.0) /          \
707                              space()->CommittedMemory()));             \
708   }
709 #define UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(space) \
710   UPDATE_COUNTERS_FOR_SPACE(space)                         \
711   UPDATE_FRAGMENTATION_FOR_SPACE(space)
712
713   UPDATE_COUNTERS_FOR_SPACE(new_space)
714   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(old_space)
715   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(code_space)
716   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(map_space)
717   UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE(lo_space)
718 #undef UPDATE_COUNTERS_FOR_SPACE
719 #undef UPDATE_FRAGMENTATION_FOR_SPACE
720 #undef UPDATE_COUNTERS_AND_FRAGMENTATION_FOR_SPACE
721
722 #ifdef DEBUG
723   ReportStatisticsAfterGC();
724 #endif  // DEBUG
725
726   // Remember the last top pointer so that we can later find out
727   // whether we allocated in new space since the last GC.
728   new_space_top_after_last_gc_ = new_space()->top();
729   last_gc_time_ = MonotonicallyIncreasingTimeInMs();
730
731   ReduceNewSpaceSize();
732 }
733
734
735 void Heap::PreprocessStackTraces() {
736   if (!weak_stack_trace_list()->IsWeakFixedArray()) return;
737   WeakFixedArray* array = WeakFixedArray::cast(weak_stack_trace_list());
738   int length = array->Length();
739   for (int i = 0; i < length; i++) {
740     if (array->IsEmptySlot(i)) continue;
741     FixedArray* elements = FixedArray::cast(array->Get(i));
742     for (int j = 1; j < elements->length(); j += 4) {
743       Object* maybe_code = elements->get(j + 2);
744       // If GC happens while adding a stack trace to the weak fixed array,
745       // which has been copied into a larger backing store, we may run into
746       // a stack trace that has already been preprocessed. Guard against this.
747       if (!maybe_code->IsCode()) break;
748       Code* code = Code::cast(maybe_code);
749       int offset = Smi::cast(elements->get(j + 3))->value();
750       Address pc = code->address() + offset;
751       int pos = code->SourcePosition(pc);
752       elements->set(j + 2, Smi::FromInt(pos));
753     }
754   }
755   // We must not compact the weak fixed list here, as we may be in the middle
756   // of writing to it, when the GC triggered. Instead, we reset the root value.
757   set_weak_stack_trace_list(Smi::FromInt(0));
758 }
759
760
761 void Heap::HandleGCRequest() {
762   if (incremental_marking()->request_type() ==
763       IncrementalMarking::COMPLETE_MARKING) {
764     CollectAllGarbage(Heap::kNoGCFlags, "GC interrupt",
765                       incremental_marking()->CallbackFlags());
766     return;
767   }
768   DCHECK(FLAG_overapproximate_weak_closure);
769   if (!incremental_marking()->weak_closure_was_overapproximated()) {
770     OverApproximateWeakClosure("GC interrupt");
771   }
772 }
773
774
775 void Heap::OverApproximateWeakClosure(const char* gc_reason) {
776   if (FLAG_trace_incremental_marking) {
777     PrintF("[IncrementalMarking] Overapproximate weak closure (%s).\n",
778            gc_reason);
779   }
780
781   GCTracer::Scope gc_scope(tracer(),
782                            GCTracer::Scope::MC_INCREMENTAL_WEAKCLOSURE);
783
784   {
785     GCCallbacksScope scope(this);
786     if (scope.CheckReenter()) {
787       AllowHeapAllocation allow_allocation;
788       GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
789       VMState<EXTERNAL> state(isolate_);
790       HandleScope handle_scope(isolate_);
791       CallGCPrologueCallbacks(kGCTypeMarkSweepCompact, kNoGCCallbackFlags);
792     }
793   }
794   incremental_marking()->MarkObjectGroups();
795   {
796     GCCallbacksScope scope(this);
797     if (scope.CheckReenter()) {
798       AllowHeapAllocation allow_allocation;
799       GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
800       VMState<EXTERNAL> state(isolate_);
801       HandleScope handle_scope(isolate_);
802       CallGCEpilogueCallbacks(kGCTypeMarkSweepCompact, kNoGCCallbackFlags);
803     }
804   }
805 }
806
807
808 void Heap::CollectAllGarbage(int flags, const char* gc_reason,
809                              const v8::GCCallbackFlags gc_callback_flags) {
810   // Since we are ignoring the return value, the exact choice of space does
811   // not matter, so long as we do not specify NEW_SPACE, which would not
812   // cause a full GC.
813   mark_compact_collector_.SetFlags(flags);
814   CollectGarbage(OLD_SPACE, gc_reason, gc_callback_flags);
815   mark_compact_collector_.SetFlags(kNoGCFlags);
816 }
817
818
819 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
820   // Since we are ignoring the return value, the exact choice of space does
821   // not matter, so long as we do not specify NEW_SPACE, which would not
822   // cause a full GC.
823   // Major GC would invoke weak handle callbacks on weakly reachable
824   // handles, but won't collect weakly reachable objects until next
825   // major GC.  Therefore if we collect aggressively and weak handle callback
826   // has been invoked, we rerun major GC to release objects which become
827   // garbage.
828   // Note: as weak callbacks can execute arbitrary code, we cannot
829   // hope that eventually there will be no weak callbacks invocations.
830   // Therefore stop recollecting after several attempts.
831   if (isolate()->concurrent_recompilation_enabled()) {
832     // The optimizing compiler may be unnecessarily holding on to memory.
833     DisallowHeapAllocation no_recursive_gc;
834     isolate()->optimizing_compile_dispatcher()->Flush();
835   }
836   isolate()->ClearSerializerData();
837   mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
838                                      kReduceMemoryFootprintMask);
839   isolate_->compilation_cache()->Clear();
840   const int kMaxNumberOfAttempts = 7;
841   const int kMinNumberOfAttempts = 2;
842   for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
843     if (!CollectGarbage(MARK_COMPACTOR, gc_reason, NULL,
844                         v8::kGCCallbackFlagForced) &&
845         attempt + 1 >= kMinNumberOfAttempts) {
846       break;
847     }
848   }
849   mark_compact_collector()->SetFlags(kNoGCFlags);
850   new_space_.Shrink();
851   UncommitFromSpace();
852 }
853
854
855 void Heap::EnsureFillerObjectAtTop() {
856   // There may be an allocation memento behind every object in new space.
857   // If we evacuate a not full new space or if we are on the last page of
858   // the new space, then there may be uninitialized memory behind the top
859   // pointer of the new space page. We store a filler object there to
860   // identify the unused space.
861   Address from_top = new_space_.top();
862   // Check that from_top is inside its page (i.e., not at the end).
863   Address space_end = new_space_.ToSpaceEnd();
864   if (from_top < space_end) {
865     Page* page = Page::FromAddress(from_top);
866     if (page->Contains(from_top)) {
867       int remaining_in_page = static_cast<int>(page->area_end() - from_top);
868       CreateFillerObjectAt(from_top, remaining_in_page);
869     }
870   }
871 }
872
873
874 bool Heap::CollectGarbage(GarbageCollector collector, const char* gc_reason,
875                           const char* collector_reason,
876                           const v8::GCCallbackFlags gc_callback_flags) {
877   // The VM is in the GC state until exiting this function.
878   VMState<GC> state(isolate_);
879
880 #ifdef DEBUG
881   // Reset the allocation timeout to the GC interval, but make sure to
882   // allow at least a few allocations after a collection. The reason
883   // for this is that we have a lot of allocation sequences and we
884   // assume that a garbage collection will allow the subsequent
885   // allocation attempts to go through.
886   allocation_timeout_ = Max(6, FLAG_gc_interval);
887 #endif
888
889   EnsureFillerObjectAtTop();
890
891   if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
892     if (FLAG_trace_incremental_marking) {
893       PrintF("[IncrementalMarking] Scavenge during marking.\n");
894     }
895   }
896
897   if (collector == MARK_COMPACTOR &&
898       !mark_compact_collector()->finalize_incremental_marking() &&
899       !mark_compact_collector()->abort_incremental_marking() &&
900       !incremental_marking()->IsStopped() &&
901       !incremental_marking()->should_hurry() && FLAG_incremental_marking) {
902     // Make progress in incremental marking.
903     const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
904     incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
905                                 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
906     if (!incremental_marking()->IsComplete() &&
907         !mark_compact_collector_.marking_deque_.IsEmpty() && !FLAG_gc_global) {
908       if (FLAG_trace_incremental_marking) {
909         PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
910       }
911       collector = SCAVENGER;
912       collector_reason = "incremental marking delaying mark-sweep";
913     }
914   }
915
916   bool next_gc_likely_to_collect_more = false;
917   intptr_t committed_memory_before = 0;
918
919   if (collector == MARK_COMPACTOR) {
920     committed_memory_before = CommittedOldGenerationMemory();
921   }
922
923   {
924     tracer()->Start(collector, gc_reason, collector_reason);
925     DCHECK(AllowHeapAllocation::IsAllowed());
926     DisallowHeapAllocation no_allocation_during_gc;
927     GarbageCollectionPrologue();
928
929     {
930       HistogramTimerScope histogram_timer_scope(
931           (collector == SCAVENGER) ? isolate_->counters()->gc_scavenger()
932                                    : isolate_->counters()->gc_compactor());
933       next_gc_likely_to_collect_more =
934           PerformGarbageCollection(collector, gc_callback_flags);
935     }
936
937     GarbageCollectionEpilogue();
938     if (collector == MARK_COMPACTOR && FLAG_track_detached_contexts) {
939       isolate()->CheckDetachedContextsAfterGC();
940     }
941
942     if (collector == MARK_COMPACTOR) {
943       intptr_t committed_memory_after = CommittedOldGenerationMemory();
944       intptr_t used_memory_after = PromotedSpaceSizeOfObjects();
945       MemoryReducer::Event event;
946       event.type = MemoryReducer::kMarkCompact;
947       event.time_ms = MonotonicallyIncreasingTimeInMs();
948       // Trigger one more GC if
949       // - this GC decreased committed memory,
950       // - there is high fragmentation,
951       // - there are live detached contexts.
952       event.next_gc_likely_to_collect_more =
953           (committed_memory_before - committed_memory_after) > MB ||
954           HasHighFragmentation(used_memory_after, committed_memory_after) ||
955           (detached_contexts()->length() > 0);
956       if (deserialization_complete_) {
957         memory_reducer_.NotifyMarkCompact(event);
958       }
959     }
960
961     tracer()->Stop(collector);
962   }
963
964   if (collector == MARK_COMPACTOR &&
965       (gc_callback_flags & kGCCallbackFlagForced) != 0) {
966     isolate()->CountUsage(v8::Isolate::kForcedGC);
967   }
968
969   // Start incremental marking for the next cycle. The heap snapshot
970   // generator needs incremental marking to stay off after it aborted.
971   if (!mark_compact_collector()->abort_incremental_marking() &&
972       incremental_marking()->IsStopped() &&
973       incremental_marking()->ShouldActivateEvenWithoutIdleNotification()) {
974     incremental_marking()->Start(kNoGCFlags, kNoGCCallbackFlags, "GC epilogue");
975   }
976
977   return next_gc_likely_to_collect_more;
978 }
979
980
981 int Heap::NotifyContextDisposed(bool dependant_context) {
982   if (!dependant_context) {
983     tracer()->ResetSurvivalEvents();
984     old_generation_size_configured_ = false;
985   }
986   if (isolate()->concurrent_recompilation_enabled()) {
987     // Flush the queued recompilation tasks.
988     isolate()->optimizing_compile_dispatcher()->Flush();
989   }
990   AgeInlineCaches();
991   set_retained_maps(ArrayList::cast(empty_fixed_array()));
992   tracer()->AddContextDisposalTime(base::OS::TimeCurrentMillis());
993   MemoryReducer::Event event;
994   event.type = MemoryReducer::kContextDisposed;
995   event.time_ms = MonotonicallyIncreasingTimeInMs();
996   memory_reducer_.NotifyContextDisposed(event);
997   return ++contexts_disposed_;
998 }
999
1000
1001 void Heap::StartIncrementalMarking(int gc_flags,
1002                                    const GCCallbackFlags gc_callback_flags,
1003                                    const char* reason) {
1004   DCHECK(incremental_marking()->IsStopped());
1005   incremental_marking()->Start(gc_flags, gc_callback_flags, reason);
1006 }
1007
1008
1009 void Heap::StartIdleIncrementalMarking() {
1010   gc_idle_time_handler_.ResetNoProgressCounter();
1011   StartIncrementalMarking(kReduceMemoryFootprintMask, kNoGCCallbackFlags,
1012                           "idle");
1013 }
1014
1015
1016 void Heap::MoveElements(FixedArray* array, int dst_index, int src_index,
1017                         int len) {
1018   if (len == 0) return;
1019
1020   DCHECK(array->map() != fixed_cow_array_map());
1021   Object** dst_objects = array->data_start() + dst_index;
1022   MemMove(dst_objects, array->data_start() + src_index, len * kPointerSize);
1023   if (!InNewSpace(array)) {
1024     for (int i = 0; i < len; i++) {
1025       // TODO(hpayer): check store buffer for entries
1026       if (InNewSpace(dst_objects[i])) {
1027         RecordWrite(array->address(), array->OffsetOfElementAt(dst_index + i));
1028       }
1029     }
1030   }
1031   incremental_marking()->RecordWrites(array);
1032 }
1033
1034
1035 #ifdef VERIFY_HEAP
1036 // Helper class for verifying the string table.
1037 class StringTableVerifier : public ObjectVisitor {
1038  public:
1039   void VisitPointers(Object** start, Object** end) {
1040     // Visit all HeapObject pointers in [start, end).
1041     for (Object** p = start; p < end; p++) {
1042       if ((*p)->IsHeapObject()) {
1043         // Check that the string is actually internalized.
1044         CHECK((*p)->IsTheHole() || (*p)->IsUndefined() ||
1045               (*p)->IsInternalizedString());
1046       }
1047     }
1048   }
1049 };
1050
1051
1052 static void VerifyStringTable(Heap* heap) {
1053   StringTableVerifier verifier;
1054   heap->string_table()->IterateElements(&verifier);
1055 }
1056 #endif  // VERIFY_HEAP
1057
1058
1059 bool Heap::ReserveSpace(Reservation* reservations) {
1060   bool gc_performed = true;
1061   int counter = 0;
1062   static const int kThreshold = 20;
1063   while (gc_performed && counter++ < kThreshold) {
1064     gc_performed = false;
1065     for (int space = NEW_SPACE; space < Serializer::kNumberOfSpaces; space++) {
1066       Reservation* reservation = &reservations[space];
1067       DCHECK_LE(1, reservation->length());
1068       if (reservation->at(0).size == 0) continue;
1069       bool perform_gc = false;
1070       if (space == LO_SPACE) {
1071         DCHECK_EQ(1, reservation->length());
1072         perform_gc = !CanExpandOldGeneration(reservation->at(0).size);
1073       } else {
1074         for (auto& chunk : *reservation) {
1075           AllocationResult allocation;
1076           int size = chunk.size;
1077           DCHECK_LE(size, MemoryAllocator::PageAreaSize(
1078                               static_cast<AllocationSpace>(space)));
1079           if (space == NEW_SPACE) {
1080             allocation = new_space()->AllocateRawUnaligned(size);
1081           } else {
1082             allocation = paged_space(space)->AllocateRawUnaligned(size);
1083           }
1084           HeapObject* free_space;
1085           if (allocation.To(&free_space)) {
1086             // Mark with a free list node, in case we have a GC before
1087             // deserializing.
1088             Address free_space_address = free_space->address();
1089             CreateFillerObjectAt(free_space_address, size);
1090             DCHECK(space < Serializer::kNumberOfPreallocatedSpaces);
1091             chunk.start = free_space_address;
1092             chunk.end = free_space_address + size;
1093           } else {
1094             perform_gc = true;
1095             break;
1096           }
1097         }
1098       }
1099       if (perform_gc) {
1100         if (space == NEW_SPACE) {
1101           CollectGarbage(NEW_SPACE, "failed to reserve space in the new space");
1102         } else {
1103           if (counter > 1) {
1104             CollectAllGarbage(
1105                 kReduceMemoryFootprintMask | kAbortIncrementalMarkingMask,
1106                 "failed to reserve space in paged or large "
1107                 "object space, trying to reduce memory footprint");
1108           } else {
1109             CollectAllGarbage(
1110                 kAbortIncrementalMarkingMask,
1111                 "failed to reserve space in paged or large object space");
1112           }
1113         }
1114         gc_performed = true;
1115         break;  // Abort for-loop over spaces and retry.
1116       }
1117     }
1118   }
1119
1120   return !gc_performed;
1121 }
1122
1123
1124 void Heap::EnsureFromSpaceIsCommitted() {
1125   if (new_space_.CommitFromSpaceIfNeeded()) return;
1126
1127   // Committing memory to from space failed.
1128   // Memory is exhausted and we will die.
1129   V8::FatalProcessOutOfMemory("Committing semi space failed.");
1130 }
1131
1132
1133 void Heap::ClearNormalizedMapCaches() {
1134   if (isolate_->bootstrapper()->IsActive() &&
1135       !incremental_marking()->IsMarking()) {
1136     return;
1137   }
1138
1139   Object* context = native_contexts_list();
1140   while (!context->IsUndefined()) {
1141     // GC can happen when the context is not fully initialized,
1142     // so the cache can be undefined.
1143     Object* cache =
1144         Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
1145     if (!cache->IsUndefined()) {
1146       NormalizedMapCache::cast(cache)->Clear();
1147     }
1148     context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
1149   }
1150 }
1151
1152
1153 void Heap::UpdateSurvivalStatistics(int start_new_space_size) {
1154   if (start_new_space_size == 0) return;
1155
1156   promotion_ratio_ = (static_cast<double>(promoted_objects_size_) /
1157                       static_cast<double>(start_new_space_size) * 100);
1158
1159   if (previous_semi_space_copied_object_size_ > 0) {
1160     promotion_rate_ =
1161         (static_cast<double>(promoted_objects_size_) /
1162          static_cast<double>(previous_semi_space_copied_object_size_) * 100);
1163   } else {
1164     promotion_rate_ = 0;
1165   }
1166
1167   semi_space_copied_rate_ =
1168       (static_cast<double>(semi_space_copied_object_size_) /
1169        static_cast<double>(start_new_space_size) * 100);
1170
1171   double survival_rate = promotion_ratio_ + semi_space_copied_rate_;
1172   tracer()->AddSurvivalRatio(survival_rate);
1173   if (survival_rate > kYoungSurvivalRateHighThreshold) {
1174     high_survival_rate_period_length_++;
1175   } else {
1176     high_survival_rate_period_length_ = 0;
1177   }
1178 }
1179
1180 bool Heap::PerformGarbageCollection(
1181     GarbageCollector collector, const v8::GCCallbackFlags gc_callback_flags) {
1182   int freed_global_handles = 0;
1183
1184   if (collector != SCAVENGER) {
1185     PROFILE(isolate_, CodeMovingGCEvent());
1186   }
1187
1188 #ifdef VERIFY_HEAP
1189   if (FLAG_verify_heap) {
1190     VerifyStringTable(this);
1191   }
1192 #endif
1193
1194   GCType gc_type =
1195       collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
1196
1197   {
1198     GCCallbacksScope scope(this);
1199     if (scope.CheckReenter()) {
1200       AllowHeapAllocation allow_allocation;
1201       GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1202       VMState<EXTERNAL> state(isolate_);
1203       HandleScope handle_scope(isolate_);
1204       CallGCPrologueCallbacks(gc_type, kNoGCCallbackFlags);
1205     }
1206   }
1207
1208   EnsureFromSpaceIsCommitted();
1209
1210   int start_new_space_size = Heap::new_space()->SizeAsInt();
1211
1212   if (IsHighSurvivalRate()) {
1213     // We speed up the incremental marker if it is running so that it
1214     // does not fall behind the rate of promotion, which would cause a
1215     // constantly growing old space.
1216     incremental_marking()->NotifyOfHighPromotionRate();
1217   }
1218
1219   if (collector == MARK_COMPACTOR) {
1220     UpdateOldGenerationAllocationCounter();
1221     // Perform mark-sweep with optional compaction.
1222     MarkCompact();
1223     sweep_generation_++;
1224     old_gen_exhausted_ = false;
1225     old_generation_size_configured_ = true;
1226     // This should be updated before PostGarbageCollectionProcessing, which can
1227     // cause another GC. Take into account the objects promoted during GC.
1228     old_generation_allocation_counter_ +=
1229         static_cast<size_t>(promoted_objects_size_);
1230     old_generation_size_at_last_gc_ = PromotedSpaceSizeOfObjects();
1231   } else {
1232     Scavenge();
1233   }
1234
1235   ProcessPretenuringFeedback();
1236   UpdateSurvivalStatistics(start_new_space_size);
1237   ConfigureInitialOldGenerationSize();
1238
1239   isolate_->counters()->objs_since_last_young()->Set(0);
1240
1241   if (collector != SCAVENGER) {
1242     // Callbacks that fire after this point might trigger nested GCs and
1243     // restart incremental marking, the assertion can't be moved down.
1244     DCHECK(incremental_marking()->IsStopped());
1245
1246     // We finished a marking cycle. We can uncommit the marking deque until
1247     // we start marking again.
1248     mark_compact_collector_.marking_deque()->Uninitialize();
1249     mark_compact_collector_.EnsureMarkingDequeIsCommitted(
1250         MarkCompactCollector::kMinMarkingDequeSize);
1251   }
1252
1253   gc_post_processing_depth_++;
1254   {
1255     AllowHeapAllocation allow_allocation;
1256     GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1257     freed_global_handles =
1258         isolate_->global_handles()->PostGarbageCollectionProcessing(
1259             collector, gc_callback_flags);
1260   }
1261   gc_post_processing_depth_--;
1262
1263   isolate_->eternal_handles()->PostGarbageCollectionProcessing(this);
1264
1265   // Update relocatables.
1266   Relocatable::PostGarbageCollectionProcessing(isolate_);
1267
1268   double gc_speed = tracer()->CombinedMarkCompactSpeedInBytesPerMillisecond();
1269   double mutator_speed = static_cast<double>(
1270       tracer()
1271           ->CurrentOldGenerationAllocationThroughputInBytesPerMillisecond());
1272   intptr_t old_gen_size = PromotedSpaceSizeOfObjects();
1273   if (collector == MARK_COMPACTOR) {
1274     // Register the amount of external allocated memory.
1275     amount_of_external_allocated_memory_at_last_global_gc_ =
1276         amount_of_external_allocated_memory_;
1277     SetOldGenerationAllocationLimit(old_gen_size, gc_speed, mutator_speed);
1278   } else if (HasLowYoungGenerationAllocationRate() &&
1279              old_generation_size_configured_) {
1280     DampenOldGenerationAllocationLimit(old_gen_size, gc_speed, mutator_speed);
1281   }
1282
1283   {
1284     GCCallbacksScope scope(this);
1285     if (scope.CheckReenter()) {
1286       AllowHeapAllocation allow_allocation;
1287       GCTracer::Scope scope(tracer(), GCTracer::Scope::EXTERNAL);
1288       VMState<EXTERNAL> state(isolate_);
1289       HandleScope handle_scope(isolate_);
1290       CallGCEpilogueCallbacks(gc_type, gc_callback_flags);
1291     }
1292   }
1293
1294 #ifdef VERIFY_HEAP
1295   if (FLAG_verify_heap) {
1296     VerifyStringTable(this);
1297   }
1298 #endif
1299
1300   return freed_global_handles > 0;
1301 }
1302
1303
1304 void Heap::CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags) {
1305   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
1306     if (gc_type & gc_prologue_callbacks_[i].gc_type) {
1307       if (!gc_prologue_callbacks_[i].pass_isolate_) {
1308         v8::GCPrologueCallback callback =
1309             reinterpret_cast<v8::GCPrologueCallback>(
1310                 gc_prologue_callbacks_[i].callback);
1311         callback(gc_type, flags);
1312       } else {
1313         v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate());
1314         gc_prologue_callbacks_[i].callback(isolate, gc_type, flags);
1315       }
1316     }
1317   }
1318 }
1319
1320
1321 void Heap::CallGCEpilogueCallbacks(GCType gc_type,
1322                                    GCCallbackFlags gc_callback_flags) {
1323   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
1324     if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
1325       if (!gc_epilogue_callbacks_[i].pass_isolate_) {
1326         v8::GCPrologueCallback callback =
1327             reinterpret_cast<v8::GCPrologueCallback>(
1328                 gc_epilogue_callbacks_[i].callback);
1329         callback(gc_type, gc_callback_flags);
1330       } else {
1331         v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this->isolate());
1332         gc_epilogue_callbacks_[i].callback(isolate, gc_type, gc_callback_flags);
1333       }
1334     }
1335   }
1336 }
1337
1338
1339 void Heap::MarkCompact() {
1340   gc_state_ = MARK_COMPACT;
1341   LOG(isolate_, ResourceEvent("markcompact", "begin"));
1342
1343   uint64_t size_of_objects_before_gc = SizeOfObjects();
1344
1345   mark_compact_collector_.Prepare();
1346
1347   ms_count_++;
1348
1349   MarkCompactPrologue();
1350
1351   mark_compact_collector_.CollectGarbage();
1352
1353   LOG(isolate_, ResourceEvent("markcompact", "end"));
1354
1355   MarkCompactEpilogue();
1356
1357   if (FLAG_allocation_site_pretenuring) {
1358     EvaluateOldSpaceLocalPretenuring(size_of_objects_before_gc);
1359   }
1360 }
1361
1362
1363 void Heap::MarkCompactEpilogue() {
1364   gc_state_ = NOT_IN_GC;
1365
1366   isolate_->counters()->objs_since_last_full()->Set(0);
1367
1368   incremental_marking()->Epilogue();
1369
1370   PreprocessStackTraces();
1371 }
1372
1373
1374 void Heap::MarkCompactPrologue() {
1375   // At any old GC clear the keyed lookup cache to enable collection of unused
1376   // maps.
1377   isolate_->keyed_lookup_cache()->Clear();
1378   isolate_->context_slot_cache()->Clear();
1379   isolate_->descriptor_lookup_cache()->Clear();
1380   RegExpResultsCache::Clear(string_split_cache());
1381   RegExpResultsCache::Clear(regexp_multiple_cache());
1382
1383   isolate_->compilation_cache()->MarkCompactPrologue();
1384
1385   CompletelyClearInstanceofCache();
1386
1387   FlushNumberStringCache();
1388   if (FLAG_cleanup_code_caches_at_gc) {
1389     polymorphic_code_cache()->set_cache(undefined_value());
1390   }
1391
1392   ClearNormalizedMapCaches();
1393 }
1394
1395
1396 // Helper class for copying HeapObjects
1397 class ScavengeVisitor : public ObjectVisitor {
1398  public:
1399   explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
1400
1401   void VisitPointer(Object** p) { ScavengePointer(p); }
1402
1403   void VisitPointers(Object** start, Object** end) {
1404     // Copy all HeapObject pointers in [start, end)
1405     for (Object** p = start; p < end; p++) ScavengePointer(p);
1406   }
1407
1408  private:
1409   void ScavengePointer(Object** p) {
1410     Object* object = *p;
1411     if (!heap_->InNewSpace(object)) return;
1412     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1413                          reinterpret_cast<HeapObject*>(object));
1414   }
1415
1416   Heap* heap_;
1417 };
1418
1419
1420 #ifdef VERIFY_HEAP
1421 // Visitor class to verify pointers in code or data space do not point into
1422 // new space.
1423 class VerifyNonPointerSpacePointersVisitor : public ObjectVisitor {
1424  public:
1425   explicit VerifyNonPointerSpacePointersVisitor(Heap* heap) : heap_(heap) {}
1426   void VisitPointers(Object** start, Object** end) {
1427     for (Object** current = start; current < end; current++) {
1428       if ((*current)->IsHeapObject()) {
1429         CHECK(!heap_->InNewSpace(HeapObject::cast(*current)));
1430       }
1431     }
1432   }
1433
1434  private:
1435   Heap* heap_;
1436 };
1437
1438
1439 static void VerifyNonPointerSpacePointers(Heap* heap) {
1440   // Verify that there are no pointers to new space in spaces where we
1441   // do not expect them.
1442   VerifyNonPointerSpacePointersVisitor v(heap);
1443   HeapObjectIterator code_it(heap->code_space());
1444   for (HeapObject* object = code_it.Next(); object != NULL;
1445        object = code_it.Next())
1446     object->Iterate(&v);
1447 }
1448 #endif  // VERIFY_HEAP
1449
1450
1451 void Heap::CheckNewSpaceExpansionCriteria() {
1452   if (FLAG_experimental_new_space_growth_heuristic) {
1453     if (new_space_.TotalCapacity() < new_space_.MaximumCapacity() &&
1454         survived_last_scavenge_ * 100 / new_space_.TotalCapacity() >= 10) {
1455       // Grow the size of new space if there is room to grow, and more than 10%
1456       // have survived the last scavenge.
1457       new_space_.Grow();
1458       survived_since_last_expansion_ = 0;
1459     }
1460   } else if (new_space_.TotalCapacity() < new_space_.MaximumCapacity() &&
1461              survived_since_last_expansion_ > new_space_.TotalCapacity()) {
1462     // Grow the size of new space if there is room to grow, and enough data
1463     // has survived scavenge since the last expansion.
1464     new_space_.Grow();
1465     survived_since_last_expansion_ = 0;
1466   }
1467 }
1468
1469
1470 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1471   return heap->InNewSpace(*p) &&
1472          !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1473 }
1474
1475
1476 void Heap::ScavengeStoreBufferCallback(Heap* heap, MemoryChunk* page,
1477                                        StoreBufferEvent event) {
1478   heap->store_buffer_rebuilder_.Callback(page, event);
1479 }
1480
1481
1482 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1483   if (event == kStoreBufferStartScanningPagesEvent) {
1484     start_of_current_page_ = NULL;
1485     current_page_ = NULL;
1486   } else if (event == kStoreBufferScanningPageEvent) {
1487     if (current_page_ != NULL) {
1488       // If this page already overflowed the store buffer during this iteration.
1489       if (current_page_->scan_on_scavenge()) {
1490         // Then we should wipe out the entries that have been added for it.
1491         store_buffer_->SetTop(start_of_current_page_);
1492       } else if (store_buffer_->Top() - start_of_current_page_ >=
1493                  (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1494         // Did we find too many pointers in the previous page?  The heuristic is
1495         // that no page can take more then 1/5 the remaining slots in the store
1496         // buffer.
1497         current_page_->set_scan_on_scavenge(true);
1498         store_buffer_->SetTop(start_of_current_page_);
1499       } else {
1500         // In this case the page we scanned took a reasonable number of slots in
1501         // the store buffer.  It has now been rehabilitated and is no longer
1502         // marked scan_on_scavenge.
1503         DCHECK(!current_page_->scan_on_scavenge());
1504       }
1505     }
1506     start_of_current_page_ = store_buffer_->Top();
1507     current_page_ = page;
1508   } else if (event == kStoreBufferFullEvent) {
1509     // The current page overflowed the store buffer again.  Wipe out its entries
1510     // in the store buffer and mark it scan-on-scavenge again.  This may happen
1511     // several times while scanning.
1512     if (current_page_ == NULL) {
1513       // Store Buffer overflowed while scanning promoted objects.  These are not
1514       // in any particular page, though they are likely to be clustered by the
1515       // allocation routines.
1516       store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize / 2);
1517     } else {
1518       // Store Buffer overflowed while scanning a particular old space page for
1519       // pointers to new space.
1520       DCHECK(current_page_ == page);
1521       DCHECK(page != NULL);
1522       current_page_->set_scan_on_scavenge(true);
1523       DCHECK(start_of_current_page_ != store_buffer_->Top());
1524       store_buffer_->SetTop(start_of_current_page_);
1525     }
1526   } else {
1527     UNREACHABLE();
1528   }
1529 }
1530
1531
1532 void PromotionQueue::Initialize() {
1533   // The last to-space page may be used for promotion queue. On promotion
1534   // conflict, we use the emergency stack.
1535   DCHECK((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize) ==
1536          0);
1537   front_ = rear_ =
1538       reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1539   limit_ = reinterpret_cast<intptr_t*>(
1540       Page::FromAllocationTop(reinterpret_cast<Address>(rear_))->area_start());
1541   emergency_stack_ = NULL;
1542 }
1543
1544
1545 void PromotionQueue::RelocateQueueHead() {
1546   DCHECK(emergency_stack_ == NULL);
1547
1548   Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1549   intptr_t* head_start = rear_;
1550   intptr_t* head_end = Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1551
1552   int entries_count =
1553       static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1554
1555   emergency_stack_ = new List<Entry>(2 * entries_count);
1556
1557   while (head_start != head_end) {
1558     int size = static_cast<int>(*(head_start++));
1559     HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1560     // New space allocation in SemiSpaceCopyObject marked the region
1561     // overlapping with promotion queue as uninitialized.
1562     MSAN_MEMORY_IS_INITIALIZED(&size, sizeof(size));
1563     MSAN_MEMORY_IS_INITIALIZED(&obj, sizeof(obj));
1564     emergency_stack_->Add(Entry(obj, size));
1565   }
1566   rear_ = head_end;
1567 }
1568
1569
1570 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1571  public:
1572   explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) {}
1573
1574   virtual Object* RetainAs(Object* object) {
1575     if (!heap_->InFromSpace(object)) {
1576       return object;
1577     }
1578
1579     MapWord map_word = HeapObject::cast(object)->map_word();
1580     if (map_word.IsForwardingAddress()) {
1581       return map_word.ToForwardingAddress();
1582     }
1583     return NULL;
1584   }
1585
1586  private:
1587   Heap* heap_;
1588 };
1589
1590
1591 void Heap::Scavenge() {
1592   GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_SCAVENGE);
1593   RelocationLock relocation_lock(this);
1594   // There are soft limits in the allocation code, designed to trigger a mark
1595   // sweep collection by failing allocations. There is no sense in trying to
1596   // trigger one during scavenge: scavenges allocation should always succeed.
1597   AlwaysAllocateScope scope(isolate());
1598
1599 #ifdef VERIFY_HEAP
1600   if (FLAG_verify_heap) VerifyNonPointerSpacePointers(this);
1601 #endif
1602
1603   gc_state_ = SCAVENGE;
1604
1605   // Implements Cheney's copying algorithm
1606   LOG(isolate_, ResourceEvent("scavenge", "begin"));
1607
1608   // Clear descriptor cache.
1609   isolate_->descriptor_lookup_cache()->Clear();
1610
1611   // Used for updating survived_since_last_expansion_ at function end.
1612   intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1613
1614   SelectScavengingVisitorsTable();
1615
1616   PrepareArrayBufferDiscoveryInNewSpace();
1617
1618   // Flip the semispaces.  After flipping, to space is empty, from space has
1619   // live objects.
1620   new_space_.Flip();
1621   new_space_.ResetAllocationInfo();
1622
1623   // We need to sweep newly copied objects which can be either in the
1624   // to space or promoted to the old generation.  For to-space
1625   // objects, we treat the bottom of the to space as a queue.  Newly
1626   // copied and unswept objects lie between a 'front' mark and the
1627   // allocation pointer.
1628   //
1629   // Promoted objects can go into various old-generation spaces, and
1630   // can be allocated internally in the spaces (from the free list).
1631   // We treat the top of the to space as a queue of addresses of
1632   // promoted objects.  The addresses of newly promoted and unswept
1633   // objects lie between a 'front' mark and a 'rear' mark that is
1634   // updated as a side effect of promoting an object.
1635   //
1636   // There is guaranteed to be enough room at the top of the to space
1637   // for the addresses of promoted objects: every object promoted
1638   // frees up its size in bytes from the top of the new space, and
1639   // objects are at least one pointer in size.
1640   Address new_space_front = new_space_.ToSpaceStart();
1641   promotion_queue_.Initialize();
1642
1643   ScavengeVisitor scavenge_visitor(this);
1644   {
1645     // Copy roots.
1646     GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_ROOTS);
1647     IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1648   }
1649
1650   {
1651     // Copy objects reachable from the old generation.
1652     GCTracer::Scope gc_scope(tracer(),
1653                              GCTracer::Scope::SCAVENGER_OLD_TO_NEW_POINTERS);
1654     StoreBufferRebuildScope scope(this, store_buffer(),
1655                                   &ScavengeStoreBufferCallback);
1656     store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1657   }
1658
1659   {
1660     GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_WEAK);
1661     // Copy objects reachable from the encountered weak collections list.
1662     scavenge_visitor.VisitPointer(&encountered_weak_collections_);
1663     // Copy objects reachable from the encountered weak cells.
1664     scavenge_visitor.VisitPointer(&encountered_weak_cells_);
1665   }
1666
1667   {
1668     // Copy objects reachable from the code flushing candidates list.
1669     GCTracer::Scope gc_scope(tracer(),
1670                              GCTracer::Scope::SCAVENGER_CODE_FLUSH_CANDIDATES);
1671     MarkCompactCollector* collector = mark_compact_collector();
1672     if (collector->is_code_flushing_enabled()) {
1673       collector->code_flusher()->IteratePointersToFromSpace(&scavenge_visitor);
1674     }
1675   }
1676
1677   {
1678     GCTracer::Scope gc_scope(tracer(), GCTracer::Scope::SCAVENGER_SEMISPACE);
1679     new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1680   }
1681
1682   {
1683     GCTracer::Scope gc_scope(tracer(),
1684                              GCTracer::Scope::SCAVENGER_OBJECT_GROUPS);
1685     while (isolate()->global_handles()->IterateObjectGroups(
1686         &scavenge_visitor, &IsUnscavengedHeapObject)) {
1687       new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1688     }
1689     isolate()->global_handles()->RemoveObjectGroups();
1690     isolate()->global_handles()->RemoveImplicitRefGroups();
1691   }
1692
1693   isolate()->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1694       &IsUnscavengedHeapObject);
1695
1696   isolate()->global_handles()->IterateNewSpaceWeakIndependentRoots(
1697       &scavenge_visitor);
1698   new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1699
1700   UpdateNewSpaceReferencesInExternalStringTable(
1701       &UpdateNewSpaceReferenceInExternalStringTableEntry);
1702
1703   promotion_queue_.Destroy();
1704
1705   incremental_marking()->UpdateMarkingDequeAfterScavenge();
1706
1707   ScavengeWeakObjectRetainer weak_object_retainer(this);
1708   ProcessYoungWeakReferences(&weak_object_retainer);
1709
1710   DCHECK(new_space_front == new_space_.top());
1711
1712   // Set age mark.
1713   new_space_.set_age_mark(new_space_.top());
1714
1715   new_space_.LowerInlineAllocationLimit(
1716       new_space_.inline_allocation_limit_step());
1717
1718   FreeDeadArrayBuffers(true);
1719
1720   // Update how much has survived scavenge.
1721   IncrementYoungSurvivorsCounter(static_cast<int>(
1722       (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1723
1724   LOG(isolate_, ResourceEvent("scavenge", "end"));
1725
1726   gc_state_ = NOT_IN_GC;
1727 }
1728
1729
1730 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1731                                                                 Object** p) {
1732   MapWord first_word = HeapObject::cast(*p)->map_word();
1733
1734   if (!first_word.IsForwardingAddress()) {
1735     // Unreachable external string can be finalized.
1736     heap->FinalizeExternalString(String::cast(*p));
1737     return NULL;
1738   }
1739
1740   // String is still reachable.
1741   return String::cast(first_word.ToForwardingAddress());
1742 }
1743
1744
1745 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1746     ExternalStringTableUpdaterCallback updater_func) {
1747 #ifdef VERIFY_HEAP
1748   if (FLAG_verify_heap) {
1749     external_string_table_.Verify();
1750   }
1751 #endif
1752
1753   if (external_string_table_.new_space_strings_.is_empty()) return;
1754
1755   Object** start = &external_string_table_.new_space_strings_[0];
1756   Object** end = start + external_string_table_.new_space_strings_.length();
1757   Object** last = start;
1758
1759   for (Object** p = start; p < end; ++p) {
1760     DCHECK(InFromSpace(*p));
1761     String* target = updater_func(this, p);
1762
1763     if (target == NULL) continue;
1764
1765     DCHECK(target->IsExternalString());
1766
1767     if (InNewSpace(target)) {
1768       // String is still in new space.  Update the table entry.
1769       *last = target;
1770       ++last;
1771     } else {
1772       // String got promoted.  Move it to the old string list.
1773       external_string_table_.AddOldString(target);
1774     }
1775   }
1776
1777   DCHECK(last <= end);
1778   external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1779 }
1780
1781
1782 void Heap::UpdateReferencesInExternalStringTable(
1783     ExternalStringTableUpdaterCallback updater_func) {
1784   // Update old space string references.
1785   if (external_string_table_.old_space_strings_.length() > 0) {
1786     Object** start = &external_string_table_.old_space_strings_[0];
1787     Object** end = start + external_string_table_.old_space_strings_.length();
1788     for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1789   }
1790
1791   UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1792 }
1793
1794
1795 void Heap::ProcessAllWeakReferences(WeakObjectRetainer* retainer) {
1796   ProcessNativeContexts(retainer);
1797   ProcessAllocationSites(retainer);
1798 }
1799
1800
1801 void Heap::ProcessYoungWeakReferences(WeakObjectRetainer* retainer) {
1802   ProcessNativeContexts(retainer);
1803 }
1804
1805
1806 void Heap::ProcessNativeContexts(WeakObjectRetainer* retainer) {
1807   Object* head = VisitWeakList<Context>(this, native_contexts_list(), retainer);
1808   // Update the head of the list of contexts.
1809   set_native_contexts_list(head);
1810 }
1811
1812
1813 void Heap::RegisterNewArrayBufferHelper(std::map<void*, size_t>& live_buffers,
1814                                         void* data, size_t length) {
1815   live_buffers[data] = length;
1816 }
1817
1818
1819 void Heap::UnregisterArrayBufferHelper(
1820     std::map<void*, size_t>& live_buffers,
1821     std::map<void*, size_t>& not_yet_discovered_buffers, void* data) {
1822   DCHECK(live_buffers.count(data) > 0);
1823   live_buffers.erase(data);
1824   not_yet_discovered_buffers.erase(data);
1825 }
1826
1827
1828 void Heap::RegisterLiveArrayBufferHelper(
1829     std::map<void*, size_t>& not_yet_discovered_buffers, void* data) {
1830   not_yet_discovered_buffers.erase(data);
1831 }
1832
1833
1834 size_t Heap::FreeDeadArrayBuffersHelper(
1835     Isolate* isolate, std::map<void*, size_t>& live_buffers,
1836     std::map<void*, size_t>& not_yet_discovered_buffers) {
1837   size_t freed_memory = 0;
1838   for (auto buffer = not_yet_discovered_buffers.begin();
1839        buffer != not_yet_discovered_buffers.end(); ++buffer) {
1840     isolate->array_buffer_allocator()->Free(buffer->first, buffer->second);
1841     freed_memory += buffer->second;
1842     live_buffers.erase(buffer->first);
1843   }
1844   not_yet_discovered_buffers = live_buffers;
1845   return freed_memory;
1846 }
1847
1848
1849 void Heap::TearDownArrayBuffersHelper(
1850     Isolate* isolate, std::map<void*, size_t>& live_buffers,
1851     std::map<void*, size_t>& not_yet_discovered_buffers) {
1852   for (auto buffer = live_buffers.begin(); buffer != live_buffers.end();
1853        ++buffer) {
1854     isolate->array_buffer_allocator()->Free(buffer->first, buffer->second);
1855   }
1856   live_buffers.clear();
1857   not_yet_discovered_buffers.clear();
1858 }
1859
1860
1861 void Heap::RegisterNewArrayBuffer(bool in_new_space, void* data,
1862                                   size_t length) {
1863   if (!data) return;
1864   RegisterNewArrayBufferHelper(live_array_buffers_, data, length);
1865   if (in_new_space) {
1866     RegisterNewArrayBufferHelper(live_array_buffers_for_scavenge_, data,
1867                                  length);
1868   }
1869   reinterpret_cast<v8::Isolate*>(isolate_)
1870       ->AdjustAmountOfExternalAllocatedMemory(length);
1871 }
1872
1873
1874 void Heap::UnregisterArrayBuffer(bool in_new_space, void* data) {
1875   if (!data) return;
1876   UnregisterArrayBufferHelper(live_array_buffers_,
1877                               not_yet_discovered_array_buffers_, data);
1878   if (in_new_space) {
1879     UnregisterArrayBufferHelper(live_array_buffers_for_scavenge_,
1880                                 not_yet_discovered_array_buffers_for_scavenge_,
1881                                 data);
1882   }
1883 }
1884
1885
1886 void Heap::RegisterLiveArrayBuffer(bool from_scavenge, void* data) {
1887   // ArrayBuffer might be in the middle of being constructed.
1888   if (data == undefined_value()) return;
1889   RegisterLiveArrayBufferHelper(
1890       from_scavenge ? not_yet_discovered_array_buffers_for_scavenge_
1891                     : not_yet_discovered_array_buffers_,
1892       data);
1893 }
1894
1895
1896 void Heap::FreeDeadArrayBuffers(bool from_scavenge) {
1897   if (from_scavenge) {
1898     for (auto& buffer : not_yet_discovered_array_buffers_for_scavenge_) {
1899       not_yet_discovered_array_buffers_.erase(buffer.first);
1900       live_array_buffers_.erase(buffer.first);
1901     }
1902   } else {
1903     for (auto& buffer : not_yet_discovered_array_buffers_) {
1904       // Scavenge can't happend during evacuation, so we only need to update
1905       // live_array_buffers_for_scavenge_.
1906       // not_yet_discovered_array_buffers_for_scanvenge_ will be reset before
1907       // the next scavenge run in PrepareArrayBufferDiscoveryInNewSpace.
1908       live_array_buffers_for_scavenge_.erase(buffer.first);
1909     }
1910   }
1911   size_t freed_memory = FreeDeadArrayBuffersHelper(
1912       isolate_,
1913       from_scavenge ? live_array_buffers_for_scavenge_ : live_array_buffers_,
1914       from_scavenge ? not_yet_discovered_array_buffers_for_scavenge_
1915                     : not_yet_discovered_array_buffers_);
1916   if (freed_memory) {
1917     reinterpret_cast<v8::Isolate*>(isolate_)
1918         ->AdjustAmountOfExternalAllocatedMemory(
1919             -static_cast<int64_t>(freed_memory));
1920   }
1921 }
1922
1923
1924 void Heap::TearDownArrayBuffers() {
1925   TearDownArrayBuffersHelper(isolate_, live_array_buffers_,
1926                              not_yet_discovered_array_buffers_);
1927 }
1928
1929
1930 void Heap::PrepareArrayBufferDiscoveryInNewSpace() {
1931   not_yet_discovered_array_buffers_for_scavenge_ =
1932       live_array_buffers_for_scavenge_;
1933 }
1934
1935
1936 void Heap::PromoteArrayBuffer(Object* obj) {
1937   JSArrayBuffer* buffer = JSArrayBuffer::cast(obj);
1938   if (buffer->is_external()) return;
1939   void* data = buffer->backing_store();
1940   if (!data) return;
1941   // ArrayBuffer might be in the middle of being constructed.
1942   if (data == undefined_value()) return;
1943   DCHECK(live_array_buffers_for_scavenge_.count(data) > 0);
1944   DCHECK(live_array_buffers_.count(data) > 0);
1945   live_array_buffers_for_scavenge_.erase(data);
1946   not_yet_discovered_array_buffers_for_scavenge_.erase(data);
1947 }
1948
1949
1950 void Heap::ProcessAllocationSites(WeakObjectRetainer* retainer) {
1951   Object* allocation_site_obj =
1952       VisitWeakList<AllocationSite>(this, allocation_sites_list(), retainer);
1953   set_allocation_sites_list(allocation_site_obj);
1954 }
1955
1956
1957 void Heap::ResetAllAllocationSitesDependentCode(PretenureFlag flag) {
1958   DisallowHeapAllocation no_allocation_scope;
1959   Object* cur = allocation_sites_list();
1960   bool marked = false;
1961   while (cur->IsAllocationSite()) {
1962     AllocationSite* casted = AllocationSite::cast(cur);
1963     if (casted->GetPretenureMode() == flag) {
1964       casted->ResetPretenureDecision();
1965       casted->set_deopt_dependent_code(true);
1966       marked = true;
1967     }
1968     cur = casted->weak_next();
1969   }
1970   if (marked) isolate_->stack_guard()->RequestDeoptMarkedAllocationSites();
1971 }
1972
1973
1974 void Heap::EvaluateOldSpaceLocalPretenuring(
1975     uint64_t size_of_objects_before_gc) {
1976   uint64_t size_of_objects_after_gc = SizeOfObjects();
1977   double old_generation_survival_rate =
1978       (static_cast<double>(size_of_objects_after_gc) * 100) /
1979       static_cast<double>(size_of_objects_before_gc);
1980
1981   if (old_generation_survival_rate < kOldSurvivalRateLowThreshold) {
1982     // Too many objects died in the old generation, pretenuring of wrong
1983     // allocation sites may be the cause for that. We have to deopt all
1984     // dependent code registered in the allocation sites to re-evaluate
1985     // our pretenuring decisions.
1986     ResetAllAllocationSitesDependentCode(TENURED);
1987     if (FLAG_trace_pretenuring) {
1988       PrintF(
1989           "Deopt all allocation sites dependent code due to low survival "
1990           "rate in the old generation %f\n",
1991           old_generation_survival_rate);
1992     }
1993   }
1994 }
1995
1996
1997 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1998   DisallowHeapAllocation no_allocation;
1999   // All external strings are listed in the external string table.
2000
2001   class ExternalStringTableVisitorAdapter : public ObjectVisitor {
2002    public:
2003     explicit ExternalStringTableVisitorAdapter(
2004         v8::ExternalResourceVisitor* visitor)
2005         : visitor_(visitor) {}
2006     virtual void VisitPointers(Object** start, Object** end) {
2007       for (Object** p = start; p < end; p++) {
2008         DCHECK((*p)->IsExternalString());
2009         visitor_->VisitExternalString(
2010             Utils::ToLocal(Handle<String>(String::cast(*p))));
2011       }
2012     }
2013
2014    private:
2015     v8::ExternalResourceVisitor* visitor_;
2016   } external_string_table_visitor(visitor);
2017
2018   external_string_table_.Iterate(&external_string_table_visitor);
2019 }
2020
2021
2022 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
2023  public:
2024   static inline void VisitPointer(Heap* heap, Object** p) {
2025     Object* object = *p;
2026     if (!heap->InNewSpace(object)) return;
2027     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
2028                          reinterpret_cast<HeapObject*>(object));
2029   }
2030 };
2031
2032
2033 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
2034                          Address new_space_front) {
2035   do {
2036     SemiSpace::AssertValidRange(new_space_front, new_space_.top());
2037     // The addresses new_space_front and new_space_.top() define a
2038     // queue of unprocessed copied objects.  Process them until the
2039     // queue is empty.
2040     while (new_space_front != new_space_.top()) {
2041       if (!NewSpacePage::IsAtEnd(new_space_front)) {
2042         HeapObject* object = HeapObject::FromAddress(new_space_front);
2043         new_space_front +=
2044             NewSpaceScavenger::IterateBody(object->map(), object);
2045       } else {
2046         new_space_front =
2047             NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
2048       }
2049     }
2050
2051     // Promote and process all the to-be-promoted objects.
2052     {
2053       StoreBufferRebuildScope scope(this, store_buffer(),
2054                                     &ScavengeStoreBufferCallback);
2055       while (!promotion_queue()->is_empty()) {
2056         HeapObject* target;
2057         int size;
2058         promotion_queue()->remove(&target, &size);
2059
2060         // Promoted object might be already partially visited
2061         // during old space pointer iteration. Thus we search specifically
2062         // for pointers to from semispace instead of looking for pointers
2063         // to new space.
2064         DCHECK(!target->IsMap());
2065         Address obj_address = target->address();
2066
2067         // We are not collecting slots on new space objects during mutation
2068         // thus we have to scan for pointers to evacuation candidates when we
2069         // promote objects. But we should not record any slots in non-black
2070         // objects. Grey object's slots would be rescanned.
2071         // White object might not survive until the end of collection
2072         // it would be a violation of the invariant to record it's slots.
2073         bool record_slots = false;
2074         if (incremental_marking()->IsCompacting()) {
2075           MarkBit mark_bit = Marking::MarkBitFrom(target);
2076           record_slots = Marking::IsBlack(mark_bit);
2077         }
2078 #if V8_DOUBLE_FIELDS_UNBOXING
2079         LayoutDescriptorHelper helper(target->map());
2080         bool has_only_tagged_fields = helper.all_fields_tagged();
2081
2082         if (!has_only_tagged_fields) {
2083           for (int offset = 0; offset < size;) {
2084             int end_of_region_offset;
2085             if (helper.IsTagged(offset, size, &end_of_region_offset)) {
2086               IterateAndMarkPointersToFromSpace(
2087                   target, obj_address + offset,
2088                   obj_address + end_of_region_offset, record_slots,
2089                   &ScavengeObject);
2090             }
2091             offset = end_of_region_offset;
2092           }
2093         } else {
2094 #endif
2095           IterateAndMarkPointersToFromSpace(target, obj_address,
2096                                             obj_address + size, record_slots,
2097                                             &ScavengeObject);
2098 #if V8_DOUBLE_FIELDS_UNBOXING
2099         }
2100 #endif
2101       }
2102     }
2103
2104     // Take another spin if there are now unswept objects in new space
2105     // (there are currently no more unswept promoted objects).
2106   } while (new_space_front != new_space_.top());
2107
2108   return new_space_front;
2109 }
2110
2111
2112 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) ==
2113               0);  // NOLINT
2114 STATIC_ASSERT((FixedTypedArrayBase::kDataOffset & kDoubleAlignmentMask) ==
2115               0);  // NOLINT
2116 #ifdef V8_HOST_ARCH_32_BIT
2117 STATIC_ASSERT((HeapNumber::kValueOffset & kDoubleAlignmentMask) !=
2118               0);  // NOLINT
2119 #endif
2120
2121
2122 int Heap::GetMaximumFillToAlign(AllocationAlignment alignment) {
2123   switch (alignment) {
2124     case kWordAligned:
2125       return 0;
2126     case kDoubleAligned:
2127     case kDoubleUnaligned:
2128       return kDoubleSize - kPointerSize;
2129     case kSimd128Unaligned:
2130       return kSimd128Size - kPointerSize;
2131     default:
2132       UNREACHABLE();
2133   }
2134   return 0;
2135 }
2136
2137
2138 int Heap::GetFillToAlign(Address address, AllocationAlignment alignment) {
2139   intptr_t offset = OffsetFrom(address);
2140   if (alignment == kDoubleAligned && (offset & kDoubleAlignmentMask) != 0)
2141     return kPointerSize;
2142   if (alignment == kDoubleUnaligned && (offset & kDoubleAlignmentMask) == 0)
2143     return kDoubleSize - kPointerSize;  // No fill if double is always aligned.
2144   if (alignment == kSimd128Unaligned) {
2145     return (kSimd128Size - (static_cast<int>(offset) + kPointerSize)) &
2146            kSimd128AlignmentMask;
2147   }
2148   return 0;
2149 }
2150
2151
2152 HeapObject* Heap::PrecedeWithFiller(HeapObject* object, int filler_size) {
2153   CreateFillerObjectAt(object->address(), filler_size);
2154   return HeapObject::FromAddress(object->address() + filler_size);
2155 }
2156
2157
2158 HeapObject* Heap::AlignWithFiller(HeapObject* object, int object_size,
2159                                   int allocation_size,
2160                                   AllocationAlignment alignment) {
2161   int filler_size = allocation_size - object_size;
2162   DCHECK(filler_size > 0);
2163   int pre_filler = GetFillToAlign(object->address(), alignment);
2164   if (pre_filler) {
2165     object = PrecedeWithFiller(object, pre_filler);
2166     filler_size -= pre_filler;
2167   }
2168   if (filler_size)
2169     CreateFillerObjectAt(object->address() + object_size, filler_size);
2170   return object;
2171 }
2172
2173
2174 HeapObject* Heap::DoubleAlignForDeserialization(HeapObject* object, int size) {
2175   return AlignWithFiller(object, size - kPointerSize, size, kDoubleAligned);
2176 }
2177
2178
2179 enum LoggingAndProfiling {
2180   LOGGING_AND_PROFILING_ENABLED,
2181   LOGGING_AND_PROFILING_DISABLED
2182 };
2183
2184
2185 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
2186
2187
2188 template <MarksHandling marks_handling,
2189           LoggingAndProfiling logging_and_profiling_mode>
2190 class ScavengingVisitor : public StaticVisitorBase {
2191  public:
2192   static void Initialize() {
2193     table_.Register(kVisitSeqOneByteString, &EvacuateSeqOneByteString);
2194     table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
2195     table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
2196     table_.Register(kVisitByteArray, &EvacuateByteArray);
2197     table_.Register(kVisitFixedArray, &EvacuateFixedArray);
2198     table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
2199     table_.Register(kVisitFixedTypedArray, &EvacuateFixedTypedArray);
2200     table_.Register(kVisitFixedFloat64Array, &EvacuateFixedFloat64Array);
2201     table_.Register(kVisitJSArrayBuffer, &EvacuateJSArrayBuffer);
2202
2203     table_.Register(
2204         kVisitNativeContext,
2205         &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2206             Context::kSize>);
2207
2208     table_.Register(
2209         kVisitConsString,
2210         &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2211             ConsString::kSize>);
2212
2213     table_.Register(
2214         kVisitSlicedString,
2215         &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2216             SlicedString::kSize>);
2217
2218     table_.Register(
2219         kVisitSymbol,
2220         &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2221             Symbol::kSize>);
2222
2223     table_.Register(
2224         kVisitSharedFunctionInfo,
2225         &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2226             SharedFunctionInfo::kSize>);
2227
2228     table_.Register(kVisitJSWeakCollection,
2229                     &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2230
2231     table_.Register(kVisitJSTypedArray,
2232                     &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2233
2234     table_.Register(kVisitJSDataView,
2235                     &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2236
2237     table_.Register(kVisitJSRegExp,
2238                     &ObjectEvacuationStrategy<POINTER_OBJECT>::Visit);
2239
2240     if (marks_handling == IGNORE_MARKS) {
2241       table_.Register(
2242           kVisitJSFunction,
2243           &ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2244               JSFunction::kSize>);
2245     } else {
2246       table_.Register(kVisitJSFunction, &EvacuateJSFunction);
2247     }
2248
2249     table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
2250                                    kVisitDataObject, kVisitDataObjectGeneric>();
2251
2252     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
2253                                    kVisitJSObject, kVisitJSObjectGeneric>();
2254
2255     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
2256                                    kVisitStruct, kVisitStructGeneric>();
2257   }
2258
2259   static VisitorDispatchTable<ScavengingCallback>* GetTable() {
2260     return &table_;
2261   }
2262
2263  private:
2264   enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
2265
2266   static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
2267     bool should_record = false;
2268 #ifdef DEBUG
2269     should_record = FLAG_heap_stats;
2270 #endif
2271     should_record = should_record || FLAG_log_gc;
2272     if (should_record) {
2273       if (heap->new_space()->Contains(obj)) {
2274         heap->new_space()->RecordAllocation(obj);
2275       } else {
2276         heap->new_space()->RecordPromotion(obj);
2277       }
2278     }
2279   }
2280
2281   // Helper function used by CopyObject to copy a source object to an
2282   // allocated target object and update the forwarding pointer in the source
2283   // object.  Returns the target object.
2284   INLINE(static void MigrateObject(Heap* heap, HeapObject* source,
2285                                    HeapObject* target, int size)) {
2286     // If we migrate into to-space, then the to-space top pointer should be
2287     // right after the target object. Incorporate double alignment
2288     // over-allocation.
2289     DCHECK(!heap->InToSpace(target) ||
2290            target->address() + size == heap->new_space()->top() ||
2291            target->address() + size + kPointerSize == heap->new_space()->top());
2292
2293     // Make sure that we do not overwrite the promotion queue which is at
2294     // the end of to-space.
2295     DCHECK(!heap->InToSpace(target) ||
2296            heap->promotion_queue()->IsBelowPromotionQueue(
2297                heap->new_space()->top()));
2298
2299     // Copy the content of source to target.
2300     heap->CopyBlock(target->address(), source->address(), size);
2301
2302     // Set the forwarding address.
2303     source->set_map_word(MapWord::FromForwardingAddress(target));
2304
2305     if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
2306       // Update NewSpace stats if necessary.
2307       RecordCopiedObject(heap, target);
2308       heap->OnMoveEvent(target, source, size);
2309     }
2310
2311     if (marks_handling == TRANSFER_MARKS) {
2312       if (Marking::TransferColor(source, target)) {
2313         MemoryChunk::IncrementLiveBytesFromGC(target, size);
2314       }
2315     }
2316   }
2317
2318   template <AllocationAlignment alignment>
2319   static inline bool SemiSpaceCopyObject(Map* map, HeapObject** slot,
2320                                          HeapObject* object, int object_size) {
2321     Heap* heap = map->GetHeap();
2322
2323     DCHECK(heap->AllowedToBeMigrated(object, NEW_SPACE));
2324     AllocationResult allocation =
2325         heap->new_space()->AllocateRaw(object_size, alignment);
2326
2327     HeapObject* target = NULL;  // Initialization to please compiler.
2328     if (allocation.To(&target)) {
2329       // Order is important here: Set the promotion limit before storing a
2330       // filler for double alignment or migrating the object. Otherwise we
2331       // may end up overwriting promotion queue entries when we migrate the
2332       // object.
2333       heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
2334
2335       MigrateObject(heap, object, target, object_size);
2336
2337       // Update slot to new target.
2338       *slot = target;
2339
2340       heap->IncrementSemiSpaceCopiedObjectSize(object_size);
2341       return true;
2342     }
2343     return false;
2344   }
2345
2346
2347   template <ObjectContents object_contents, AllocationAlignment alignment>
2348   static inline bool PromoteObject(Map* map, HeapObject** slot,
2349                                    HeapObject* object, int object_size) {
2350     Heap* heap = map->GetHeap();
2351
2352     AllocationResult allocation =
2353         heap->old_space()->AllocateRaw(object_size, alignment);
2354
2355     HeapObject* target = NULL;  // Initialization to please compiler.
2356     if (allocation.To(&target)) {
2357       MigrateObject(heap, object, target, object_size);
2358
2359       // Update slot to new target.
2360       *slot = target;
2361
2362       if (object_contents == POINTER_OBJECT) {
2363         if (map->instance_type() == JS_FUNCTION_TYPE) {
2364           heap->promotion_queue()->insert(target,
2365                                           JSFunction::kNonWeakFieldsEndOffset);
2366         } else {
2367           heap->promotion_queue()->insert(target, object_size);
2368         }
2369       }
2370       heap->IncrementPromotedObjectsSize(object_size);
2371       return true;
2372     }
2373     return false;
2374   }
2375
2376
2377   template <ObjectContents object_contents, AllocationAlignment alignment>
2378   static inline void EvacuateObject(Map* map, HeapObject** slot,
2379                                     HeapObject* object, int object_size) {
2380     SLOW_DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
2381     SLOW_DCHECK(object->Size() == object_size);
2382     Heap* heap = map->GetHeap();
2383
2384     if (!heap->ShouldBePromoted(object->address(), object_size)) {
2385       // A semi-space copy may fail due to fragmentation. In that case, we
2386       // try to promote the object.
2387       if (SemiSpaceCopyObject<alignment>(map, slot, object, object_size)) {
2388         return;
2389       }
2390     }
2391
2392     if (PromoteObject<object_contents, alignment>(map, slot, object,
2393                                                   object_size)) {
2394       return;
2395     }
2396
2397     // If promotion failed, we try to copy the object to the other semi-space
2398     if (SemiSpaceCopyObject<alignment>(map, slot, object, object_size)) return;
2399
2400     UNREACHABLE();
2401   }
2402
2403
2404   static inline void EvacuateJSFunction(Map* map, HeapObject** slot,
2405                                         HeapObject* object) {
2406     ObjectEvacuationStrategy<POINTER_OBJECT>::template VisitSpecialized<
2407         JSFunction::kSize>(map, slot, object);
2408
2409     MapWord map_word = object->map_word();
2410     DCHECK(map_word.IsForwardingAddress());
2411     HeapObject* target = map_word.ToForwardingAddress();
2412
2413     MarkBit mark_bit = Marking::MarkBitFrom(target);
2414     if (Marking::IsBlack(mark_bit)) {
2415       // This object is black and it might not be rescanned by marker.
2416       // We should explicitly record code entry slot for compaction because
2417       // promotion queue processing (IterateAndMarkPointersToFromSpace) will
2418       // miss it as it is not HeapObject-tagged.
2419       Address code_entry_slot =
2420           target->address() + JSFunction::kCodeEntryOffset;
2421       Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
2422       map->GetHeap()->mark_compact_collector()->RecordCodeEntrySlot(
2423           target, code_entry_slot, code);
2424     }
2425   }
2426
2427
2428   static inline void EvacuateFixedArray(Map* map, HeapObject** slot,
2429                                         HeapObject* object) {
2430     int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
2431     EvacuateObject<POINTER_OBJECT, kWordAligned>(map, slot, object,
2432                                                  object_size);
2433   }
2434
2435
2436   static inline void EvacuateFixedDoubleArray(Map* map, HeapObject** slot,
2437                                               HeapObject* object) {
2438     int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
2439     int object_size = FixedDoubleArray::SizeFor(length);
2440     EvacuateObject<DATA_OBJECT, kDoubleAligned>(map, slot, object, object_size);
2441   }
2442
2443
2444   static inline void EvacuateFixedTypedArray(Map* map, HeapObject** slot,
2445                                              HeapObject* object) {
2446     int object_size = reinterpret_cast<FixedTypedArrayBase*>(object)->size();
2447     EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2448
2449     MapWord map_word = object->map_word();
2450     DCHECK(map_word.IsForwardingAddress());
2451     FixedTypedArrayBase* target =
2452         reinterpret_cast<FixedTypedArrayBase*>(map_word.ToForwardingAddress());
2453     if (target->base_pointer() != Smi::FromInt(0))
2454       target->set_base_pointer(target, SKIP_WRITE_BARRIER);
2455   }
2456
2457
2458   static inline void EvacuateFixedFloat64Array(Map* map, HeapObject** slot,
2459                                                HeapObject* object) {
2460     int object_size = reinterpret_cast<FixedFloat64Array*>(object)->size();
2461     EvacuateObject<DATA_OBJECT, kDoubleAligned>(map, slot, object, object_size);
2462
2463     MapWord map_word = object->map_word();
2464     DCHECK(map_word.IsForwardingAddress());
2465     FixedTypedArrayBase* target =
2466         reinterpret_cast<FixedTypedArrayBase*>(map_word.ToForwardingAddress());
2467     if (target->base_pointer() != Smi::FromInt(0))
2468       target->set_base_pointer(target, SKIP_WRITE_BARRIER);
2469   }
2470
2471
2472   static inline void EvacuateJSArrayBuffer(Map* map, HeapObject** slot,
2473                                            HeapObject* object) {
2474     ObjectEvacuationStrategy<POINTER_OBJECT>::Visit(map, slot, object);
2475
2476     Heap* heap = map->GetHeap();
2477     MapWord map_word = object->map_word();
2478     DCHECK(map_word.IsForwardingAddress());
2479     HeapObject* target = map_word.ToForwardingAddress();
2480     if (!heap->InNewSpace(target)) heap->PromoteArrayBuffer(target);
2481   }
2482
2483
2484   static inline void EvacuateByteArray(Map* map, HeapObject** slot,
2485                                        HeapObject* object) {
2486     int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
2487     EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2488   }
2489
2490
2491   static inline void EvacuateSeqOneByteString(Map* map, HeapObject** slot,
2492                                               HeapObject* object) {
2493     int object_size = SeqOneByteString::cast(object)
2494                           ->SeqOneByteStringSize(map->instance_type());
2495     EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2496   }
2497
2498
2499   static inline void EvacuateSeqTwoByteString(Map* map, HeapObject** slot,
2500                                               HeapObject* object) {
2501     int object_size = SeqTwoByteString::cast(object)
2502                           ->SeqTwoByteStringSize(map->instance_type());
2503     EvacuateObject<DATA_OBJECT, kWordAligned>(map, slot, object, object_size);
2504   }
2505
2506
2507   static inline void EvacuateShortcutCandidate(Map* map, HeapObject** slot,
2508                                                HeapObject* object) {
2509     DCHECK(IsShortcutCandidate(map->instance_type()));
2510
2511     Heap* heap = map->GetHeap();
2512
2513     if (marks_handling == IGNORE_MARKS &&
2514         ConsString::cast(object)->unchecked_second() == heap->empty_string()) {
2515       HeapObject* first =
2516           HeapObject::cast(ConsString::cast(object)->unchecked_first());
2517
2518       *slot = first;
2519
2520       if (!heap->InNewSpace(first)) {
2521         object->set_map_word(MapWord::FromForwardingAddress(first));
2522         return;
2523       }
2524
2525       MapWord first_word = first->map_word();
2526       if (first_word.IsForwardingAddress()) {
2527         HeapObject* target = first_word.ToForwardingAddress();
2528
2529         *slot = target;
2530         object->set_map_word(MapWord::FromForwardingAddress(target));
2531         return;
2532       }
2533
2534       heap->DoScavengeObject(first->map(), slot, first);
2535       object->set_map_word(MapWord::FromForwardingAddress(*slot));
2536       return;
2537     }
2538
2539     int object_size = ConsString::kSize;
2540     EvacuateObject<POINTER_OBJECT, kWordAligned>(map, slot, object,
2541                                                  object_size);
2542   }
2543
2544   template <ObjectContents object_contents>
2545   class ObjectEvacuationStrategy {
2546    public:
2547     template <int object_size>
2548     static inline void VisitSpecialized(Map* map, HeapObject** slot,
2549                                         HeapObject* object) {
2550       EvacuateObject<object_contents, kWordAligned>(map, slot, object,
2551                                                     object_size);
2552     }
2553
2554     static inline void Visit(Map* map, HeapObject** slot, HeapObject* object) {
2555       int object_size = map->instance_size();
2556       EvacuateObject<object_contents, kWordAligned>(map, slot, object,
2557                                                     object_size);
2558     }
2559   };
2560
2561   static VisitorDispatchTable<ScavengingCallback> table_;
2562 };
2563
2564
2565 template <MarksHandling marks_handling,
2566           LoggingAndProfiling logging_and_profiling_mode>
2567 VisitorDispatchTable<ScavengingCallback>
2568     ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
2569
2570
2571 static void InitializeScavengingVisitorsTables() {
2572   ScavengingVisitor<TRANSFER_MARKS,
2573                     LOGGING_AND_PROFILING_DISABLED>::Initialize();
2574   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
2575   ScavengingVisitor<TRANSFER_MARKS,
2576                     LOGGING_AND_PROFILING_ENABLED>::Initialize();
2577   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
2578 }
2579
2580
2581 void Heap::SelectScavengingVisitorsTable() {
2582   bool logging_and_profiling =
2583       FLAG_verify_predictable || isolate()->logger()->is_logging() ||
2584       isolate()->cpu_profiler()->is_profiling() ||
2585       (isolate()->heap_profiler() != NULL &&
2586        isolate()->heap_profiler()->is_tracking_object_moves());
2587
2588   if (!incremental_marking()->IsMarking()) {
2589     if (!logging_and_profiling) {
2590       scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2591           IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable());
2592     } else {
2593       scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2594           IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable());
2595     }
2596   } else {
2597     if (!logging_and_profiling) {
2598       scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2599           TRANSFER_MARKS, LOGGING_AND_PROFILING_DISABLED>::GetTable());
2600     } else {
2601       scavenging_visitors_table_.CopyFrom(ScavengingVisitor<
2602           TRANSFER_MARKS, LOGGING_AND_PROFILING_ENABLED>::GetTable());
2603     }
2604
2605     if (incremental_marking()->IsCompacting()) {
2606       // When compacting forbid short-circuiting of cons-strings.
2607       // Scavenging code relies on the fact that new space object
2608       // can't be evacuated into evacuation candidate but
2609       // short-circuiting violates this assumption.
2610       scavenging_visitors_table_.Register(
2611           StaticVisitorBase::kVisitShortcutCandidate,
2612           scavenging_visitors_table_.GetVisitorById(
2613               StaticVisitorBase::kVisitConsString));
2614     }
2615   }
2616 }
2617
2618
2619 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
2620   SLOW_DCHECK(object->GetIsolate()->heap()->InFromSpace(object));
2621   MapWord first_word = object->map_word();
2622   SLOW_DCHECK(!first_word.IsForwardingAddress());
2623   Map* map = first_word.ToMap();
2624   map->GetHeap()->DoScavengeObject(map, p, object);
2625 }
2626
2627
2628 void Heap::ConfigureInitialOldGenerationSize() {
2629   if (!old_generation_size_configured_ && tracer()->SurvivalEventsRecorded()) {
2630     old_generation_allocation_limit_ =
2631         Max(kMinimumOldGenerationAllocationLimit,
2632             static_cast<intptr_t>(
2633                 static_cast<double>(old_generation_allocation_limit_) *
2634                 (tracer()->AverageSurvivalRatio() / 100)));
2635   }
2636 }
2637
2638
2639 AllocationResult Heap::AllocatePartialMap(InstanceType instance_type,
2640                                           int instance_size) {
2641   Object* result = nullptr;
2642   AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE);
2643   if (!allocation.To(&result)) return allocation;
2644
2645   // Map::cast cannot be used due to uninitialized map field.
2646   reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
2647   reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
2648   reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2649   // Initialize to only containing tagged fields.
2650   reinterpret_cast<Map*>(result)->set_visitor_id(
2651       StaticVisitorBase::GetVisitorId(instance_type, instance_size, false));
2652   if (FLAG_unbox_double_fields) {
2653     reinterpret_cast<Map*>(result)
2654         ->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2655   }
2656   reinterpret_cast<Map*>(result)->clear_unused();
2657   reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2658   reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2659   reinterpret_cast<Map*>(result)->set_bit_field(0);
2660   reinterpret_cast<Map*>(result)->set_bit_field2(0);
2661   int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
2662                    Map::OwnsDescriptors::encode(true) |
2663                    Map::Counter::encode(Map::kRetainingCounterStart);
2664   reinterpret_cast<Map*>(result)->set_bit_field3(bit_field3);
2665   reinterpret_cast<Map*>(result)->set_weak_cell_cache(Smi::FromInt(0));
2666   return result;
2667 }
2668
2669
2670 AllocationResult Heap::AllocateMap(InstanceType instance_type,
2671                                    int instance_size,
2672                                    ElementsKind elements_kind) {
2673   HeapObject* result;
2674   AllocationResult allocation = AllocateRaw(Map::kSize, MAP_SPACE, MAP_SPACE);
2675   if (!allocation.To(&result)) return allocation;
2676
2677   result->set_map_no_write_barrier(meta_map());
2678   Map* map = Map::cast(result);
2679   map->set_instance_type(instance_type);
2680   map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2681   map->set_constructor_or_backpointer(null_value(), SKIP_WRITE_BARRIER);
2682   map->set_instance_size(instance_size);
2683   map->clear_unused();
2684   map->set_inobject_properties(0);
2685   map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2686   map->set_dependent_code(DependentCode::cast(empty_fixed_array()),
2687                           SKIP_WRITE_BARRIER);
2688   map->set_weak_cell_cache(Smi::FromInt(0));
2689   map->set_raw_transitions(Smi::FromInt(0));
2690   map->set_unused_property_fields(0);
2691   map->set_instance_descriptors(empty_descriptor_array());
2692   if (FLAG_unbox_double_fields) {
2693     map->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2694   }
2695   // Must be called only after |instance_type|, |instance_size| and
2696   // |layout_descriptor| are set.
2697   map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
2698   map->set_bit_field(0);
2699   map->set_bit_field2(1 << Map::kIsExtensible);
2700   int bit_field3 = Map::EnumLengthBits::encode(kInvalidEnumCacheSentinel) |
2701                    Map::OwnsDescriptors::encode(true) |
2702                    Map::Counter::encode(Map::kRetainingCounterStart);
2703   map->set_bit_field3(bit_field3);
2704   map->set_elements_kind(elements_kind);
2705
2706   return map;
2707 }
2708
2709
2710 AllocationResult Heap::AllocateFillerObject(int size, bool double_align,
2711                                             AllocationSpace space) {
2712   HeapObject* obj;
2713   {
2714     AllocationAlignment align = double_align ? kDoubleAligned : kWordAligned;
2715     AllocationResult allocation = AllocateRaw(size, space, space, align);
2716     if (!allocation.To(&obj)) return allocation;
2717   }
2718 #ifdef DEBUG
2719   MemoryChunk* chunk = MemoryChunk::FromAddress(obj->address());
2720   DCHECK(chunk->owner()->identity() == space);
2721 #endif
2722   CreateFillerObjectAt(obj->address(), size);
2723   return obj;
2724 }
2725
2726
2727 const Heap::StringTypeTable Heap::string_type_table[] = {
2728 #define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
2729   { type, size, k##camel_name##MapRootIndex }             \
2730   ,
2731     STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2732 #undef STRING_TYPE_ELEMENT
2733 };
2734
2735
2736 const Heap::ConstantStringTable Heap::constant_string_table[] = {
2737     {"", kempty_stringRootIndex},
2738 #define CONSTANT_STRING_ELEMENT(name, contents) \
2739   { contents, k##name##RootIndex }              \
2740   ,
2741     INTERNALIZED_STRING_LIST(CONSTANT_STRING_ELEMENT)
2742 #undef CONSTANT_STRING_ELEMENT
2743 };
2744
2745
2746 const Heap::StructTable Heap::struct_table[] = {
2747 #define STRUCT_TABLE_ELEMENT(NAME, Name, name)        \
2748   { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex } \
2749   ,
2750     STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2751 #undef STRUCT_TABLE_ELEMENT
2752 };
2753
2754
2755 bool Heap::CreateInitialMaps() {
2756   HeapObject* obj;
2757   {
2758     AllocationResult allocation = AllocatePartialMap(MAP_TYPE, Map::kSize);
2759     if (!allocation.To(&obj)) return false;
2760   }
2761   // Map::cast cannot be used due to uninitialized map field.
2762   Map* new_meta_map = reinterpret_cast<Map*>(obj);
2763   set_meta_map(new_meta_map);
2764   new_meta_map->set_map(new_meta_map);
2765
2766   {  // Partial map allocation
2767 #define ALLOCATE_PARTIAL_MAP(instance_type, size, field_name)                \
2768   {                                                                          \
2769     Map* map;                                                                \
2770     if (!AllocatePartialMap((instance_type), (size)).To(&map)) return false; \
2771     set_##field_name##_map(map);                                             \
2772   }
2773
2774     ALLOCATE_PARTIAL_MAP(FIXED_ARRAY_TYPE, kVariableSizeSentinel, fixed_array);
2775     ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, undefined);
2776     ALLOCATE_PARTIAL_MAP(ODDBALL_TYPE, Oddball::kSize, null);
2777
2778 #undef ALLOCATE_PARTIAL_MAP
2779   }
2780
2781   // Allocate the empty array.
2782   {
2783     AllocationResult allocation = AllocateEmptyFixedArray();
2784     if (!allocation.To(&obj)) return false;
2785   }
2786   set_empty_fixed_array(FixedArray::cast(obj));
2787
2788   {
2789     AllocationResult allocation = Allocate(null_map(), OLD_SPACE);
2790     if (!allocation.To(&obj)) return false;
2791   }
2792   set_null_value(Oddball::cast(obj));
2793   Oddball::cast(obj)->set_kind(Oddball::kNull);
2794
2795   {
2796     AllocationResult allocation = Allocate(undefined_map(), OLD_SPACE);
2797     if (!allocation.To(&obj)) return false;
2798   }
2799   set_undefined_value(Oddball::cast(obj));
2800   Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2801   DCHECK(!InNewSpace(undefined_value()));
2802
2803   // Set preliminary exception sentinel value before actually initializing it.
2804   set_exception(null_value());
2805
2806   // Allocate the empty descriptor array.
2807   {
2808     AllocationResult allocation = AllocateEmptyFixedArray();
2809     if (!allocation.To(&obj)) return false;
2810   }
2811   set_empty_descriptor_array(DescriptorArray::cast(obj));
2812
2813   // Fix the instance_descriptors for the existing maps.
2814   meta_map()->set_code_cache(empty_fixed_array());
2815   meta_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2816   meta_map()->set_raw_transitions(Smi::FromInt(0));
2817   meta_map()->set_instance_descriptors(empty_descriptor_array());
2818   if (FLAG_unbox_double_fields) {
2819     meta_map()->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2820   }
2821
2822   fixed_array_map()->set_code_cache(empty_fixed_array());
2823   fixed_array_map()->set_dependent_code(
2824       DependentCode::cast(empty_fixed_array()));
2825   fixed_array_map()->set_raw_transitions(Smi::FromInt(0));
2826   fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
2827   if (FLAG_unbox_double_fields) {
2828     fixed_array_map()->set_layout_descriptor(
2829         LayoutDescriptor::FastPointerLayout());
2830   }
2831
2832   undefined_map()->set_code_cache(empty_fixed_array());
2833   undefined_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2834   undefined_map()->set_raw_transitions(Smi::FromInt(0));
2835   undefined_map()->set_instance_descriptors(empty_descriptor_array());
2836   if (FLAG_unbox_double_fields) {
2837     undefined_map()->set_layout_descriptor(
2838         LayoutDescriptor::FastPointerLayout());
2839   }
2840
2841   null_map()->set_code_cache(empty_fixed_array());
2842   null_map()->set_dependent_code(DependentCode::cast(empty_fixed_array()));
2843   null_map()->set_raw_transitions(Smi::FromInt(0));
2844   null_map()->set_instance_descriptors(empty_descriptor_array());
2845   if (FLAG_unbox_double_fields) {
2846     null_map()->set_layout_descriptor(LayoutDescriptor::FastPointerLayout());
2847   }
2848
2849   // Fix prototype object for existing maps.
2850   meta_map()->set_prototype(null_value());
2851   meta_map()->set_constructor_or_backpointer(null_value());
2852
2853   fixed_array_map()->set_prototype(null_value());
2854   fixed_array_map()->set_constructor_or_backpointer(null_value());
2855
2856   undefined_map()->set_prototype(null_value());
2857   undefined_map()->set_constructor_or_backpointer(null_value());
2858
2859   null_map()->set_prototype(null_value());
2860   null_map()->set_constructor_or_backpointer(null_value());
2861
2862   {  // Map allocation
2863 #define ALLOCATE_MAP(instance_type, size, field_name)               \
2864   {                                                                 \
2865     Map* map;                                                       \
2866     if (!AllocateMap((instance_type), size).To(&map)) return false; \
2867     set_##field_name##_map(map);                                    \
2868   }
2869
2870 #define ALLOCATE_VARSIZE_MAP(instance_type, field_name) \
2871   ALLOCATE_MAP(instance_type, kVariableSizeSentinel, field_name)
2872
2873     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, fixed_cow_array)
2874     DCHECK(fixed_array_map() != fixed_cow_array_map());
2875
2876     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, scope_info)
2877     ALLOCATE_MAP(HEAP_NUMBER_TYPE, HeapNumber::kSize, heap_number)
2878     ALLOCATE_MAP(MUTABLE_HEAP_NUMBER_TYPE, HeapNumber::kSize,
2879                  mutable_heap_number)
2880     ALLOCATE_MAP(SYMBOL_TYPE, Symbol::kSize, symbol)
2881 #define ALLOCATE_SIMD128_MAP(TYPE, Type, type, lane_count, lane_type) \
2882   ALLOCATE_MAP(SIMD128_VALUE_TYPE, Type::kSize, type)
2883     SIMD128_TYPES(ALLOCATE_SIMD128_MAP)
2884 #undef ALLOCATE_SIMD128_MAP
2885     ALLOCATE_MAP(FOREIGN_TYPE, Foreign::kSize, foreign)
2886
2887     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, the_hole);
2888     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, boolean);
2889     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, uninitialized);
2890     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, arguments_marker);
2891     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, no_interceptor_result_sentinel);
2892     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, exception);
2893     ALLOCATE_MAP(ODDBALL_TYPE, Oddball::kSize, termination_exception);
2894
2895     for (unsigned i = 0; i < arraysize(string_type_table); i++) {
2896       const StringTypeTable& entry = string_type_table[i];
2897       {
2898         AllocationResult allocation = AllocateMap(entry.type, entry.size);
2899         if (!allocation.To(&obj)) return false;
2900       }
2901       // Mark cons string maps as unstable, because their objects can change
2902       // maps during GC.
2903       Map* map = Map::cast(obj);
2904       if (StringShape(entry.type).IsCons()) map->mark_unstable();
2905       roots_[entry.index] = map;
2906     }
2907
2908     {  // Create a separate external one byte string map for native sources.
2909       AllocationResult allocation = AllocateMap(EXTERNAL_ONE_BYTE_STRING_TYPE,
2910                                                 ExternalOneByteString::kSize);
2911       if (!allocation.To(&obj)) return false;
2912       set_native_source_string_map(Map::cast(obj));
2913     }
2914
2915     ALLOCATE_VARSIZE_MAP(FIXED_DOUBLE_ARRAY_TYPE, fixed_double_array)
2916     ALLOCATE_VARSIZE_MAP(BYTE_ARRAY_TYPE, byte_array)
2917     ALLOCATE_VARSIZE_MAP(BYTECODE_ARRAY_TYPE, bytecode_array)
2918     ALLOCATE_VARSIZE_MAP(FREE_SPACE_TYPE, free_space)
2919
2920 #define ALLOCATE_FIXED_TYPED_ARRAY_MAP(Type, type, TYPE, ctype, size) \
2921   ALLOCATE_VARSIZE_MAP(FIXED_##TYPE##_ARRAY_TYPE, fixed_##type##_array)
2922
2923     TYPED_ARRAYS(ALLOCATE_FIXED_TYPED_ARRAY_MAP)
2924 #undef ALLOCATE_FIXED_TYPED_ARRAY_MAP
2925
2926     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, sloppy_arguments_elements)
2927
2928     ALLOCATE_VARSIZE_MAP(CODE_TYPE, code)
2929
2930     ALLOCATE_MAP(CELL_TYPE, Cell::kSize, cell)
2931     ALLOCATE_MAP(PROPERTY_CELL_TYPE, PropertyCell::kSize, global_property_cell)
2932     ALLOCATE_MAP(WEAK_CELL_TYPE, WeakCell::kSize, weak_cell)
2933     ALLOCATE_MAP(FILLER_TYPE, kPointerSize, one_pointer_filler)
2934     ALLOCATE_MAP(FILLER_TYPE, 2 * kPointerSize, two_pointer_filler)
2935
2936
2937     for (unsigned i = 0; i < arraysize(struct_table); i++) {
2938       const StructTable& entry = struct_table[i];
2939       Map* map;
2940       if (!AllocateMap(entry.type, entry.size).To(&map)) return false;
2941       roots_[entry.index] = map;
2942     }
2943
2944     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, hash_table)
2945     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, ordered_hash_table)
2946
2947     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, function_context)
2948     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, catch_context)
2949     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, with_context)
2950     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, block_context)
2951     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, module_context)
2952     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, script_context)
2953     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, script_context_table)
2954
2955     ALLOCATE_VARSIZE_MAP(FIXED_ARRAY_TYPE, native_context)
2956     native_context_map()->set_dictionary_map(true);
2957     native_context_map()->set_visitor_id(
2958         StaticVisitorBase::kVisitNativeContext);
2959
2960     ALLOCATE_MAP(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kAlignedSize,
2961                  shared_function_info)
2962
2963     ALLOCATE_MAP(JS_MESSAGE_OBJECT_TYPE, JSMessageObject::kSize, message_object)
2964     ALLOCATE_MAP(JS_OBJECT_TYPE, JSObject::kHeaderSize + kPointerSize, external)
2965     external_map()->set_is_extensible(false);
2966 #undef ALLOCATE_VARSIZE_MAP
2967 #undef ALLOCATE_MAP
2968   }
2969
2970   {  // Empty arrays
2971     {
2972       ByteArray* byte_array;
2973       if (!AllocateByteArray(0, TENURED).To(&byte_array)) return false;
2974       set_empty_byte_array(byte_array);
2975
2976       BytecodeArray* bytecode_array;
2977       AllocationResult allocation =
2978           AllocateBytecodeArray(0, nullptr, kPointerSize);
2979       if (!allocation.To(&bytecode_array)) {
2980         return false;
2981       }
2982       set_empty_bytecode_array(bytecode_array);
2983     }
2984
2985 #define ALLOCATE_EMPTY_FIXED_TYPED_ARRAY(Type, type, TYPE, ctype, size) \
2986   {                                                                     \
2987     FixedTypedArrayBase* obj;                                           \
2988     if (!AllocateEmptyFixedTypedArray(kExternal##Type##Array).To(&obj)) \
2989       return false;                                                     \
2990     set_empty_fixed_##type##_array(obj);                                \
2991   }
2992
2993     TYPED_ARRAYS(ALLOCATE_EMPTY_FIXED_TYPED_ARRAY)
2994 #undef ALLOCATE_EMPTY_FIXED_TYPED_ARRAY
2995   }
2996   DCHECK(!InNewSpace(empty_fixed_array()));
2997   return true;
2998 }
2999
3000
3001 AllocationResult Heap::AllocateHeapNumber(double value, MutableMode mode,
3002                                           PretenureFlag pretenure) {
3003   // Statically ensure that it is safe to allocate heap numbers in paged
3004   // spaces.
3005   int size = HeapNumber::kSize;
3006   STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxRegularHeapObjectSize);
3007
3008   AllocationSpace space = SelectSpace(size, pretenure);
3009
3010   HeapObject* result;
3011   {
3012     AllocationResult allocation =
3013         AllocateRaw(size, space, OLD_SPACE, kDoubleUnaligned);
3014     if (!allocation.To(&result)) return allocation;
3015   }
3016
3017   Map* map = mode == MUTABLE ? mutable_heap_number_map() : heap_number_map();
3018   HeapObject::cast(result)->set_map_no_write_barrier(map);
3019   HeapNumber::cast(result)->set_value(value);
3020   return result;
3021 }
3022
3023 #define SIMD_ALLOCATE_DEFINITION(TYPE, Type, type, lane_count, lane_type) \
3024   AllocationResult Heap::Allocate##Type(lane_type lanes[lane_count],      \
3025                                         PretenureFlag pretenure) {        \
3026     int size = Type::kSize;                                               \
3027     STATIC_ASSERT(Type::kSize <= Page::kMaxRegularHeapObjectSize);        \
3028                                                                           \
3029     AllocationSpace space = SelectSpace(size, pretenure);                 \
3030                                                                           \
3031     HeapObject* result;                                                   \
3032     {                                                                     \
3033       AllocationResult allocation =                                       \
3034           AllocateRaw(size, space, OLD_SPACE, kSimd128Unaligned);         \
3035       if (!allocation.To(&result)) return allocation;                     \
3036     }                                                                     \
3037                                                                           \
3038     result->set_map_no_write_barrier(type##_map());                       \
3039     Type* instance = Type::cast(result);                                  \
3040     for (int i = 0; i < lane_count; i++) {                                \
3041       instance->set_lane(i, lanes[i]);                                    \
3042     }                                                                     \
3043     return result;                                                        \
3044   }
3045 SIMD128_TYPES(SIMD_ALLOCATE_DEFINITION)
3046 #undef SIMD_ALLOCATE_DEFINITION
3047
3048
3049 AllocationResult Heap::AllocateCell(Object* value) {
3050   int size = Cell::kSize;
3051   STATIC_ASSERT(Cell::kSize <= Page::kMaxRegularHeapObjectSize);
3052
3053   HeapObject* result;
3054   {
3055     AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3056     if (!allocation.To(&result)) return allocation;
3057   }
3058   result->set_map_no_write_barrier(cell_map());
3059   Cell::cast(result)->set_value(value);
3060   return result;
3061 }
3062
3063
3064 AllocationResult Heap::AllocatePropertyCell() {
3065   int size = PropertyCell::kSize;
3066   STATIC_ASSERT(PropertyCell::kSize <= Page::kMaxRegularHeapObjectSize);
3067
3068   HeapObject* result;
3069   AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3070   if (!allocation.To(&result)) return allocation;
3071
3072   result->set_map_no_write_barrier(global_property_cell_map());
3073   PropertyCell* cell = PropertyCell::cast(result);
3074   cell->set_dependent_code(DependentCode::cast(empty_fixed_array()),
3075                            SKIP_WRITE_BARRIER);
3076   cell->set_property_details(PropertyDetails(Smi::FromInt(0)));
3077   cell->set_value(the_hole_value());
3078   return result;
3079 }
3080
3081
3082 AllocationResult Heap::AllocateWeakCell(HeapObject* value) {
3083   int size = WeakCell::kSize;
3084   STATIC_ASSERT(WeakCell::kSize <= Page::kMaxRegularHeapObjectSize);
3085   HeapObject* result = NULL;
3086   {
3087     AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3088     if (!allocation.To(&result)) return allocation;
3089   }
3090   result->set_map_no_write_barrier(weak_cell_map());
3091   WeakCell::cast(result)->initialize(value);
3092   WeakCell::cast(result)->clear_next(this);
3093   return result;
3094 }
3095
3096
3097 void Heap::CreateApiObjects() {
3098   HandleScope scope(isolate());
3099   Factory* factory = isolate()->factory();
3100   Handle<Map> new_neander_map =
3101       factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
3102
3103   // Don't use Smi-only elements optimizations for objects with the neander
3104   // map. There are too many cases where element values are set directly with a
3105   // bottleneck to trap the Smi-only -> fast elements transition, and there
3106   // appears to be no benefit for optimize this case.
3107   new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
3108   set_neander_map(*new_neander_map);
3109
3110   Handle<JSObject> listeners = factory->NewNeanderObject();
3111   Handle<FixedArray> elements = factory->NewFixedArray(2);
3112   elements->set(0, Smi::FromInt(0));
3113   listeners->set_elements(*elements);
3114   set_message_listeners(*listeners);
3115 }
3116
3117
3118 void Heap::CreateJSEntryStub() {
3119   JSEntryStub stub(isolate(), StackFrame::ENTRY);
3120   set_js_entry_code(*stub.GetCode());
3121 }
3122
3123
3124 void Heap::CreateJSConstructEntryStub() {
3125   JSEntryStub stub(isolate(), StackFrame::ENTRY_CONSTRUCT);
3126   set_js_construct_entry_code(*stub.GetCode());
3127 }
3128
3129
3130 void Heap::CreateFixedStubs() {
3131   // Here we create roots for fixed stubs. They are needed at GC
3132   // for cooking and uncooking (check out frames.cc).
3133   // The eliminates the need for doing dictionary lookup in the
3134   // stub cache for these stubs.
3135   HandleScope scope(isolate());
3136
3137   // Create stubs that should be there, so we don't unexpectedly have to
3138   // create them if we need them during the creation of another stub.
3139   // Stub creation mixes raw pointers and handles in an unsafe manner so
3140   // we cannot create stubs while we are creating stubs.
3141   CodeStub::GenerateStubsAheadOfTime(isolate());
3142
3143   // MacroAssembler::Abort calls (usually enabled with --debug-code) depend on
3144   // CEntryStub, so we need to call GenerateStubsAheadOfTime before JSEntryStub
3145   // is created.
3146
3147   // gcc-4.4 has problem generating correct code of following snippet:
3148   // {  JSEntryStub stub;
3149   //    js_entry_code_ = *stub.GetCode();
3150   // }
3151   // {  JSConstructEntryStub stub;
3152   //    js_construct_entry_code_ = *stub.GetCode();
3153   // }
3154   // To workaround the problem, make separate functions without inlining.
3155   Heap::CreateJSEntryStub();
3156   Heap::CreateJSConstructEntryStub();
3157 }
3158
3159
3160 void Heap::CreateInitialObjects() {
3161   HandleScope scope(isolate());
3162   Factory* factory = isolate()->factory();
3163
3164   // The -0 value must be set before NewNumber works.
3165   set_minus_zero_value(*factory->NewHeapNumber(-0.0, IMMUTABLE, TENURED));
3166   DCHECK(std::signbit(minus_zero_value()->Number()) != 0);
3167
3168   set_nan_value(*factory->NewHeapNumber(
3169       std::numeric_limits<double>::quiet_NaN(), IMMUTABLE, TENURED));
3170   set_infinity_value(*factory->NewHeapNumber(V8_INFINITY, IMMUTABLE, TENURED));
3171   set_minus_infinity_value(
3172       *factory->NewHeapNumber(-V8_INFINITY, IMMUTABLE, TENURED));
3173
3174   // The hole has not been created yet, but we want to put something
3175   // predictable in the gaps in the string table, so lets make that Smi zero.
3176   set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
3177
3178   // Allocate initial string table.
3179   set_string_table(*StringTable::New(isolate(), kInitialStringTableSize));
3180
3181   // Finish initializing oddballs after creating the string table.
3182   Oddball::Initialize(isolate(), factory->undefined_value(), "undefined",
3183                       factory->nan_value(), "undefined", Oddball::kUndefined);
3184
3185   // Initialize the null_value.
3186   Oddball::Initialize(isolate(), factory->null_value(), "null",
3187                       handle(Smi::FromInt(0), isolate()), "object",
3188                       Oddball::kNull);
3189
3190   set_true_value(*factory->NewOddball(factory->boolean_map(), "true",
3191                                       handle(Smi::FromInt(1), isolate()),
3192                                       "boolean", Oddball::kTrue));
3193
3194   set_false_value(*factory->NewOddball(factory->boolean_map(), "false",
3195                                        handle(Smi::FromInt(0), isolate()),
3196                                        "boolean", Oddball::kFalse));
3197
3198   set_the_hole_value(*factory->NewOddball(factory->the_hole_map(), "hole",
3199                                           handle(Smi::FromInt(-1), isolate()),
3200                                           "undefined", Oddball::kTheHole));
3201
3202   set_uninitialized_value(
3203       *factory->NewOddball(factory->uninitialized_map(), "uninitialized",
3204                            handle(Smi::FromInt(-1), isolate()), "undefined",
3205                            Oddball::kUninitialized));
3206
3207   set_arguments_marker(
3208       *factory->NewOddball(factory->arguments_marker_map(), "arguments_marker",
3209                            handle(Smi::FromInt(-4), isolate()), "undefined",
3210                            Oddball::kArgumentMarker));
3211
3212   set_no_interceptor_result_sentinel(*factory->NewOddball(
3213       factory->no_interceptor_result_sentinel_map(),
3214       "no_interceptor_result_sentinel", handle(Smi::FromInt(-2), isolate()),
3215       "undefined", Oddball::kOther));
3216
3217   set_termination_exception(*factory->NewOddball(
3218       factory->termination_exception_map(), "termination_exception",
3219       handle(Smi::FromInt(-3), isolate()), "undefined", Oddball::kOther));
3220
3221   set_exception(*factory->NewOddball(factory->exception_map(), "exception",
3222                                      handle(Smi::FromInt(-5), isolate()),
3223                                      "undefined", Oddball::kException));
3224
3225   for (unsigned i = 0; i < arraysize(constant_string_table); i++) {
3226     Handle<String> str =
3227         factory->InternalizeUtf8String(constant_string_table[i].contents);
3228     roots_[constant_string_table[i].index] = *str;
3229   }
3230
3231   // Allocate the hidden string which is used to identify the hidden properties
3232   // in JSObjects. The hash code has a special value so that it will not match
3233   // the empty string when searching for the property. It cannot be part of the
3234   // loop above because it needs to be allocated manually with the special
3235   // hash code in place. The hash code for the hidden_string is zero to ensure
3236   // that it will always be at the first entry in property descriptors.
3237   hidden_string_ = *factory->NewOneByteInternalizedString(
3238       OneByteVector("", 0), String::kEmptyStringHash);
3239
3240   // Create the code_stubs dictionary. The initial size is set to avoid
3241   // expanding the dictionary during bootstrapping.
3242   set_code_stubs(*UnseededNumberDictionary::New(isolate(), 128));
3243
3244   // Create the non_monomorphic_cache used in stub-cache.cc. The initial size
3245   // is set to avoid expanding the dictionary during bootstrapping.
3246   set_non_monomorphic_cache(*UnseededNumberDictionary::New(isolate(), 64));
3247
3248   set_polymorphic_code_cache(PolymorphicCodeCache::cast(
3249       *factory->NewStruct(POLYMORPHIC_CODE_CACHE_TYPE)));
3250
3251   set_instanceof_cache_function(Smi::FromInt(0));
3252   set_instanceof_cache_map(Smi::FromInt(0));
3253   set_instanceof_cache_answer(Smi::FromInt(0));
3254
3255   {
3256     HandleScope scope(isolate());
3257 #define SYMBOL_INIT(name)                                                   \
3258   {                                                                         \
3259     Handle<String> name##d = factory->NewStringFromStaticChars(#name);      \
3260     Handle<Object> symbol(isolate()->factory()->NewPrivateSymbol(name##d)); \
3261     roots_[k##name##RootIndex] = *symbol;                                   \
3262   }
3263     PRIVATE_SYMBOL_LIST(SYMBOL_INIT)
3264 #undef SYMBOL_INIT
3265   }
3266
3267   {
3268     HandleScope scope(isolate());
3269 #define SYMBOL_INIT(name, varname, description)                             \
3270   Handle<Symbol> name = factory->NewSymbol();                               \
3271   Handle<String> name##d = factory->NewStringFromStaticChars(#description); \
3272   name->set_name(*name##d);                                                 \
3273   roots_[k##name##RootIndex] = *name;
3274     PUBLIC_SYMBOL_LIST(SYMBOL_INIT)
3275 #undef SYMBOL_INIT
3276   }
3277
3278   CreateFixedStubs();
3279
3280   // Allocate the dictionary of intrinsic function names.
3281   Handle<NameDictionary> intrinsic_names =
3282       NameDictionary::New(isolate(), Runtime::kNumFunctions, TENURED);
3283   Runtime::InitializeIntrinsicFunctionNames(isolate(), intrinsic_names);
3284   set_intrinsic_function_names(*intrinsic_names);
3285
3286   set_number_string_cache(
3287       *factory->NewFixedArray(kInitialNumberStringCacheSize * 2, TENURED));
3288
3289   // Allocate cache for single character one byte strings.
3290   set_single_character_string_cache(
3291       *factory->NewFixedArray(String::kMaxOneByteCharCode + 1, TENURED));
3292
3293   // Allocate cache for string split and regexp-multiple.
3294   set_string_split_cache(*factory->NewFixedArray(
3295       RegExpResultsCache::kRegExpResultsCacheSize, TENURED));
3296   set_regexp_multiple_cache(*factory->NewFixedArray(
3297       RegExpResultsCache::kRegExpResultsCacheSize, TENURED));
3298
3299   // Allocate cache for external strings pointing to native source code.
3300   set_natives_source_cache(
3301       *factory->NewFixedArray(Natives::GetBuiltinsCount()));
3302
3303   set_experimental_natives_source_cache(
3304       *factory->NewFixedArray(ExperimentalNatives::GetBuiltinsCount()));
3305
3306   set_extra_natives_source_cache(
3307       *factory->NewFixedArray(ExtraNatives::GetBuiltinsCount()));
3308
3309   set_code_stub_natives_source_cache(
3310       *factory->NewFixedArray(CodeStubNatives::GetBuiltinsCount()));
3311
3312   set_undefined_cell(*factory->NewCell(factory->undefined_value()));
3313
3314   // The symbol registry is initialized lazily.
3315   set_symbol_registry(Smi::FromInt(0));
3316
3317   // Allocate object to hold object observation state.
3318   set_observation_state(*factory->NewJSObjectFromMap(
3319       factory->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize)));
3320
3321   // Microtask queue uses the empty fixed array as a sentinel for "empty".
3322   // Number of queued microtasks stored in Isolate::pending_microtask_count().
3323   set_microtask_queue(empty_fixed_array());
3324
3325   {
3326     Code::Kind kinds[] = {Code::LOAD_IC, Code::KEYED_LOAD_IC, Code::STORE_IC,
3327                           Code::KEYED_STORE_IC};
3328     FeedbackVectorSpec spec(0, 4, kinds);
3329     Handle<TypeFeedbackVector> dummy_vector =
3330         factory->NewTypeFeedbackVector(&spec);
3331     for (int i = 0; i < 4; i++) {
3332       dummy_vector->Set(FeedbackVectorICSlot(0),
3333                         *TypeFeedbackVector::MegamorphicSentinel(isolate()),
3334                         SKIP_WRITE_BARRIER);
3335     }
3336     set_dummy_vector(*dummy_vector);
3337   }
3338
3339   set_detached_contexts(empty_fixed_array());
3340   set_retained_maps(ArrayList::cast(empty_fixed_array()));
3341
3342   set_weak_object_to_code_table(
3343       *WeakHashTable::New(isolate(), 16, USE_DEFAULT_MINIMUM_CAPACITY,
3344                           TENURED));
3345
3346   Handle<SeededNumberDictionary> slow_element_dictionary =
3347       SeededNumberDictionary::New(isolate(), 0, TENURED);
3348   slow_element_dictionary->set_requires_slow_elements();
3349   set_empty_slow_element_dictionary(*slow_element_dictionary);
3350
3351   set_materialized_objects(*factory->NewFixedArray(0, TENURED));
3352
3353   // Handling of script id generation is in Factory::NewScript.
3354   set_last_script_id(Smi::FromInt(v8::UnboundScript::kNoScriptId));
3355
3356   Handle<PropertyCell> cell = factory->NewPropertyCell();
3357   cell->set_value(Smi::FromInt(Isolate::kArrayProtectorValid));
3358   set_array_protector(*cell);
3359
3360   cell = factory->NewPropertyCell();
3361   cell->set_value(the_hole_value());
3362   set_empty_property_cell(*cell);
3363
3364   set_weak_stack_trace_list(Smi::FromInt(0));
3365
3366   // Will be filled in by Interpreter::Initialize().
3367   set_interpreter_table(
3368       *interpreter::Interpreter::CreateUninitializedInterpreterTable(
3369           isolate()));
3370
3371   set_allocation_sites_scratchpad(
3372       *factory->NewFixedArray(kAllocationSiteScratchpadSize, TENURED));
3373   InitializeAllocationSitesScratchpad();
3374
3375   // Initialize keyed lookup cache.
3376   isolate_->keyed_lookup_cache()->Clear();
3377
3378   // Initialize context slot cache.
3379   isolate_->context_slot_cache()->Clear();
3380
3381   // Initialize descriptor cache.
3382   isolate_->descriptor_lookup_cache()->Clear();
3383
3384   // Initialize compilation cache.
3385   isolate_->compilation_cache()->Clear();
3386 }
3387
3388
3389 void Heap::AddPrivateGlobalSymbols(Handle<Object> private_intern_table) {
3390 #define ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE(name_arg)                     \
3391   {                                                                      \
3392     Handle<Symbol> symbol(Symbol::cast(roots_[k##name_arg##RootIndex])); \
3393     Handle<String> name_arg##d(String::cast(symbol->name()));            \
3394     JSObject::AddProperty(Handle<JSObject>::cast(private_intern_table),  \
3395                           name_arg##d, symbol, NONE);                    \
3396   }
3397   PRIVATE_SYMBOL_LIST(ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE)
3398 #undef ADD_SYMBOL_TO_PRIVATE_INTERN_TABLE
3399 }
3400
3401
3402 bool Heap::RootCanBeWrittenAfterInitialization(Heap::RootListIndex root_index) {
3403   switch (root_index) {
3404     case kStoreBufferTopRootIndex:
3405     case kNumberStringCacheRootIndex:
3406     case kInstanceofCacheFunctionRootIndex:
3407     case kInstanceofCacheMapRootIndex:
3408     case kInstanceofCacheAnswerRootIndex:
3409     case kCodeStubsRootIndex:
3410     case kNonMonomorphicCacheRootIndex:
3411     case kPolymorphicCodeCacheRootIndex:
3412     case kEmptyScriptRootIndex:
3413     case kSymbolRegistryRootIndex:
3414     case kMaterializedObjectsRootIndex:
3415     case kAllocationSitesScratchpadRootIndex:
3416     case kMicrotaskQueueRootIndex:
3417     case kDetachedContextsRootIndex:
3418     case kWeakObjectToCodeTableRootIndex:
3419     case kRetainedMapsRootIndex:
3420     case kWeakStackTraceListRootIndex:
3421 // Smi values
3422 #define SMI_ENTRY(type, name, Name) case k##Name##RootIndex:
3423       SMI_ROOT_LIST(SMI_ENTRY)
3424 #undef SMI_ENTRY
3425     // String table
3426     case kStringTableRootIndex:
3427       return true;
3428
3429     default:
3430       return false;
3431   }
3432 }
3433
3434
3435 bool Heap::RootCanBeTreatedAsConstant(RootListIndex root_index) {
3436   return !RootCanBeWrittenAfterInitialization(root_index) &&
3437          !InNewSpace(roots_array_start()[root_index]);
3438 }
3439
3440
3441 Object* RegExpResultsCache::Lookup(Heap* heap, String* key_string,
3442                                    Object* key_pattern, ResultsCacheType type) {
3443   FixedArray* cache;
3444   if (!key_string->IsInternalizedString()) return Smi::FromInt(0);
3445   if (type == STRING_SPLIT_SUBSTRINGS) {
3446     DCHECK(key_pattern->IsString());
3447     if (!key_pattern->IsInternalizedString()) return Smi::FromInt(0);
3448     cache = heap->string_split_cache();
3449   } else {
3450     DCHECK(type == REGEXP_MULTIPLE_INDICES);
3451     DCHECK(key_pattern->IsFixedArray());
3452     cache = heap->regexp_multiple_cache();
3453   }
3454
3455   uint32_t hash = key_string->Hash();
3456   uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
3457                     ~(kArrayEntriesPerCacheEntry - 1));
3458   if (cache->get(index + kStringOffset) == key_string &&
3459       cache->get(index + kPatternOffset) == key_pattern) {
3460     return cache->get(index + kArrayOffset);
3461   }
3462   index =
3463       ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
3464   if (cache->get(index + kStringOffset) == key_string &&
3465       cache->get(index + kPatternOffset) == key_pattern) {
3466     return cache->get(index + kArrayOffset);
3467   }
3468   return Smi::FromInt(0);
3469 }
3470
3471
3472 void RegExpResultsCache::Enter(Isolate* isolate, Handle<String> key_string,
3473                                Handle<Object> key_pattern,
3474                                Handle<FixedArray> value_array,
3475                                ResultsCacheType type) {
3476   Factory* factory = isolate->factory();
3477   Handle<FixedArray> cache;
3478   if (!key_string->IsInternalizedString()) return;
3479   if (type == STRING_SPLIT_SUBSTRINGS) {
3480     DCHECK(key_pattern->IsString());
3481     if (!key_pattern->IsInternalizedString()) return;
3482     cache = factory->string_split_cache();
3483   } else {
3484     DCHECK(type == REGEXP_MULTIPLE_INDICES);
3485     DCHECK(key_pattern->IsFixedArray());
3486     cache = factory->regexp_multiple_cache();
3487   }
3488
3489   uint32_t hash = key_string->Hash();
3490   uint32_t index = ((hash & (kRegExpResultsCacheSize - 1)) &
3491                     ~(kArrayEntriesPerCacheEntry - 1));
3492   if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
3493     cache->set(index + kStringOffset, *key_string);
3494     cache->set(index + kPatternOffset, *key_pattern);
3495     cache->set(index + kArrayOffset, *value_array);
3496   } else {
3497     uint32_t index2 =
3498         ((index + kArrayEntriesPerCacheEntry) & (kRegExpResultsCacheSize - 1));
3499     if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
3500       cache->set(index2 + kStringOffset, *key_string);
3501       cache->set(index2 + kPatternOffset, *key_pattern);
3502       cache->set(index2 + kArrayOffset, *value_array);
3503     } else {
3504       cache->set(index2 + kStringOffset, Smi::FromInt(0));
3505       cache->set(index2 + kPatternOffset, Smi::FromInt(0));
3506       cache->set(index2 + kArrayOffset, Smi::FromInt(0));
3507       cache->set(index + kStringOffset, *key_string);
3508       cache->set(index + kPatternOffset, *key_pattern);
3509       cache->set(index + kArrayOffset, *value_array);
3510     }
3511   }
3512   // If the array is a reasonably short list of substrings, convert it into a
3513   // list of internalized strings.
3514   if (type == STRING_SPLIT_SUBSTRINGS && value_array->length() < 100) {
3515     for (int i = 0; i < value_array->length(); i++) {
3516       Handle<String> str(String::cast(value_array->get(i)), isolate);
3517       Handle<String> internalized_str = factory->InternalizeString(str);
3518       value_array->set(i, *internalized_str);
3519     }
3520   }
3521   // Convert backing store to a copy-on-write array.
3522   value_array->set_map_no_write_barrier(*factory->fixed_cow_array_map());
3523 }
3524
3525
3526 void RegExpResultsCache::Clear(FixedArray* cache) {
3527   for (int i = 0; i < kRegExpResultsCacheSize; i++) {
3528     cache->set(i, Smi::FromInt(0));
3529   }
3530 }
3531
3532
3533 int Heap::FullSizeNumberStringCacheLength() {
3534   // Compute the size of the number string cache based on the max newspace size.
3535   // The number string cache has a minimum size based on twice the initial cache
3536   // size to ensure that it is bigger after being made 'full size'.
3537   int number_string_cache_size = max_semi_space_size_ / 512;
3538   number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
3539                                  Min(0x4000, number_string_cache_size));
3540   // There is a string and a number per entry so the length is twice the number
3541   // of entries.
3542   return number_string_cache_size * 2;
3543 }
3544
3545
3546 void Heap::FlushNumberStringCache() {
3547   // Flush the number to string cache.
3548   int len = number_string_cache()->length();
3549   for (int i = 0; i < len; i++) {
3550     number_string_cache()->set_undefined(i);
3551   }
3552 }
3553
3554
3555 void Heap::FlushAllocationSitesScratchpad() {
3556   for (int i = 0; i < allocation_sites_scratchpad_length_; i++) {
3557     allocation_sites_scratchpad()->set_undefined(i);
3558   }
3559   allocation_sites_scratchpad_length_ = 0;
3560 }
3561
3562
3563 void Heap::InitializeAllocationSitesScratchpad() {
3564   DCHECK(allocation_sites_scratchpad()->length() ==
3565          kAllocationSiteScratchpadSize);
3566   for (int i = 0; i < kAllocationSiteScratchpadSize; i++) {
3567     allocation_sites_scratchpad()->set_undefined(i);
3568   }
3569 }
3570
3571
3572 void Heap::AddAllocationSiteToScratchpad(AllocationSite* site,
3573                                          ScratchpadSlotMode mode) {
3574   if (allocation_sites_scratchpad_length_ < kAllocationSiteScratchpadSize) {
3575     // We cannot use the normal write-barrier because slots need to be
3576     // recorded with non-incremental marking as well. We have to explicitly
3577     // record the slot to take evacuation candidates into account.
3578     allocation_sites_scratchpad()->set(allocation_sites_scratchpad_length_,
3579                                        site, SKIP_WRITE_BARRIER);
3580     Object** slot = allocation_sites_scratchpad()->RawFieldOfElementAt(
3581         allocation_sites_scratchpad_length_);
3582
3583     if (mode == RECORD_SCRATCHPAD_SLOT) {
3584       // We need to allow slots buffer overflow here since the evacuation
3585       // candidates are not part of the global list of old space pages and
3586       // releasing an evacuation candidate due to a slots buffer overflow
3587       // results in lost pages.
3588       mark_compact_collector()->RecordSlot(allocation_sites_scratchpad(), slot,
3589                                            *slot, SlotsBuffer::IGNORE_OVERFLOW);
3590     }
3591     allocation_sites_scratchpad_length_++;
3592   }
3593 }
3594
3595
3596
3597 Map* Heap::MapForFixedTypedArray(ExternalArrayType array_type) {
3598   return Map::cast(roots_[RootIndexForFixedTypedArray(array_type)]);
3599 }
3600
3601
3602 Heap::RootListIndex Heap::RootIndexForFixedTypedArray(
3603     ExternalArrayType array_type) {
3604   switch (array_type) {
3605 #define ARRAY_TYPE_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \
3606   case kExternal##Type##Array:                                  \
3607     return kFixed##Type##ArrayMapRootIndex;
3608
3609     TYPED_ARRAYS(ARRAY_TYPE_TO_ROOT_INDEX)
3610 #undef ARRAY_TYPE_TO_ROOT_INDEX
3611
3612     default:
3613       UNREACHABLE();
3614       return kUndefinedValueRootIndex;
3615   }
3616 }
3617
3618
3619 Heap::RootListIndex Heap::RootIndexForEmptyFixedTypedArray(
3620     ElementsKind elementsKind) {
3621   switch (elementsKind) {
3622 #define ELEMENT_KIND_TO_ROOT_INDEX(Type, type, TYPE, ctype, size) \
3623   case TYPE##_ELEMENTS:                                           \
3624     return kEmptyFixed##Type##ArrayRootIndex;
3625
3626     TYPED_ARRAYS(ELEMENT_KIND_TO_ROOT_INDEX)
3627 #undef ELEMENT_KIND_TO_ROOT_INDEX
3628     default:
3629       UNREACHABLE();
3630       return kUndefinedValueRootIndex;
3631   }
3632 }
3633
3634
3635 FixedTypedArrayBase* Heap::EmptyFixedTypedArrayForMap(Map* map) {
3636   return FixedTypedArrayBase::cast(
3637       roots_[RootIndexForEmptyFixedTypedArray(map->elements_kind())]);
3638 }
3639
3640
3641 AllocationResult Heap::AllocateForeign(Address address,
3642                                        PretenureFlag pretenure) {
3643   // Statically ensure that it is safe to allocate foreigns in paged spaces.
3644   STATIC_ASSERT(Foreign::kSize <= Page::kMaxRegularHeapObjectSize);
3645   AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
3646   Foreign* result;
3647   AllocationResult allocation = Allocate(foreign_map(), space);
3648   if (!allocation.To(&result)) return allocation;
3649   result->set_foreign_address(address);
3650   return result;
3651 }
3652
3653
3654 AllocationResult Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3655   if (length < 0 || length > ByteArray::kMaxLength) {
3656     v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
3657   }
3658   int size = ByteArray::SizeFor(length);
3659   AllocationSpace space = SelectSpace(size, pretenure);
3660   HeapObject* result;
3661   {
3662     AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
3663     if (!allocation.To(&result)) return allocation;
3664   }
3665
3666   result->set_map_no_write_barrier(byte_array_map());
3667   ByteArray::cast(result)->set_length(length);
3668   return result;
3669 }
3670
3671
3672 AllocationResult Heap::AllocateBytecodeArray(int length,
3673                                              const byte* const raw_bytecodes,
3674                                              int frame_size) {
3675   if (length < 0 || length > BytecodeArray::kMaxLength) {
3676     v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
3677   }
3678
3679   int size = BytecodeArray::SizeFor(length);
3680   HeapObject* result;
3681   {
3682     AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
3683     if (!allocation.To(&result)) return allocation;
3684   }
3685
3686   result->set_map_no_write_barrier(bytecode_array_map());
3687   BytecodeArray* instance = BytecodeArray::cast(result);
3688   instance->set_length(length);
3689   instance->set_frame_size(frame_size);
3690   CopyBytes(instance->GetFirstBytecodeAddress(), raw_bytecodes, length);
3691
3692   return result;
3693 }
3694
3695
3696 void Heap::CreateFillerObjectAt(Address addr, int size) {
3697   if (size == 0) return;
3698   HeapObject* filler = HeapObject::FromAddress(addr);
3699   if (size == kPointerSize) {
3700     filler->set_map_no_write_barrier(raw_unchecked_one_pointer_filler_map());
3701   } else if (size == 2 * kPointerSize) {
3702     filler->set_map_no_write_barrier(raw_unchecked_two_pointer_filler_map());
3703   } else {
3704     filler->set_map_no_write_barrier(raw_unchecked_free_space_map());
3705     FreeSpace::cast(filler)->nobarrier_set_size(size);
3706   }
3707   // At this point, we may be deserializing the heap from a snapshot, and
3708   // none of the maps have been created yet and are NULL.
3709   DCHECK((filler->map() == NULL && !deserialization_complete_) ||
3710          filler->map()->IsMap());
3711 }
3712
3713
3714 bool Heap::CanMoveObjectStart(HeapObject* object) {
3715   Address address = object->address();
3716
3717   if (lo_space()->Contains(object)) return false;
3718
3719   Page* page = Page::FromAddress(address);
3720   // We can move the object start if:
3721   // (1) the object is not in old space,
3722   // (2) the page of the object was already swept,
3723   // (3) the page was already concurrently swept. This case is an optimization
3724   // for concurrent sweeping. The WasSwept predicate for concurrently swept
3725   // pages is set after sweeping all pages.
3726   return !InOldSpace(address) || page->WasSwept() || page->SweepingCompleted();
3727 }
3728
3729
3730 void Heap::AdjustLiveBytes(HeapObject* object, int by, InvocationMode mode) {
3731   if (incremental_marking()->IsMarking() &&
3732       Marking::IsBlack(Marking::MarkBitFrom(object->address()))) {
3733     if (mode == SEQUENTIAL_TO_SWEEPER) {
3734       MemoryChunk::IncrementLiveBytesFromGC(object, by);
3735     } else {
3736       MemoryChunk::IncrementLiveBytesFromMutator(object, by);
3737     }
3738   }
3739 }
3740
3741
3742 FixedArrayBase* Heap::LeftTrimFixedArray(FixedArrayBase* object,
3743                                          int elements_to_trim) {
3744   DCHECK(!object->IsFixedTypedArrayBase());
3745   const int element_size = object->IsFixedArray() ? kPointerSize : kDoubleSize;
3746   const int bytes_to_trim = elements_to_trim * element_size;
3747   Map* map = object->map();
3748
3749   // For now this trick is only applied to objects in new and paged space.
3750   // In large object space the object's start must coincide with chunk
3751   // and thus the trick is just not applicable.
3752   DCHECK(!lo_space()->Contains(object));
3753   DCHECK(object->map() != fixed_cow_array_map());
3754
3755   STATIC_ASSERT(FixedArrayBase::kMapOffset == 0);
3756   STATIC_ASSERT(FixedArrayBase::kLengthOffset == kPointerSize);
3757   STATIC_ASSERT(FixedArrayBase::kHeaderSize == 2 * kPointerSize);
3758
3759   const int len = object->length();
3760   DCHECK(elements_to_trim <= len);
3761
3762   // Calculate location of new array start.
3763   Address new_start = object->address() + bytes_to_trim;
3764
3765   // Technically in new space this write might be omitted (except for
3766   // debug mode which iterates through the heap), but to play safer
3767   // we still do it.
3768   CreateFillerObjectAt(object->address(), bytes_to_trim);
3769
3770   // Initialize header of the trimmed array. Since left trimming is only
3771   // performed on pages which are not concurrently swept creating a filler
3772   // object does not require synchronization.
3773   DCHECK(CanMoveObjectStart(object));
3774   Object** former_start = HeapObject::RawField(object, 0);
3775   int new_start_index = elements_to_trim * (element_size / kPointerSize);
3776   former_start[new_start_index] = map;
3777   former_start[new_start_index + 1] = Smi::FromInt(len - elements_to_trim);
3778   FixedArrayBase* new_object =
3779       FixedArrayBase::cast(HeapObject::FromAddress(new_start));
3780
3781   // Maintain consistency of live bytes during incremental marking
3782   Marking::TransferMark(this, object->address(), new_start);
3783   AdjustLiveBytes(new_object, -bytes_to_trim, Heap::CONCURRENT_TO_SWEEPER);
3784
3785   // Notify the heap profiler of change in object layout.
3786   OnMoveEvent(new_object, object, new_object->Size());
3787   return new_object;
3788 }
3789
3790
3791 // Force instantiation of templatized method.
3792 template void Heap::RightTrimFixedArray<Heap::SEQUENTIAL_TO_SWEEPER>(
3793     FixedArrayBase*, int);
3794 template void Heap::RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
3795     FixedArrayBase*, int);
3796
3797
3798 template<Heap::InvocationMode mode>
3799 void Heap::RightTrimFixedArray(FixedArrayBase* object, int elements_to_trim) {
3800   const int len = object->length();
3801   DCHECK(elements_to_trim < len);
3802
3803   int bytes_to_trim;
3804   if (object->IsFixedTypedArrayBase()) {
3805     InstanceType type = object->map()->instance_type();
3806     bytes_to_trim =
3807         FixedTypedArrayBase::TypedArraySize(type, len) -
3808         FixedTypedArrayBase::TypedArraySize(type, len - elements_to_trim);
3809   } else {
3810     const int element_size =
3811         object->IsFixedArray() ? kPointerSize : kDoubleSize;
3812     bytes_to_trim = elements_to_trim * element_size;
3813   }
3814
3815   // For now this trick is only applied to objects in new and paged space.
3816   DCHECK(object->map() != fixed_cow_array_map());
3817
3818   if (bytes_to_trim == 0) {
3819     // No need to create filler and update live bytes counters, just initialize
3820     // header of the trimmed array.
3821     object->synchronized_set_length(len - elements_to_trim);
3822     return;
3823   }
3824
3825   // Calculate location of new array end.
3826   Address new_end = object->address() + object->Size() - bytes_to_trim;
3827
3828   // Technically in new space this write might be omitted (except for
3829   // debug mode which iterates through the heap), but to play safer
3830   // we still do it.
3831   // We do not create a filler for objects in large object space.
3832   // TODO(hpayer): We should shrink the large object page if the size
3833   // of the object changed significantly.
3834   if (!lo_space()->Contains(object)) {
3835     CreateFillerObjectAt(new_end, bytes_to_trim);
3836   }
3837
3838   // Initialize header of the trimmed array. We are storing the new length
3839   // using release store after creating a filler for the left-over space to
3840   // avoid races with the sweeper thread.
3841   object->synchronized_set_length(len - elements_to_trim);
3842
3843   // Maintain consistency of live bytes during incremental marking
3844   AdjustLiveBytes(object, -bytes_to_trim, mode);
3845
3846   // Notify the heap profiler of change in object layout. The array may not be
3847   // moved during GC, and size has to be adjusted nevertheless.
3848   HeapProfiler* profiler = isolate()->heap_profiler();
3849   if (profiler->is_tracking_allocations()) {
3850     profiler->UpdateObjectSizeEvent(object->address(), object->Size());
3851   }
3852 }
3853
3854
3855 AllocationResult Heap::AllocateFixedTypedArrayWithExternalPointer(
3856     int length, ExternalArrayType array_type, void* external_pointer,
3857     PretenureFlag pretenure) {
3858   int size = FixedTypedArrayBase::kHeaderSize;
3859   AllocationSpace space = SelectSpace(size, pretenure);
3860   HeapObject* result;
3861   {
3862     AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
3863     if (!allocation.To(&result)) return allocation;
3864   }
3865
3866   result->set_map_no_write_barrier(MapForFixedTypedArray(array_type));
3867   FixedTypedArrayBase* elements = FixedTypedArrayBase::cast(result);
3868   elements->set_base_pointer(Smi::FromInt(0), SKIP_WRITE_BARRIER);
3869   elements->set_external_pointer(external_pointer, SKIP_WRITE_BARRIER);
3870   elements->set_length(length);
3871   return elements;
3872 }
3873
3874 static void ForFixedTypedArray(ExternalArrayType array_type, int* element_size,
3875                                ElementsKind* element_kind) {
3876   switch (array_type) {
3877 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
3878   case kExternal##Type##Array:                          \
3879     *element_size = size;                               \
3880     *element_kind = TYPE##_ELEMENTS;                    \
3881     return;
3882
3883     TYPED_ARRAYS(TYPED_ARRAY_CASE)
3884 #undef TYPED_ARRAY_CASE
3885
3886     default:
3887       *element_size = 0;               // Bogus
3888       *element_kind = UINT8_ELEMENTS;  // Bogus
3889       UNREACHABLE();
3890   }
3891 }
3892
3893
3894 AllocationResult Heap::AllocateFixedTypedArray(int length,
3895                                                ExternalArrayType array_type,
3896                                                bool initialize,
3897                                                PretenureFlag pretenure) {
3898   int element_size;
3899   ElementsKind elements_kind;
3900   ForFixedTypedArray(array_type, &element_size, &elements_kind);
3901   int size = OBJECT_POINTER_ALIGN(length * element_size +
3902                                   FixedTypedArrayBase::kDataOffset);
3903   AllocationSpace space = SelectSpace(size, pretenure);
3904
3905   HeapObject* object;
3906   AllocationResult allocation = AllocateRaw(
3907       size, space, OLD_SPACE,
3908       array_type == kExternalFloat64Array ? kDoubleAligned : kWordAligned);
3909   if (!allocation.To(&object)) return allocation;
3910
3911   object->set_map_no_write_barrier(MapForFixedTypedArray(array_type));
3912   FixedTypedArrayBase* elements = FixedTypedArrayBase::cast(object);
3913   elements->set_base_pointer(elements, SKIP_WRITE_BARRIER);
3914   elements->set_external_pointer(
3915       ExternalReference::fixed_typed_array_base_data_offset().address(),
3916       SKIP_WRITE_BARRIER);
3917   elements->set_length(length);
3918   if (initialize) memset(elements->DataPtr(), 0, elements->DataSize());
3919   return elements;
3920 }
3921
3922
3923 AllocationResult Heap::AllocateCode(int object_size, bool immovable) {
3924   DCHECK(IsAligned(static_cast<intptr_t>(object_size), kCodeAlignment));
3925   AllocationResult allocation =
3926       AllocateRaw(object_size, CODE_SPACE, CODE_SPACE);
3927
3928   HeapObject* result;
3929   if (!allocation.To(&result)) return allocation;
3930
3931   if (immovable) {
3932     Address address = result->address();
3933     // Code objects which should stay at a fixed address are allocated either
3934     // in the first page of code space (objects on the first page of each space
3935     // are never moved) or in large object space.
3936     if (!code_space_->FirstPage()->Contains(address) &&
3937         MemoryChunk::FromAddress(address)->owner()->identity() != LO_SPACE) {
3938       // Discard the first code allocation, which was on a page where it could
3939       // be moved.
3940       CreateFillerObjectAt(result->address(), object_size);
3941       allocation = lo_space_->AllocateRaw(object_size, EXECUTABLE);
3942       if (!allocation.To(&result)) return allocation;
3943       OnAllocationEvent(result, object_size);
3944     }
3945   }
3946
3947   result->set_map_no_write_barrier(code_map());
3948   Code* code = Code::cast(result);
3949   DCHECK(IsAligned(bit_cast<intptr_t>(code->address()), kCodeAlignment));
3950   DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
3951          isolate_->code_range()->contains(code->address()) ||
3952          object_size <= code_space()->AreaSize());
3953   code->set_gc_metadata(Smi::FromInt(0));
3954   code->set_ic_age(global_ic_age_);
3955   return code;
3956 }
3957
3958
3959 AllocationResult Heap::CopyCode(Code* code) {
3960   AllocationResult allocation;
3961
3962   HeapObject* result = NULL;
3963   // Allocate an object the same size as the code object.
3964   int obj_size = code->Size();
3965   allocation = AllocateRaw(obj_size, CODE_SPACE, CODE_SPACE);
3966   if (!allocation.To(&result)) return allocation;
3967
3968   // Copy code object.
3969   Address old_addr = code->address();
3970   Address new_addr = result->address();
3971   CopyBlock(new_addr, old_addr, obj_size);
3972   Code* new_code = Code::cast(result);
3973
3974   // Relocate the copy.
3975   DCHECK(IsAligned(bit_cast<intptr_t>(new_code->address()), kCodeAlignment));
3976   DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
3977          isolate_->code_range()->contains(code->address()) ||
3978          obj_size <= code_space()->AreaSize());
3979   new_code->Relocate(new_addr - old_addr);
3980   return new_code;
3981 }
3982
3983
3984 AllocationResult Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3985   // Allocate ByteArray before the Code object, so that we do not risk
3986   // leaving uninitialized Code object (and breaking the heap).
3987   ByteArray* reloc_info_array;
3988   {
3989     AllocationResult allocation =
3990         AllocateByteArray(reloc_info.length(), TENURED);
3991     if (!allocation.To(&reloc_info_array)) return allocation;
3992   }
3993
3994   int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3995
3996   int new_obj_size = Code::SizeFor(new_body_size);
3997
3998   Address old_addr = code->address();
3999
4000   size_t relocation_offset =
4001       static_cast<size_t>(code->instruction_end() - old_addr);
4002
4003   HeapObject* result;
4004   AllocationResult allocation =
4005       AllocateRaw(new_obj_size, CODE_SPACE, CODE_SPACE);
4006   if (!allocation.To(&result)) return allocation;
4007
4008   // Copy code object.
4009   Address new_addr = result->address();
4010
4011   // Copy header and instructions.
4012   CopyBytes(new_addr, old_addr, relocation_offset);
4013
4014   Code* new_code = Code::cast(result);
4015   new_code->set_relocation_info(reloc_info_array);
4016
4017   // Copy patched rinfo.
4018   CopyBytes(new_code->relocation_start(), reloc_info.start(),
4019             static_cast<size_t>(reloc_info.length()));
4020
4021   // Relocate the copy.
4022   DCHECK(IsAligned(bit_cast<intptr_t>(new_code->address()), kCodeAlignment));
4023   DCHECK(isolate_->code_range() == NULL || !isolate_->code_range()->valid() ||
4024          isolate_->code_range()->contains(code->address()) ||
4025          new_obj_size <= code_space()->AreaSize());
4026
4027   new_code->Relocate(new_addr - old_addr);
4028
4029 #ifdef VERIFY_HEAP
4030   if (FLAG_verify_heap) code->ObjectVerify();
4031 #endif
4032   return new_code;
4033 }
4034
4035
4036 void Heap::InitializeAllocationMemento(AllocationMemento* memento,
4037                                        AllocationSite* allocation_site) {
4038   memento->set_map_no_write_barrier(allocation_memento_map());
4039   DCHECK(allocation_site->map() == allocation_site_map());
4040   memento->set_allocation_site(allocation_site, SKIP_WRITE_BARRIER);
4041   if (FLAG_allocation_site_pretenuring) {
4042     allocation_site->IncrementMementoCreateCount();
4043   }
4044 }
4045
4046
4047 AllocationResult Heap::Allocate(Map* map, AllocationSpace space,
4048                                 AllocationSite* allocation_site) {
4049   DCHECK(gc_state_ == NOT_IN_GC);
4050   DCHECK(map->instance_type() != MAP_TYPE);
4051   // If allocation failures are disallowed, we may allocate in a different
4052   // space when new space is full and the object is not a large object.
4053   AllocationSpace retry_space = (space != NEW_SPACE) ? space : OLD_SPACE;
4054   int size = map->instance_size();
4055   if (allocation_site != NULL) {
4056     size += AllocationMemento::kSize;
4057   }
4058   HeapObject* result;
4059   AllocationResult allocation = AllocateRaw(size, space, retry_space);
4060   if (!allocation.To(&result)) return allocation;
4061   // No need for write barrier since object is white and map is in old space.
4062   result->set_map_no_write_barrier(map);
4063   if (allocation_site != NULL) {
4064     AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>(
4065         reinterpret_cast<Address>(result) + map->instance_size());
4066     InitializeAllocationMemento(alloc_memento, allocation_site);
4067   }
4068   return result;
4069 }
4070
4071
4072 void Heap::InitializeJSObjectFromMap(JSObject* obj, FixedArray* properties,
4073                                      Map* map) {
4074   obj->set_properties(properties);
4075   obj->initialize_elements();
4076   // TODO(1240798): Initialize the object's body using valid initial values
4077   // according to the object's initial map.  For example, if the map's
4078   // instance type is JS_ARRAY_TYPE, the length field should be initialized
4079   // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
4080   // fixed array (e.g. Heap::empty_fixed_array()).  Currently, the object
4081   // verification code has to cope with (temporarily) invalid objects.  See
4082   // for example, JSArray::JSArrayVerify).
4083   Object* filler;
4084   // We cannot always fill with one_pointer_filler_map because objects
4085   // created from API functions expect their internal fields to be initialized
4086   // with undefined_value.
4087   // Pre-allocated fields need to be initialized with undefined_value as well
4088   // so that object accesses before the constructor completes (e.g. in the
4089   // debugger) will not cause a crash.
4090   Object* constructor = map->GetConstructor();
4091   if (constructor->IsJSFunction() &&
4092       JSFunction::cast(constructor)->IsInobjectSlackTrackingInProgress()) {
4093     // We might want to shrink the object later.
4094     DCHECK(obj->GetInternalFieldCount() == 0);
4095     filler = Heap::one_pointer_filler_map();
4096   } else {
4097     filler = Heap::undefined_value();
4098   }
4099   obj->InitializeBody(map, Heap::undefined_value(), filler);
4100 }
4101
4102
4103 AllocationResult Heap::AllocateJSObjectFromMap(
4104     Map* map, PretenureFlag pretenure, AllocationSite* allocation_site) {
4105   // JSFunctions should be allocated using AllocateFunction to be
4106   // properly initialized.
4107   DCHECK(map->instance_type() != JS_FUNCTION_TYPE);
4108
4109   // Both types of global objects should be allocated using
4110   // AllocateGlobalObject to be properly initialized.
4111   DCHECK(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
4112   DCHECK(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
4113
4114   // Allocate the backing storage for the properties.
4115   FixedArray* properties = empty_fixed_array();
4116
4117   // Allocate the JSObject.
4118   int size = map->instance_size();
4119   AllocationSpace space = SelectSpace(size, pretenure);
4120   JSObject* js_obj;
4121   AllocationResult allocation = Allocate(map, space, allocation_site);
4122   if (!allocation.To(&js_obj)) return allocation;
4123
4124   // Initialize the JSObject.
4125   InitializeJSObjectFromMap(js_obj, properties, map);
4126   DCHECK(js_obj->HasFastElements() || js_obj->HasFixedTypedArrayElements());
4127   return js_obj;
4128 }
4129
4130
4131 AllocationResult Heap::AllocateJSObject(JSFunction* constructor,
4132                                         PretenureFlag pretenure,
4133                                         AllocationSite* allocation_site) {
4134   DCHECK(constructor->has_initial_map());
4135
4136   // Allocate the object based on the constructors initial map.
4137   AllocationResult allocation = AllocateJSObjectFromMap(
4138       constructor->initial_map(), pretenure, allocation_site);
4139 #ifdef DEBUG
4140   // Make sure result is NOT a global object if valid.
4141   HeapObject* obj;
4142   DCHECK(!allocation.To(&obj) || !obj->IsGlobalObject());
4143 #endif
4144   return allocation;
4145 }
4146
4147
4148 AllocationResult Heap::CopyJSObject(JSObject* source, AllocationSite* site) {
4149   // Make the clone.
4150   Map* map = source->map();
4151
4152   // We can only clone normal objects or arrays. Copying anything else
4153   // will break invariants.
4154   CHECK(map->instance_type() == JS_OBJECT_TYPE ||
4155         map->instance_type() == JS_ARRAY_TYPE);
4156
4157   int object_size = map->instance_size();
4158   HeapObject* clone;
4159
4160   DCHECK(site == NULL || AllocationSite::CanTrack(map->instance_type()));
4161
4162   WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4163
4164   // If we're forced to always allocate, we use the general allocation
4165   // functions which may leave us with an object in old space.
4166   if (always_allocate()) {
4167     {
4168       AllocationResult allocation =
4169           AllocateRaw(object_size, NEW_SPACE, OLD_SPACE);
4170       if (!allocation.To(&clone)) return allocation;
4171     }
4172     Address clone_address = clone->address();
4173     CopyBlock(clone_address, source->address(), object_size);
4174
4175     // Update write barrier for all tagged fields that lie beyond the header.
4176     const int start_offset = JSObject::kHeaderSize;
4177     const int end_offset = object_size;
4178
4179 #if V8_DOUBLE_FIELDS_UNBOXING
4180     LayoutDescriptorHelper helper(map);
4181     bool has_only_tagged_fields = helper.all_fields_tagged();
4182
4183     if (!has_only_tagged_fields) {
4184       for (int offset = start_offset; offset < end_offset;) {
4185         int end_of_region_offset;
4186         if (helper.IsTagged(offset, end_offset, &end_of_region_offset)) {
4187           RecordWrites(clone_address, offset,
4188                        (end_of_region_offset - offset) / kPointerSize);
4189         }
4190         offset = end_of_region_offset;
4191       }
4192     } else {
4193 #endif
4194       // Object has only tagged fields.
4195       RecordWrites(clone_address, start_offset,
4196                    (end_offset - start_offset) / kPointerSize);
4197 #if V8_DOUBLE_FIELDS_UNBOXING
4198     }
4199 #endif
4200
4201   } else {
4202     wb_mode = SKIP_WRITE_BARRIER;
4203
4204     {
4205       int adjusted_object_size =
4206           site != NULL ? object_size + AllocationMemento::kSize : object_size;
4207       AllocationResult allocation =
4208           AllocateRaw(adjusted_object_size, NEW_SPACE, NEW_SPACE);
4209       if (!allocation.To(&clone)) return allocation;
4210     }
4211     SLOW_DCHECK(InNewSpace(clone));
4212     // Since we know the clone is allocated in new space, we can copy
4213     // the contents without worrying about updating the write barrier.
4214     CopyBlock(clone->address(), source->address(), object_size);
4215
4216     if (site != NULL) {
4217       AllocationMemento* alloc_memento = reinterpret_cast<AllocationMemento*>(
4218           reinterpret_cast<Address>(clone) + object_size);
4219       InitializeAllocationMemento(alloc_memento, site);
4220     }
4221   }
4222
4223   SLOW_DCHECK(JSObject::cast(clone)->GetElementsKind() ==
4224               source->GetElementsKind());
4225   FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4226   FixedArray* properties = FixedArray::cast(source->properties());
4227   // Update elements if necessary.
4228   if (elements->length() > 0) {
4229     FixedArrayBase* elem;
4230     {
4231       AllocationResult allocation;
4232       if (elements->map() == fixed_cow_array_map()) {
4233         allocation = FixedArray::cast(elements);
4234       } else if (source->HasFastDoubleElements()) {
4235         allocation = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4236       } else {
4237         allocation = CopyFixedArray(FixedArray::cast(elements));
4238       }
4239       if (!allocation.To(&elem)) return allocation;
4240     }
4241     JSObject::cast(clone)->set_elements(elem, wb_mode);
4242   }
4243   // Update properties if necessary.
4244   if (properties->length() > 0) {
4245     FixedArray* prop;
4246     {
4247       AllocationResult allocation = CopyFixedArray(properties);
4248       if (!allocation.To(&prop)) return allocation;
4249     }
4250     JSObject::cast(clone)->set_properties(prop, wb_mode);
4251   }
4252   // Return the new clone.
4253   return clone;
4254 }
4255
4256
4257 static inline void WriteOneByteData(Vector<const char> vector, uint8_t* chars,
4258                                     int len) {
4259   // Only works for one byte strings.
4260   DCHECK(vector.length() == len);
4261   MemCopy(chars, vector.start(), len);
4262 }
4263
4264 static inline void WriteTwoByteData(Vector<const char> vector, uint16_t* chars,
4265                                     int len) {
4266   const uint8_t* stream = reinterpret_cast<const uint8_t*>(vector.start());
4267   size_t stream_length = vector.length();
4268   while (stream_length != 0) {
4269     size_t consumed = 0;
4270     uint32_t c = unibrow::Utf8::ValueOf(stream, stream_length, &consumed);
4271     DCHECK(c != unibrow::Utf8::kBadChar);
4272     DCHECK(consumed <= stream_length);
4273     stream_length -= consumed;
4274     stream += consumed;
4275     if (c > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4276       len -= 2;
4277       if (len < 0) break;
4278       *chars++ = unibrow::Utf16::LeadSurrogate(c);
4279       *chars++ = unibrow::Utf16::TrailSurrogate(c);
4280     } else {
4281       len -= 1;
4282       if (len < 0) break;
4283       *chars++ = c;
4284     }
4285   }
4286   DCHECK(stream_length == 0);
4287   DCHECK(len == 0);
4288 }
4289
4290
4291 static inline void WriteOneByteData(String* s, uint8_t* chars, int len) {
4292   DCHECK(s->length() == len);
4293   String::WriteToFlat(s, chars, 0, len);
4294 }
4295
4296
4297 static inline void WriteTwoByteData(String* s, uint16_t* chars, int len) {
4298   DCHECK(s->length() == len);
4299   String::WriteToFlat(s, chars, 0, len);
4300 }
4301
4302
4303 template <bool is_one_byte, typename T>
4304 AllocationResult Heap::AllocateInternalizedStringImpl(T t, int chars,
4305                                                       uint32_t hash_field) {
4306   DCHECK(chars >= 0);
4307   // Compute map and object size.
4308   int size;
4309   Map* map;
4310
4311   DCHECK_LE(0, chars);
4312   DCHECK_GE(String::kMaxLength, chars);
4313   if (is_one_byte) {
4314     map = one_byte_internalized_string_map();
4315     size = SeqOneByteString::SizeFor(chars);
4316   } else {
4317     map = internalized_string_map();
4318     size = SeqTwoByteString::SizeFor(chars);
4319   }
4320   AllocationSpace space = SelectSpace(size, TENURED);
4321
4322   // Allocate string.
4323   HeapObject* result;
4324   {
4325     AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4326     if (!allocation.To(&result)) return allocation;
4327   }
4328
4329   result->set_map_no_write_barrier(map);
4330   // Set length and hash fields of the allocated string.
4331   String* answer = String::cast(result);
4332   answer->set_length(chars);
4333   answer->set_hash_field(hash_field);
4334
4335   DCHECK_EQ(size, answer->Size());
4336
4337   if (is_one_byte) {
4338     WriteOneByteData(t, SeqOneByteString::cast(answer)->GetChars(), chars);
4339   } else {
4340     WriteTwoByteData(t, SeqTwoByteString::cast(answer)->GetChars(), chars);
4341   }
4342   return answer;
4343 }
4344
4345
4346 // Need explicit instantiations.
4347 template AllocationResult Heap::AllocateInternalizedStringImpl<true>(String*,
4348                                                                      int,
4349                                                                      uint32_t);
4350 template AllocationResult Heap::AllocateInternalizedStringImpl<false>(String*,
4351                                                                       int,
4352                                                                       uint32_t);
4353 template AllocationResult Heap::AllocateInternalizedStringImpl<false>(
4354     Vector<const char>, int, uint32_t);
4355
4356
4357 AllocationResult Heap::AllocateRawOneByteString(int length,
4358                                                 PretenureFlag pretenure) {
4359   DCHECK_LE(0, length);
4360   DCHECK_GE(String::kMaxLength, length);
4361   int size = SeqOneByteString::SizeFor(length);
4362   DCHECK(size <= SeqOneByteString::kMaxSize);
4363   AllocationSpace space = SelectSpace(size, pretenure);
4364
4365   HeapObject* result;
4366   {
4367     AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4368     if (!allocation.To(&result)) return allocation;
4369   }
4370
4371   // Partially initialize the object.
4372   result->set_map_no_write_barrier(one_byte_string_map());
4373   String::cast(result)->set_length(length);
4374   String::cast(result)->set_hash_field(String::kEmptyHashField);
4375   DCHECK_EQ(size, HeapObject::cast(result)->Size());
4376
4377   return result;
4378 }
4379
4380
4381 AllocationResult Heap::AllocateRawTwoByteString(int length,
4382                                                 PretenureFlag pretenure) {
4383   DCHECK_LE(0, length);
4384   DCHECK_GE(String::kMaxLength, length);
4385   int size = SeqTwoByteString::SizeFor(length);
4386   DCHECK(size <= SeqTwoByteString::kMaxSize);
4387   AllocationSpace space = SelectSpace(size, pretenure);
4388
4389   HeapObject* result;
4390   {
4391     AllocationResult allocation = AllocateRaw(size, space, OLD_SPACE);
4392     if (!allocation.To(&result)) return allocation;
4393   }
4394
4395   // Partially initialize the object.
4396   result->set_map_no_write_barrier(string_map());
4397   String::cast(result)->set_length(length);
4398   String::cast(result)->set_hash_field(String::kEmptyHashField);
4399   DCHECK_EQ(size, HeapObject::cast(result)->Size());
4400   return result;
4401 }
4402
4403
4404 AllocationResult Heap::AllocateEmptyFixedArray() {
4405   int size = FixedArray::SizeFor(0);
4406   HeapObject* result;
4407   {
4408     AllocationResult allocation = AllocateRaw(size, OLD_SPACE, OLD_SPACE);
4409     if (!allocation.To(&result)) return allocation;
4410   }
4411   // Initialize the object.
4412   result->set_map_no_write_barrier(fixed_array_map());
4413   FixedArray::cast(result)->set_length(0);
4414   return result;
4415 }
4416
4417
4418 AllocationResult Heap::CopyAndTenureFixedCOWArray(FixedArray* src) {
4419   if (!InNewSpace(src)) {
4420     return src;
4421   }
4422
4423   int len = src->length();
4424   HeapObject* obj;
4425   {
4426     AllocationResult allocation = AllocateRawFixedArray(len, TENURED);
4427     if (!allocation.To(&obj)) return allocation;
4428   }
4429   obj->set_map_no_write_barrier(fixed_array_map());
4430   FixedArray* result = FixedArray::cast(obj);
4431   result->set_length(len);
4432
4433   // Copy the content.
4434   DisallowHeapAllocation no_gc;
4435   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4436   for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4437
4438   // TODO(mvstanton): The map is set twice because of protection against calling
4439   // set() on a COW FixedArray. Issue v8:3221 created to track this, and
4440   // we might then be able to remove this whole method.
4441   HeapObject::cast(obj)->set_map_no_write_barrier(fixed_cow_array_map());
4442   return result;
4443 }
4444
4445
4446 AllocationResult Heap::AllocateEmptyFixedTypedArray(
4447     ExternalArrayType array_type) {
4448   return AllocateFixedTypedArray(0, array_type, false, TENURED);
4449 }
4450
4451
4452 AllocationResult Heap::CopyFixedArrayAndGrow(FixedArray* src, int grow_by,
4453                                              PretenureFlag pretenure) {
4454   int old_len = src->length();
4455   int new_len = old_len + grow_by;
4456   DCHECK(new_len >= old_len);
4457   HeapObject* obj;
4458   {
4459     AllocationResult allocation = AllocateRawFixedArray(new_len, pretenure);
4460     if (!allocation.To(&obj)) return allocation;
4461   }
4462   obj->set_map_no_write_barrier(fixed_array_map());
4463   FixedArray* result = FixedArray::cast(obj);
4464   result->set_length(new_len);
4465
4466   // Copy the content.
4467   DisallowHeapAllocation no_gc;
4468   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4469   for (int i = 0; i < old_len; i++) result->set(i, src->get(i), mode);
4470   MemsetPointer(result->data_start() + old_len, undefined_value(), grow_by);
4471   return result;
4472 }
4473
4474
4475 AllocationResult Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4476   int len = src->length();
4477   HeapObject* obj;
4478   {
4479     AllocationResult allocation = AllocateRawFixedArray(len, NOT_TENURED);
4480     if (!allocation.To(&obj)) return allocation;
4481   }
4482   if (InNewSpace(obj)) {
4483     obj->set_map_no_write_barrier(map);
4484     CopyBlock(obj->address() + kPointerSize, src->address() + kPointerSize,
4485               FixedArray::SizeFor(len) - kPointerSize);
4486     return obj;
4487   }
4488   obj->set_map_no_write_barrier(map);
4489   FixedArray* result = FixedArray::cast(obj);
4490   result->set_length(len);
4491
4492   // Copy the content.
4493   DisallowHeapAllocation no_gc;
4494   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4495   for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4496   return result;
4497 }
4498
4499
4500 AllocationResult Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4501                                                    Map* map) {
4502   int len = src->length();
4503   HeapObject* obj;
4504   {
4505     AllocationResult allocation = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4506     if (!allocation.To(&obj)) return allocation;
4507   }
4508   obj->set_map_no_write_barrier(map);
4509   CopyBlock(obj->address() + FixedDoubleArray::kLengthOffset,
4510             src->address() + FixedDoubleArray::kLengthOffset,
4511             FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4512   return obj;
4513 }
4514
4515
4516 AllocationResult Heap::AllocateRawFixedArray(int length,
4517                                              PretenureFlag pretenure) {
4518   if (length < 0 || length > FixedArray::kMaxLength) {
4519     v8::internal::Heap::FatalProcessOutOfMemory("invalid array length", true);
4520   }
4521   int size = FixedArray::SizeFor(length);
4522   AllocationSpace space = SelectSpace(size, pretenure);
4523
4524   return AllocateRaw(size, space, OLD_SPACE);
4525 }
4526
4527
4528 AllocationResult Heap::AllocateFixedArrayWithFiller(int length,
4529                                                     PretenureFlag pretenure,
4530                                                     Object* filler) {
4531   DCHECK(length >= 0);
4532   DCHECK(empty_fixed_array()->IsFixedArray());
4533   if (length == 0) return empty_fixed_array();
4534
4535   DCHECK(!InNewSpace(filler));
4536   HeapObject* result = nullptr;
4537   {
4538     AllocationResult allocation = AllocateRawFixedArray(length, pretenure);
4539     if (!allocation.To(&result)) return allocation;
4540   }
4541
4542   result->set_map_no_write_barrier(fixed_array_map());
4543   FixedArray* array = FixedArray::cast(result);
4544   array->set_length(length);
4545   MemsetPointer(array->data_start(), filler, length);
4546   return array;
4547 }
4548
4549
4550 AllocationResult Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4551   return AllocateFixedArrayWithFiller(length, pretenure, undefined_value());
4552 }
4553
4554
4555 AllocationResult Heap::AllocateUninitializedFixedArray(int length) {
4556   if (length == 0) return empty_fixed_array();
4557
4558   HeapObject* obj;
4559   {
4560     AllocationResult allocation = AllocateRawFixedArray(length, NOT_TENURED);
4561     if (!allocation.To(&obj)) return allocation;
4562   }
4563
4564   obj->set_map_no_write_barrier(fixed_array_map());
4565   FixedArray::cast(obj)->set_length(length);
4566   return obj;
4567 }
4568
4569
4570 AllocationResult Heap::AllocateUninitializedFixedDoubleArray(
4571     int length, PretenureFlag pretenure) {
4572   if (length == 0) return empty_fixed_array();
4573
4574   HeapObject* elements;
4575   AllocationResult allocation = AllocateRawFixedDoubleArray(length, pretenure);
4576   if (!allocation.To(&elements)) return allocation;
4577
4578   elements->set_map_no_write_barrier(fixed_double_array_map());
4579   FixedDoubleArray::cast(elements)->set_length(length);
4580   return elements;
4581 }
4582
4583
4584 AllocationResult Heap::AllocateRawFixedDoubleArray(int length,
4585                                                    PretenureFlag pretenure) {
4586   if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4587     v8::internal::Heap::FatalProcessOutOfMemory("invalid array length",
4588                                                 kDoubleAligned);
4589   }
4590   int size = FixedDoubleArray::SizeFor(length);
4591   AllocationSpace space = SelectSpace(size, pretenure);
4592
4593   HeapObject* object;
4594   {
4595     AllocationResult allocation =
4596         AllocateRaw(size, space, OLD_SPACE, kDoubleAligned);
4597     if (!allocation.To(&object)) return allocation;
4598   }
4599
4600   return object;
4601 }
4602
4603
4604 AllocationResult Heap::AllocateSymbol() {
4605   // Statically ensure that it is safe to allocate symbols in paged spaces.
4606   STATIC_ASSERT(Symbol::kSize <= Page::kMaxRegularHeapObjectSize);
4607
4608   HeapObject* result = NULL;
4609   AllocationResult allocation =
4610       AllocateRaw(Symbol::kSize, OLD_SPACE, OLD_SPACE);
4611   if (!allocation.To(&result)) return allocation;
4612
4613   result->set_map_no_write_barrier(symbol_map());
4614
4615   // Generate a random hash value.
4616   int hash;
4617   int attempts = 0;
4618   do {
4619     hash = isolate()->random_number_generator()->NextInt() & Name::kHashBitMask;
4620     attempts++;
4621   } while (hash == 0 && attempts < 30);
4622   if (hash == 0) hash = 1;  // never return 0
4623
4624   Symbol::cast(result)
4625       ->set_hash_field(Name::kIsNotArrayIndexMask | (hash << Name::kHashShift));
4626   Symbol::cast(result)->set_name(undefined_value());
4627   Symbol::cast(result)->set_flags(Smi::FromInt(0));
4628
4629   DCHECK(!Symbol::cast(result)->is_private());
4630   return result;
4631 }
4632
4633
4634 AllocationResult Heap::AllocateStruct(InstanceType type) {
4635   Map* map;
4636   switch (type) {
4637 #define MAKE_CASE(NAME, Name, name) \
4638   case NAME##_TYPE:                 \
4639     map = name##_map();             \
4640     break;
4641     STRUCT_LIST(MAKE_CASE)
4642 #undef MAKE_CASE
4643     default:
4644       UNREACHABLE();
4645       return exception();
4646   }
4647   int size = map->instance_size();
4648   AllocationSpace space = SelectSpace(size, TENURED);
4649   Struct* result;
4650   {
4651     AllocationResult allocation = Allocate(map, space);
4652     if (!allocation.To(&result)) return allocation;
4653   }
4654   result->InitializeBody(size);
4655   return result;
4656 }
4657
4658
4659 bool Heap::IsHeapIterable() {
4660   // TODO(hpayer): This function is not correct. Allocation folding in old
4661   // space breaks the iterability.
4662   return new_space_top_after_last_gc_ == new_space()->top();
4663 }
4664
4665
4666 void Heap::MakeHeapIterable() {
4667   DCHECK(AllowHeapAllocation::IsAllowed());
4668   if (!IsHeapIterable()) {
4669     CollectAllGarbage(kMakeHeapIterableMask, "Heap::MakeHeapIterable");
4670   }
4671   if (mark_compact_collector()->sweeping_in_progress()) {
4672     mark_compact_collector()->EnsureSweepingCompleted();
4673   }
4674   DCHECK(IsHeapIterable());
4675 }
4676
4677
4678 static double ComputeMutatorUtilization(double mutator_speed, double gc_speed) {
4679   const double kMinMutatorUtilization = 0.0;
4680   const double kConservativeGcSpeedInBytesPerMillisecond = 200000;
4681   if (mutator_speed == 0) return kMinMutatorUtilization;
4682   if (gc_speed == 0) gc_speed = kConservativeGcSpeedInBytesPerMillisecond;
4683   // Derivation:
4684   // mutator_utilization = mutator_time / (mutator_time + gc_time)
4685   // mutator_time = 1 / mutator_speed
4686   // gc_time = 1 / gc_speed
4687   // mutator_utilization = (1 / mutator_speed) /
4688   //                       (1 / mutator_speed + 1 / gc_speed)
4689   // mutator_utilization = gc_speed / (mutator_speed + gc_speed)
4690   return gc_speed / (mutator_speed + gc_speed);
4691 }
4692
4693
4694 double Heap::YoungGenerationMutatorUtilization() {
4695   double mutator_speed = static_cast<double>(
4696       tracer()->NewSpaceAllocationThroughputInBytesPerMillisecond());
4697   double gc_speed = static_cast<double>(
4698       tracer()->ScavengeSpeedInBytesPerMillisecond(kForSurvivedObjects));
4699   double result = ComputeMutatorUtilization(mutator_speed, gc_speed);
4700   if (FLAG_trace_mutator_utilization) {
4701     PrintIsolate(isolate(),
4702                  "Young generation mutator utilization = %.3f ("
4703                  "mutator_speed=%.f, gc_speed=%.f)\n",
4704                  result, mutator_speed, gc_speed);
4705   }
4706   return result;
4707 }
4708
4709
4710 double Heap::OldGenerationMutatorUtilization() {
4711   double mutator_speed = static_cast<double>(
4712       tracer()->OldGenerationAllocationThroughputInBytesPerMillisecond());
4713   double gc_speed = static_cast<double>(
4714       tracer()->CombinedMarkCompactSpeedInBytesPerMillisecond());
4715   double result = ComputeMutatorUtilization(mutator_speed, gc_speed);
4716   if (FLAG_trace_mutator_utilization) {
4717     PrintIsolate(isolate(),
4718                  "Old generation mutator utilization = %.3f ("
4719                  "mutator_speed=%.f, gc_speed=%.f)\n",
4720                  result, mutator_speed, gc_speed);
4721   }
4722   return result;
4723 }
4724
4725
4726 bool Heap::HasLowYoungGenerationAllocationRate() {
4727   const double high_mutator_utilization = 0.993;
4728   return YoungGenerationMutatorUtilization() > high_mutator_utilization;
4729 }
4730
4731
4732 bool Heap::HasLowOldGenerationAllocationRate() {
4733   const double high_mutator_utilization = 0.993;
4734   return OldGenerationMutatorUtilization() > high_mutator_utilization;
4735 }
4736
4737
4738 bool Heap::HasLowAllocationRate() {
4739   return HasLowYoungGenerationAllocationRate() &&
4740          HasLowOldGenerationAllocationRate();
4741 }
4742
4743
4744 bool Heap::HasHighFragmentation() {
4745   intptr_t used = PromotedSpaceSizeOfObjects();
4746   intptr_t committed = CommittedOldGenerationMemory();
4747   return HasHighFragmentation(used, committed);
4748 }
4749
4750
4751 bool Heap::HasHighFragmentation(intptr_t used, intptr_t committed) {
4752   const intptr_t kSlack = 16 * MB;
4753   // Fragmentation is high if committed > 2 * used + kSlack.
4754   // Rewrite the exression to avoid overflow.
4755   return committed - used > used + kSlack;
4756 }
4757
4758
4759 void Heap::ReduceNewSpaceSize() {
4760   // TODO(ulan): Unify this constant with the similar constant in
4761   // GCIdleTimeHandler once the change is merged to 4.5.
4762   static const size_t kLowAllocationThroughput = 1000;
4763   size_t allocation_throughput =
4764       tracer()->CurrentAllocationThroughputInBytesPerMillisecond();
4765   if (FLAG_predictable || allocation_throughput == 0) return;
4766   if (allocation_throughput < kLowAllocationThroughput) {
4767     new_space_.Shrink();
4768     UncommitFromSpace();
4769   }
4770 }
4771
4772
4773 void Heap::FinalizeIncrementalMarkingIfComplete(const char* comment) {
4774   if (FLAG_overapproximate_weak_closure &&
4775       (incremental_marking()->IsReadyToOverApproximateWeakClosure() ||
4776        (!incremental_marking()->weak_closure_was_overapproximated() &&
4777         mark_compact_collector_.marking_deque()->IsEmpty()))) {
4778     OverApproximateWeakClosure(comment);
4779   } else if (incremental_marking()->IsComplete() ||
4780              (mark_compact_collector_.marking_deque()->IsEmpty())) {
4781     CollectAllGarbage(kNoGCFlags, comment);
4782   }
4783 }
4784
4785
4786 bool Heap::TryFinalizeIdleIncrementalMarking(
4787     double idle_time_in_ms, size_t size_of_objects,
4788     size_t final_incremental_mark_compact_speed_in_bytes_per_ms) {
4789   if (FLAG_overapproximate_weak_closure &&
4790       (incremental_marking()->IsReadyToOverApproximateWeakClosure() ||
4791        (!incremental_marking()->weak_closure_was_overapproximated() &&
4792         mark_compact_collector_.marking_deque()->IsEmpty() &&
4793         gc_idle_time_handler_.ShouldDoOverApproximateWeakClosure(
4794             static_cast<size_t>(idle_time_in_ms))))) {
4795     OverApproximateWeakClosure(
4796         "Idle notification: overapproximate weak closure");
4797     return true;
4798   } else if (incremental_marking()->IsComplete() ||
4799              (mark_compact_collector_.marking_deque()->IsEmpty() &&
4800               gc_idle_time_handler_.ShouldDoFinalIncrementalMarkCompact(
4801                   static_cast<size_t>(idle_time_in_ms), size_of_objects,
4802                   final_incremental_mark_compact_speed_in_bytes_per_ms))) {
4803     CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
4804     return true;
4805   }
4806   return false;
4807 }
4808
4809
4810 GCIdleTimeHandler::HeapState Heap::ComputeHeapState() {
4811   GCIdleTimeHandler::HeapState heap_state;
4812   heap_state.contexts_disposed = contexts_disposed_;
4813   heap_state.contexts_disposal_rate =
4814       tracer()->ContextDisposalRateInMilliseconds();
4815   heap_state.size_of_objects = static_cast<size_t>(SizeOfObjects());
4816   heap_state.incremental_marking_stopped = incremental_marking()->IsStopped();
4817   heap_state.sweeping_in_progress =
4818       mark_compact_collector()->sweeping_in_progress();
4819   heap_state.sweeping_completed =
4820       mark_compact_collector()->IsSweepingCompleted();
4821   heap_state.mark_compact_speed_in_bytes_per_ms =
4822       static_cast<size_t>(tracer()->MarkCompactSpeedInBytesPerMillisecond());
4823   heap_state.incremental_marking_speed_in_bytes_per_ms = static_cast<size_t>(
4824       tracer()->IncrementalMarkingSpeedInBytesPerMillisecond());
4825   heap_state.final_incremental_mark_compact_speed_in_bytes_per_ms =
4826       static_cast<size_t>(
4827           tracer()->FinalIncrementalMarkCompactSpeedInBytesPerMillisecond());
4828   heap_state.scavenge_speed_in_bytes_per_ms =
4829       static_cast<size_t>(tracer()->ScavengeSpeedInBytesPerMillisecond());
4830   heap_state.used_new_space_size = new_space_.Size();
4831   heap_state.new_space_capacity = new_space_.Capacity();
4832   heap_state.new_space_allocation_throughput_in_bytes_per_ms =
4833       tracer()->NewSpaceAllocationThroughputInBytesPerMillisecond();
4834   return heap_state;
4835 }
4836
4837
4838 double Heap::AdvanceIncrementalMarking(
4839     intptr_t step_size_in_bytes, double deadline_in_ms,
4840     IncrementalMarking::StepActions step_actions) {
4841   DCHECK(!incremental_marking()->IsStopped());
4842
4843   if (step_size_in_bytes == 0) {
4844     step_size_in_bytes = GCIdleTimeHandler::EstimateMarkingStepSize(
4845         static_cast<size_t>(GCIdleTimeHandler::kIncrementalMarkingStepTimeInMs),
4846         static_cast<size_t>(
4847             tracer()->FinalIncrementalMarkCompactSpeedInBytesPerMillisecond()));
4848   }
4849
4850   double remaining_time_in_ms = 0.0;
4851   do {
4852     incremental_marking()->Step(
4853         step_size_in_bytes, step_actions.completion_action,
4854         step_actions.force_marking, step_actions.force_completion);
4855     remaining_time_in_ms = deadline_in_ms - MonotonicallyIncreasingTimeInMs();
4856   } while (remaining_time_in_ms >=
4857                2.0 * GCIdleTimeHandler::kIncrementalMarkingStepTimeInMs &&
4858            !incremental_marking()->IsComplete() &&
4859            !mark_compact_collector_.marking_deque()->IsEmpty());
4860   return remaining_time_in_ms;
4861 }
4862
4863
4864 bool Heap::PerformIdleTimeAction(GCIdleTimeAction action,
4865                                  GCIdleTimeHandler::HeapState heap_state,
4866                                  double deadline_in_ms) {
4867   bool result = false;
4868   switch (action.type) {
4869     case DONE:
4870       result = true;
4871       break;
4872     case DO_INCREMENTAL_MARKING: {
4873       const double remaining_idle_time_in_ms =
4874           AdvanceIncrementalMarking(action.parameter, deadline_in_ms,
4875                                     IncrementalMarking::IdleStepActions());
4876       if (remaining_idle_time_in_ms > 0.0) {
4877         action.additional_work = TryFinalizeIdleIncrementalMarking(
4878             remaining_idle_time_in_ms, heap_state.size_of_objects,
4879             heap_state.final_incremental_mark_compact_speed_in_bytes_per_ms);
4880       }
4881       break;
4882     }
4883     case DO_FULL_GC: {
4884       DCHECK(contexts_disposed_ > 0);
4885       HistogramTimerScope scope(isolate_->counters()->gc_context());
4886       CollectAllGarbage(kNoGCFlags, "idle notification: contexts disposed");
4887       break;
4888     }
4889     case DO_SCAVENGE:
4890       CollectGarbage(NEW_SPACE, "idle notification: scavenge");
4891       break;
4892     case DO_FINALIZE_SWEEPING:
4893       mark_compact_collector()->EnsureSweepingCompleted();
4894       break;
4895     case DO_NOTHING:
4896       break;
4897   }
4898
4899   return result;
4900 }
4901
4902
4903 void Heap::IdleNotificationEpilogue(GCIdleTimeAction action,
4904                                     GCIdleTimeHandler::HeapState heap_state,
4905                                     double start_ms, double deadline_in_ms) {
4906   double idle_time_in_ms = deadline_in_ms - start_ms;
4907   double current_time = MonotonicallyIncreasingTimeInMs();
4908   last_idle_notification_time_ = current_time;
4909   double deadline_difference = deadline_in_ms - current_time;
4910
4911   contexts_disposed_ = 0;
4912
4913   isolate()->counters()->gc_idle_time_allotted_in_ms()->AddSample(
4914       static_cast<int>(idle_time_in_ms));
4915
4916   if (deadline_in_ms - start_ms >
4917       GCIdleTimeHandler::kMaxFrameRenderingIdleTime) {
4918     int committed_memory = static_cast<int>(CommittedMemory() / KB);
4919     int used_memory = static_cast<int>(heap_state.size_of_objects / KB);
4920     isolate()->counters()->aggregated_memory_heap_committed()->AddSample(
4921         start_ms, committed_memory);
4922     isolate()->counters()->aggregated_memory_heap_used()->AddSample(
4923         start_ms, used_memory);
4924   }
4925
4926   if (deadline_difference >= 0) {
4927     if (action.type != DONE && action.type != DO_NOTHING) {
4928       isolate()->counters()->gc_idle_time_limit_undershot()->AddSample(
4929           static_cast<int>(deadline_difference));
4930     }
4931   } else {
4932     isolate()->counters()->gc_idle_time_limit_overshot()->AddSample(
4933         static_cast<int>(-deadline_difference));
4934   }
4935
4936   if ((FLAG_trace_idle_notification && action.type > DO_NOTHING) ||
4937       FLAG_trace_idle_notification_verbose) {
4938     PrintIsolate(isolate_, "%8.0f ms: ", isolate()->time_millis_since_init());
4939     PrintF(
4940         "Idle notification: requested idle time %.2f ms, used idle time %.2f "
4941         "ms, deadline usage %.2f ms [",
4942         idle_time_in_ms, idle_time_in_ms - deadline_difference,
4943         deadline_difference);
4944     action.Print();
4945     PrintF("]");
4946     if (FLAG_trace_idle_notification_verbose) {
4947       PrintF("[");
4948       heap_state.Print();
4949       PrintF("]");
4950     }
4951     PrintF("\n");
4952   }
4953 }
4954
4955
4956 void Heap::CheckAndNotifyBackgroundIdleNotification(double idle_time_in_ms,
4957                                                     double now_ms) {
4958   if (idle_time_in_ms >= GCIdleTimeHandler::kMinBackgroundIdleTime) {
4959     MemoryReducer::Event event;
4960     event.type = MemoryReducer::kBackgroundIdleNotification;
4961     event.time_ms = now_ms;
4962     event.can_start_incremental_gc = incremental_marking()->IsStopped() &&
4963                                      incremental_marking()->CanBeActivated();
4964     memory_reducer_.NotifyBackgroundIdleNotification(event);
4965     optimize_for_memory_usage_ = true;
4966   } else {
4967     optimize_for_memory_usage_ = false;
4968   }
4969 }
4970
4971
4972 double Heap::MonotonicallyIncreasingTimeInMs() {
4973   return V8::GetCurrentPlatform()->MonotonicallyIncreasingTime() *
4974          static_cast<double>(base::Time::kMillisecondsPerSecond);
4975 }
4976
4977
4978 bool Heap::IdleNotification(int idle_time_in_ms) {
4979   return IdleNotification(
4980       V8::GetCurrentPlatform()->MonotonicallyIncreasingTime() +
4981       (static_cast<double>(idle_time_in_ms) /
4982        static_cast<double>(base::Time::kMillisecondsPerSecond)));
4983 }
4984
4985
4986 bool Heap::IdleNotification(double deadline_in_seconds) {
4987   CHECK(HasBeenSetUp());
4988   double deadline_in_ms =
4989       deadline_in_seconds *
4990       static_cast<double>(base::Time::kMillisecondsPerSecond);
4991   HistogramTimerScope idle_notification_scope(
4992       isolate_->counters()->gc_idle_notification());
4993   double start_ms = MonotonicallyIncreasingTimeInMs();
4994   double idle_time_in_ms = deadline_in_ms - start_ms;
4995
4996   CheckAndNotifyBackgroundIdleNotification(idle_time_in_ms, start_ms);
4997
4998   tracer()->SampleAllocation(start_ms, NewSpaceAllocationCounter(),
4999                              OldGenerationAllocationCounter());
5000
5001   GCIdleTimeHandler::HeapState heap_state = ComputeHeapState();
5002
5003   GCIdleTimeAction action =
5004       gc_idle_time_handler_.Compute(idle_time_in_ms, heap_state);
5005
5006   bool result = PerformIdleTimeAction(action, heap_state, deadline_in_ms);
5007
5008   IdleNotificationEpilogue(action, heap_state, start_ms, deadline_in_ms);
5009   return result;
5010 }
5011
5012
5013 bool Heap::RecentIdleNotificationHappened() {
5014   return (last_idle_notification_time_ +
5015           GCIdleTimeHandler::kMaxScheduledIdleTime) >
5016          MonotonicallyIncreasingTimeInMs();
5017 }
5018
5019
5020 #ifdef DEBUG
5021
5022 void Heap::Print() {
5023   if (!HasBeenSetUp()) return;
5024   isolate()->PrintStack(stdout);
5025   AllSpaces spaces(this);
5026   for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
5027     space->Print();
5028   }
5029 }
5030
5031
5032 void Heap::ReportCodeStatistics(const char* title) {
5033   PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5034   PagedSpace::ResetCodeStatistics(isolate());
5035   // We do not look for code in new space, map space, or old space.  If code
5036   // somehow ends up in those spaces, we would miss it here.
5037   code_space_->CollectCodeStatistics();
5038   lo_space_->CollectCodeStatistics();
5039   PagedSpace::ReportCodeStatistics(isolate());
5040 }
5041
5042
5043 // This function expects that NewSpace's allocated objects histogram is
5044 // populated (via a call to CollectStatistics or else as a side effect of a
5045 // just-completed scavenge collection).
5046 void Heap::ReportHeapStatistics(const char* title) {
5047   USE(title);
5048   PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n", title,
5049          gc_count_);
5050   PrintF("old_generation_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5051          old_generation_allocation_limit_);
5052
5053   PrintF("\n");
5054   PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles(isolate_));
5055   isolate_->global_handles()->PrintStats();
5056   PrintF("\n");
5057
5058   PrintF("Heap statistics : ");
5059   isolate_->memory_allocator()->ReportStatistics();
5060   PrintF("To space : ");
5061   new_space_.ReportStatistics();
5062   PrintF("Old space : ");
5063   old_space_->ReportStatistics();
5064   PrintF("Code space : ");
5065   code_space_->ReportStatistics();
5066   PrintF("Map space : ");
5067   map_space_->ReportStatistics();
5068   PrintF("Large object space : ");
5069   lo_space_->ReportStatistics();
5070   PrintF(">>>>>> ========================================= >>>>>>\n");
5071 }
5072
5073 #endif  // DEBUG
5074
5075 bool Heap::Contains(HeapObject* value) { return Contains(value->address()); }
5076
5077
5078 bool Heap::Contains(Address addr) {
5079   if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false;
5080   return HasBeenSetUp() &&
5081          (new_space_.ToSpaceContains(addr) || old_space_->Contains(addr) ||
5082           code_space_->Contains(addr) || map_space_->Contains(addr) ||
5083           lo_space_->SlowContains(addr));
5084 }
5085
5086
5087 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5088   return InSpace(value->address(), space);
5089 }
5090
5091
5092 bool Heap::InSpace(Address addr, AllocationSpace space) {
5093   if (isolate_->memory_allocator()->IsOutsideAllocatedSpace(addr)) return false;
5094   if (!HasBeenSetUp()) return false;
5095
5096   switch (space) {
5097     case NEW_SPACE:
5098       return new_space_.ToSpaceContains(addr);
5099     case OLD_SPACE:
5100       return old_space_->Contains(addr);
5101     case CODE_SPACE:
5102       return code_space_->Contains(addr);
5103     case MAP_SPACE:
5104       return map_space_->Contains(addr);
5105     case LO_SPACE:
5106       return lo_space_->SlowContains(addr);
5107   }
5108   UNREACHABLE();
5109   return false;
5110 }
5111
5112
5113 bool Heap::IsValidAllocationSpace(AllocationSpace space) {
5114   switch (space) {
5115     case NEW_SPACE:
5116     case OLD_SPACE:
5117     case CODE_SPACE:
5118     case MAP_SPACE:
5119     case LO_SPACE:
5120       return true;
5121     default:
5122       return false;
5123   }
5124 }
5125
5126
5127 bool Heap::RootIsImmortalImmovable(int root_index) {
5128   switch (root_index) {
5129 #define CASE(name)               \
5130   case Heap::k##name##RootIndex: \
5131     return true;
5132     IMMORTAL_IMMOVABLE_ROOT_LIST(CASE);
5133 #undef CASE
5134     default:
5135       return false;
5136   }
5137 }
5138
5139
5140 #ifdef VERIFY_HEAP
5141 void Heap::Verify() {
5142   CHECK(HasBeenSetUp());
5143   HandleScope scope(isolate());
5144
5145   store_buffer()->Verify();
5146
5147   if (mark_compact_collector()->sweeping_in_progress()) {
5148     // We have to wait here for the sweeper threads to have an iterable heap.
5149     mark_compact_collector()->EnsureSweepingCompleted();
5150   }
5151
5152   VerifyPointersVisitor visitor;
5153   IterateRoots(&visitor, VISIT_ONLY_STRONG);
5154
5155   VerifySmisVisitor smis_visitor;
5156   IterateSmiRoots(&smis_visitor);
5157
5158   new_space_.Verify();
5159
5160   old_space_->Verify(&visitor);
5161   map_space_->Verify(&visitor);
5162
5163   VerifyPointersVisitor no_dirty_regions_visitor;
5164   code_space_->Verify(&no_dirty_regions_visitor);
5165
5166   lo_space_->Verify();
5167
5168   mark_compact_collector_.VerifyWeakEmbeddedObjectsInCode();
5169   if (FLAG_omit_map_checks_for_leaf_maps) {
5170     mark_compact_collector_.VerifyOmittedMapChecks();
5171   }
5172 }
5173 #endif
5174
5175
5176 void Heap::ZapFromSpace() {
5177   if (!new_space_.IsFromSpaceCommitted()) return;
5178   NewSpacePageIterator it(new_space_.FromSpaceStart(),
5179                           new_space_.FromSpaceEnd());
5180   while (it.has_next()) {
5181     NewSpacePage* page = it.next();
5182     for (Address cursor = page->area_start(), limit = page->area_end();
5183          cursor < limit; cursor += kPointerSize) {
5184       Memory::Address_at(cursor) = kFromSpaceZapValue;
5185     }
5186   }
5187 }
5188
5189
5190 void Heap::IterateAndMarkPointersToFromSpace(HeapObject* object, Address start,
5191                                              Address end, bool record_slots,
5192                                              ObjectSlotCallback callback) {
5193   Address slot_address = start;
5194
5195   while (slot_address < end) {
5196     Object** slot = reinterpret_cast<Object**>(slot_address);
5197     Object* target = *slot;
5198     // If the store buffer becomes overfull we mark pages as being exempt from
5199     // the store buffer.  These pages are scanned to find pointers that point
5200     // to the new space.  In that case we may hit newly promoted objects and
5201     // fix the pointers before the promotion queue gets to them.  Thus the 'if'.
5202     if (target->IsHeapObject()) {
5203       if (Heap::InFromSpace(target)) {
5204         callback(reinterpret_cast<HeapObject**>(slot),
5205                  HeapObject::cast(target));
5206         Object* new_target = *slot;
5207         if (InNewSpace(new_target)) {
5208           SLOW_DCHECK(Heap::InToSpace(new_target));
5209           SLOW_DCHECK(new_target->IsHeapObject());
5210           store_buffer_.EnterDirectlyIntoStoreBuffer(
5211               reinterpret_cast<Address>(slot));
5212         }
5213         SLOW_DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(new_target));
5214       } else if (record_slots &&
5215                  MarkCompactCollector::IsOnEvacuationCandidate(target)) {
5216         mark_compact_collector()->RecordSlot(object, slot, target);
5217       }
5218     }
5219     slot_address += kPointerSize;
5220   }
5221 }
5222
5223
5224 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5225   IterateStrongRoots(v, mode);
5226   IterateWeakRoots(v, mode);
5227 }
5228
5229
5230 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5231   v->VisitPointer(reinterpret_cast<Object**>(&roots_[kStringTableRootIndex]));
5232   v->Synchronize(VisitorSynchronization::kStringTable);
5233   if (mode != VISIT_ALL_IN_SCAVENGE && mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5234     // Scavenge collections have special processing for this.
5235     external_string_table_.Iterate(v);
5236   }
5237   v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5238 }
5239
5240
5241 void Heap::IterateSmiRoots(ObjectVisitor* v) {
5242   // Acquire execution access since we are going to read stack limit values.
5243   ExecutionAccess access(isolate());
5244   v->VisitPointers(&roots_[kSmiRootsStart], &roots_[kRootListLength]);
5245   v->Synchronize(VisitorSynchronization::kSmiRootList);
5246 }
5247
5248
5249 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5250   v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5251   v->Synchronize(VisitorSynchronization::kStrongRootList);
5252
5253   v->VisitPointer(bit_cast<Object**>(&hidden_string_));
5254   v->Synchronize(VisitorSynchronization::kInternalizedString);
5255
5256   isolate_->bootstrapper()->Iterate(v);
5257   v->Synchronize(VisitorSynchronization::kBootstrapper);
5258   isolate_->Iterate(v);
5259   v->Synchronize(VisitorSynchronization::kTop);
5260   Relocatable::Iterate(isolate_, v);
5261   v->Synchronize(VisitorSynchronization::kRelocatable);
5262
5263   if (isolate_->deoptimizer_data() != NULL) {
5264     isolate_->deoptimizer_data()->Iterate(v);
5265   }
5266   v->Synchronize(VisitorSynchronization::kDebug);
5267   isolate_->compilation_cache()->Iterate(v);
5268   v->Synchronize(VisitorSynchronization::kCompilationCache);
5269
5270   // Iterate over local handles in handle scopes.
5271   isolate_->handle_scope_implementer()->Iterate(v);
5272   isolate_->IterateDeferredHandles(v);
5273   v->Synchronize(VisitorSynchronization::kHandleScope);
5274
5275   // Iterate over the builtin code objects and code stubs in the
5276   // heap. Note that it is not necessary to iterate over code objects
5277   // on scavenge collections.
5278   if (mode != VISIT_ALL_IN_SCAVENGE) {
5279     isolate_->builtins()->IterateBuiltins(v);
5280   }
5281   v->Synchronize(VisitorSynchronization::kBuiltins);
5282
5283   // Iterate over global handles.
5284   switch (mode) {
5285     case VISIT_ONLY_STRONG:
5286       isolate_->global_handles()->IterateStrongRoots(v);
5287       break;
5288     case VISIT_ALL_IN_SCAVENGE:
5289       isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5290       break;
5291     case VISIT_ALL_IN_SWEEP_NEWSPACE:
5292     case VISIT_ALL:
5293       isolate_->global_handles()->IterateAllRoots(v);
5294       break;
5295   }
5296   v->Synchronize(VisitorSynchronization::kGlobalHandles);
5297
5298   // Iterate over eternal handles.
5299   if (mode == VISIT_ALL_IN_SCAVENGE) {
5300     isolate_->eternal_handles()->IterateNewSpaceRoots(v);
5301   } else {
5302     isolate_->eternal_handles()->IterateAllRoots(v);
5303   }
5304   v->Synchronize(VisitorSynchronization::kEternalHandles);
5305
5306   // Iterate over pointers being held by inactive threads.
5307   isolate_->thread_manager()->Iterate(v);
5308   v->Synchronize(VisitorSynchronization::kThreadManager);
5309
5310   // Iterate over other strong roots (currently only identity maps).
5311   for (StrongRootsList* list = strong_roots_list_; list; list = list->next) {
5312     v->VisitPointers(list->start, list->end);
5313   }
5314   v->Synchronize(VisitorSynchronization::kStrongRoots);
5315
5316   // Iterate over the pointers the Serialization/Deserialization code is
5317   // holding.
5318   // During garbage collection this keeps the partial snapshot cache alive.
5319   // During deserialization of the startup snapshot this creates the partial
5320   // snapshot cache and deserializes the objects it refers to.  During
5321   // serialization this does nothing, since the partial snapshot cache is
5322   // empty.  However the next thing we do is create the partial snapshot,
5323   // filling up the partial snapshot cache with objects it needs as we go.
5324   SerializerDeserializer::Iterate(isolate_, v);
5325   // We don't do a v->Synchronize call here, because in debug mode that will
5326   // output a flag to the snapshot.  However at this point the serializer and
5327   // deserializer are deliberately a little unsynchronized (see above) so the
5328   // checking of the sync flag in the snapshot would fail.
5329 }
5330
5331
5332 // TODO(1236194): Since the heap size is configurable on the command line
5333 // and through the API, we should gracefully handle the case that the heap
5334 // size is not big enough to fit all the initial objects.
5335 bool Heap::ConfigureHeap(int max_semi_space_size, int max_old_space_size,
5336                          int max_executable_size, size_t code_range_size) {
5337   if (HasBeenSetUp()) return false;
5338
5339   // Overwrite default configuration.
5340   if (max_semi_space_size > 0) {
5341     max_semi_space_size_ = max_semi_space_size * MB;
5342   }
5343   if (max_old_space_size > 0) {
5344     max_old_generation_size_ = static_cast<intptr_t>(max_old_space_size) * MB;
5345   }
5346   if (max_executable_size > 0) {
5347     max_executable_size_ = static_cast<intptr_t>(max_executable_size) * MB;
5348   }
5349
5350   // If max space size flags are specified overwrite the configuration.
5351   if (FLAG_max_semi_space_size > 0) {
5352     max_semi_space_size_ = FLAG_max_semi_space_size * MB;
5353   }
5354   if (FLAG_max_old_space_size > 0) {
5355     max_old_generation_size_ =
5356         static_cast<intptr_t>(FLAG_max_old_space_size) * MB;
5357   }
5358   if (FLAG_max_executable_size > 0) {
5359     max_executable_size_ = static_cast<intptr_t>(FLAG_max_executable_size) * MB;
5360   }
5361
5362   if (Page::kPageSize > MB) {
5363     max_semi_space_size_ = ROUND_UP(max_semi_space_size_, Page::kPageSize);
5364     max_old_generation_size_ =
5365         ROUND_UP(max_old_generation_size_, Page::kPageSize);
5366     max_executable_size_ = ROUND_UP(max_executable_size_, Page::kPageSize);
5367   }
5368
5369   if (FLAG_stress_compaction) {
5370     // This will cause more frequent GCs when stressing.
5371     max_semi_space_size_ = Page::kPageSize;
5372   }
5373
5374   if (isolate()->snapshot_available()) {
5375     // If we are using a snapshot we always reserve the default amount
5376     // of memory for each semispace because code in the snapshot has
5377     // write-barrier code that relies on the size and alignment of new
5378     // space.  We therefore cannot use a larger max semispace size
5379     // than the default reserved semispace size.
5380     if (max_semi_space_size_ > reserved_semispace_size_) {
5381       max_semi_space_size_ = reserved_semispace_size_;
5382       if (FLAG_trace_gc) {
5383         PrintIsolate(isolate_,
5384                      "Max semi-space size cannot be more than %d kbytes\n",
5385                      reserved_semispace_size_ >> 10);
5386       }
5387     }
5388   } else {
5389     // If we are not using snapshots we reserve space for the actual
5390     // max semispace size.
5391     reserved_semispace_size_ = max_semi_space_size_;
5392   }
5393
5394   // The new space size must be a power of two to support single-bit testing
5395   // for containment.
5396   max_semi_space_size_ =
5397       base::bits::RoundUpToPowerOfTwo32(max_semi_space_size_);
5398   reserved_semispace_size_ =
5399       base::bits::RoundUpToPowerOfTwo32(reserved_semispace_size_);
5400
5401   if (FLAG_min_semi_space_size > 0) {
5402     int initial_semispace_size = FLAG_min_semi_space_size * MB;
5403     if (initial_semispace_size > max_semi_space_size_) {
5404       initial_semispace_size_ = max_semi_space_size_;
5405       if (FLAG_trace_gc) {
5406         PrintIsolate(isolate_,
5407                      "Min semi-space size cannot be more than the maximum "
5408                      "semi-space size of %d MB\n",
5409                      max_semi_space_size_ / MB);
5410       }
5411     } else {
5412       initial_semispace_size_ =
5413           ROUND_UP(initial_semispace_size, Page::kPageSize);
5414     }
5415   }
5416
5417   initial_semispace_size_ = Min(initial_semispace_size_, max_semi_space_size_);
5418
5419   if (FLAG_target_semi_space_size > 0) {
5420     int target_semispace_size = FLAG_target_semi_space_size * MB;
5421     if (target_semispace_size < initial_semispace_size_) {
5422       target_semispace_size_ = initial_semispace_size_;
5423       if (FLAG_trace_gc) {
5424         PrintIsolate(isolate_,
5425                      "Target semi-space size cannot be less than the minimum "
5426                      "semi-space size of %d MB\n",
5427                      initial_semispace_size_ / MB);
5428       }
5429     } else if (target_semispace_size > max_semi_space_size_) {
5430       target_semispace_size_ = max_semi_space_size_;
5431       if (FLAG_trace_gc) {
5432         PrintIsolate(isolate_,
5433                      "Target semi-space size cannot be less than the maximum "
5434                      "semi-space size of %d MB\n",
5435                      max_semi_space_size_ / MB);
5436       }
5437     } else {
5438       target_semispace_size_ = ROUND_UP(target_semispace_size, Page::kPageSize);
5439     }
5440   }
5441
5442   target_semispace_size_ = Max(initial_semispace_size_, target_semispace_size_);
5443
5444   if (FLAG_semi_space_growth_factor < 2) {
5445     FLAG_semi_space_growth_factor = 2;
5446   }
5447
5448   // The old generation is paged and needs at least one page for each space.
5449   int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5450   max_old_generation_size_ =
5451       Max(static_cast<intptr_t>(paged_space_count * Page::kPageSize),
5452           max_old_generation_size_);
5453
5454   // The max executable size must be less than or equal to the max old
5455   // generation size.
5456   if (max_executable_size_ > max_old_generation_size_) {
5457     max_executable_size_ = max_old_generation_size_;
5458   }
5459
5460   if (FLAG_initial_old_space_size > 0) {
5461     initial_old_generation_size_ = FLAG_initial_old_space_size * MB;
5462   } else {
5463     initial_old_generation_size_ =
5464         max_old_generation_size_ / kInitalOldGenerationLimitFactor;
5465   }
5466   old_generation_allocation_limit_ = initial_old_generation_size_;
5467
5468   // We rely on being able to allocate new arrays in paged spaces.
5469   DCHECK(Page::kMaxRegularHeapObjectSize >=
5470          (JSArray::kSize +
5471           FixedArray::SizeFor(JSObject::kInitialMaxFastElementArray) +
5472           AllocationMemento::kSize));
5473
5474   code_range_size_ = code_range_size * MB;
5475
5476   configured_ = true;
5477   return true;
5478 }
5479
5480
5481 void Heap::AddToRingBuffer(const char* string) {
5482   size_t first_part =
5483       Min(strlen(string), kTraceRingBufferSize - ring_buffer_end_);
5484   memcpy(trace_ring_buffer_ + ring_buffer_end_, string, first_part);
5485   ring_buffer_end_ += first_part;
5486   if (first_part < strlen(string)) {
5487     ring_buffer_full_ = true;
5488     size_t second_part = strlen(string) - first_part;
5489     memcpy(trace_ring_buffer_, string + first_part, second_part);
5490     ring_buffer_end_ = second_part;
5491   }
5492 }
5493
5494
5495 void Heap::GetFromRingBuffer(char* buffer) {
5496   size_t copied = 0;
5497   if (ring_buffer_full_) {
5498     copied = kTraceRingBufferSize - ring_buffer_end_;
5499     memcpy(buffer, trace_ring_buffer_ + ring_buffer_end_, copied);
5500   }
5501   memcpy(buffer + copied, trace_ring_buffer_, ring_buffer_end_);
5502 }
5503
5504
5505 bool Heap::ConfigureHeapDefault() { return ConfigureHeap(0, 0, 0, 0); }
5506
5507
5508 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5509   *stats->start_marker = HeapStats::kStartMarker;
5510   *stats->end_marker = HeapStats::kEndMarker;
5511   *stats->new_space_size = new_space_.SizeAsInt();
5512   *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5513   *stats->old_space_size = old_space_->SizeOfObjects();
5514   *stats->old_space_capacity = old_space_->Capacity();
5515   *stats->code_space_size = code_space_->SizeOfObjects();
5516   *stats->code_space_capacity = code_space_->Capacity();
5517   *stats->map_space_size = map_space_->SizeOfObjects();
5518   *stats->map_space_capacity = map_space_->Capacity();
5519   *stats->lo_space_size = lo_space_->Size();
5520   isolate_->global_handles()->RecordStats(stats);
5521   *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5522   *stats->memory_allocator_capacity =
5523       isolate()->memory_allocator()->Size() +
5524       isolate()->memory_allocator()->Available();
5525   *stats->os_error = base::OS::GetLastError();
5526   isolate()->memory_allocator()->Available();
5527   if (take_snapshot) {
5528     HeapIterator iterator(this);
5529     for (HeapObject* obj = iterator.next(); obj != NULL;
5530          obj = iterator.next()) {
5531       InstanceType type = obj->map()->instance_type();
5532       DCHECK(0 <= type && type <= LAST_TYPE);
5533       stats->objects_per_type[type]++;
5534       stats->size_per_type[type] += obj->Size();
5535     }
5536   }
5537   if (stats->last_few_messages != NULL)
5538     GetFromRingBuffer(stats->last_few_messages);
5539   if (stats->js_stacktrace != NULL) {
5540     FixedStringAllocator fixed(stats->js_stacktrace, kStacktraceBufferSize - 1);
5541     StringStream accumulator(&fixed);
5542     isolate()->PrintStack(&accumulator, Isolate::kPrintStackVerbose);
5543   }
5544 }
5545
5546
5547 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5548   return old_space_->SizeOfObjects() + code_space_->SizeOfObjects() +
5549          map_space_->SizeOfObjects() + lo_space_->SizeOfObjects();
5550 }
5551
5552
5553 int64_t Heap::PromotedExternalMemorySize() {
5554   if (amount_of_external_allocated_memory_ <=
5555       amount_of_external_allocated_memory_at_last_global_gc_)
5556     return 0;
5557   return amount_of_external_allocated_memory_ -
5558          amount_of_external_allocated_memory_at_last_global_gc_;
5559 }
5560
5561
5562 const double Heap::kMinHeapGrowingFactor = 1.1;
5563 const double Heap::kMaxHeapGrowingFactor = 4.0;
5564 const double Heap::kMaxHeapGrowingFactorMemoryConstrained = 2.0;
5565 const double Heap::kMaxHeapGrowingFactorIdle = 1.5;
5566 const double Heap::kTargetMutatorUtilization = 0.97;
5567
5568
5569 // Given GC speed in bytes per ms, the allocation throughput in bytes per ms
5570 // (mutator speed), this function returns the heap growing factor that will
5571 // achieve the kTargetMutatorUtilisation if the GC speed and the mutator speed
5572 // remain the same until the next GC.
5573 //
5574 // For a fixed time-frame T = TM + TG, the mutator utilization is the ratio
5575 // TM / (TM + TG), where TM is the time spent in the mutator and TG is the
5576 // time spent in the garbage collector.
5577 //
5578 // Let MU be kTargetMutatorUtilisation, the desired mutator utilization for the
5579 // time-frame from the end of the current GC to the end of the next GC. Based
5580 // on the MU we can compute the heap growing factor F as
5581 //
5582 // F = R * (1 - MU) / (R * (1 - MU) - MU), where R = gc_speed / mutator_speed.
5583 //
5584 // This formula can be derived as follows.
5585 //
5586 // F = Limit / Live by definition, where the Limit is the allocation limit,
5587 // and the Live is size of live objects.
5588 // Let’s assume that we already know the Limit. Then:
5589 //   TG = Limit / gc_speed
5590 //   TM = (TM + TG) * MU, by definition of MU.
5591 //   TM = TG * MU / (1 - MU)
5592 //   TM = Limit *  MU / (gc_speed * (1 - MU))
5593 // On the other hand, if the allocation throughput remains constant:
5594 //   Limit = Live + TM * allocation_throughput = Live + TM * mutator_speed
5595 // Solving it for TM, we get
5596 //   TM = (Limit - Live) / mutator_speed
5597 // Combining the two equation for TM:
5598 //   (Limit - Live) / mutator_speed = Limit * MU / (gc_speed * (1 - MU))
5599 //   (Limit - Live) = Limit * MU * mutator_speed / (gc_speed * (1 - MU))
5600 // substitute R = gc_speed / mutator_speed
5601 //   (Limit - Live) = Limit * MU  / (R * (1 - MU))
5602 // substitute F = Limit / Live
5603 //   F - 1 = F * MU  / (R * (1 - MU))
5604 //   F - F * MU / (R * (1 - MU)) = 1
5605 //   F * (1 - MU / (R * (1 - MU))) = 1
5606 //   F * (R * (1 - MU) - MU) / (R * (1 - MU)) = 1
5607 //   F = R * (1 - MU) / (R * (1 - MU) - MU)
5608 double Heap::HeapGrowingFactor(double gc_speed, double mutator_speed) {
5609   if (gc_speed == 0 || mutator_speed == 0) return kMaxHeapGrowingFactor;
5610
5611   const double speed_ratio = gc_speed / mutator_speed;
5612   const double mu = kTargetMutatorUtilization;
5613
5614   const double a = speed_ratio * (1 - mu);
5615   const double b = speed_ratio * (1 - mu) - mu;
5616
5617   // The factor is a / b, but we need to check for small b first.
5618   double factor =
5619       (a < b * kMaxHeapGrowingFactor) ? a / b : kMaxHeapGrowingFactor;
5620   factor = Min(factor, kMaxHeapGrowingFactor);
5621   factor = Max(factor, kMinHeapGrowingFactor);
5622   return factor;
5623 }
5624
5625
5626 intptr_t Heap::CalculateOldGenerationAllocationLimit(double factor,
5627                                                      intptr_t old_gen_size) {
5628   CHECK(factor > 1.0);
5629   CHECK(old_gen_size > 0);
5630   intptr_t limit = static_cast<intptr_t>(old_gen_size * factor);
5631   limit = Max(limit, old_gen_size + kMinimumOldGenerationAllocationLimit);
5632   limit += new_space_.Capacity();
5633   intptr_t halfway_to_the_max = (old_gen_size + max_old_generation_size_) / 2;
5634   return Min(limit, halfway_to_the_max);
5635 }
5636
5637
5638 void Heap::SetOldGenerationAllocationLimit(intptr_t old_gen_size,
5639                                            double gc_speed,
5640                                            double mutator_speed) {
5641   const double kConservativeHeapGrowingFactor = 1.3;
5642
5643   double factor = HeapGrowingFactor(gc_speed, mutator_speed);
5644
5645   if (FLAG_trace_gc_verbose) {
5646     PrintIsolate(isolate_,
5647                  "Heap growing factor %.1f based on mu=%.3f, speed_ratio=%.f "
5648                  "(gc=%.f, mutator=%.f)\n",
5649                  factor, kTargetMutatorUtilization, gc_speed / mutator_speed,
5650                  gc_speed, mutator_speed);
5651   }
5652
5653   // We set the old generation growing factor to 2 to grow the heap slower on
5654   // memory-constrained devices.
5655   if (max_old_generation_size_ <= kMaxOldSpaceSizeMediumMemoryDevice ||
5656       FLAG_optimize_for_size) {
5657     factor = Min(factor, kMaxHeapGrowingFactorMemoryConstrained);
5658   }
5659
5660   if (memory_reducer_.ShouldGrowHeapSlowly() || optimize_for_memory_usage_) {
5661     factor = Min(factor, kConservativeHeapGrowingFactor);
5662   }
5663
5664   if (FLAG_stress_compaction ||
5665       mark_compact_collector()->reduce_memory_footprint_) {
5666     factor = kMinHeapGrowingFactor;
5667   }
5668
5669   old_generation_allocation_limit_ =
5670       CalculateOldGenerationAllocationLimit(factor, old_gen_size);
5671
5672   if (FLAG_trace_gc_verbose) {
5673     PrintIsolate(isolate_, "Grow: old size: %" V8_PTR_PREFIX
5674                            "d KB, new limit: %" V8_PTR_PREFIX "d KB (%.1f)\n",
5675                  old_gen_size / KB, old_generation_allocation_limit_ / KB,
5676                  factor);
5677   }
5678 }
5679
5680
5681 void Heap::DampenOldGenerationAllocationLimit(intptr_t old_gen_size,
5682                                               double gc_speed,
5683                                               double mutator_speed) {
5684   double factor = HeapGrowingFactor(gc_speed, mutator_speed);
5685   intptr_t limit = CalculateOldGenerationAllocationLimit(factor, old_gen_size);
5686   if (limit < old_generation_allocation_limit_) {
5687     if (FLAG_trace_gc_verbose) {
5688       PrintIsolate(isolate_, "Dampen: old size: %" V8_PTR_PREFIX
5689                              "d KB, old limit: %" V8_PTR_PREFIX
5690                              "d KB, "
5691                              "new limit: %" V8_PTR_PREFIX "d KB (%.1f)\n",
5692                    old_gen_size / KB, old_generation_allocation_limit_ / KB,
5693                    limit / KB, factor);
5694     }
5695     old_generation_allocation_limit_ = limit;
5696   }
5697 }
5698
5699
5700 void Heap::EnableInlineAllocation() {
5701   if (!inline_allocation_disabled_) return;
5702   inline_allocation_disabled_ = false;
5703
5704   // Update inline allocation limit for new space.
5705   new_space()->UpdateInlineAllocationLimit(0);
5706 }
5707
5708
5709 void Heap::DisableInlineAllocation() {
5710   if (inline_allocation_disabled_) return;
5711   inline_allocation_disabled_ = true;
5712
5713   // Update inline allocation limit for new space.
5714   new_space()->UpdateInlineAllocationLimit(0);
5715
5716   // Update inline allocation limit for old spaces.
5717   PagedSpaces spaces(this);
5718   for (PagedSpace* space = spaces.next(); space != NULL;
5719        space = spaces.next()) {
5720     space->EmptyAllocationInfo();
5721   }
5722 }
5723
5724
5725 V8_DECLARE_ONCE(initialize_gc_once);
5726
5727 static void InitializeGCOnce() {
5728   InitializeScavengingVisitorsTables();
5729   NewSpaceScavenger::Initialize();
5730   MarkCompactCollector::Initialize();
5731 }
5732
5733
5734 bool Heap::SetUp() {
5735 #ifdef DEBUG
5736   allocation_timeout_ = FLAG_gc_interval;
5737 #endif
5738
5739   // Initialize heap spaces and initial maps and objects. Whenever something
5740   // goes wrong, just return false. The caller should check the results and
5741   // call Heap::TearDown() to release allocated memory.
5742   //
5743   // If the heap is not yet configured (e.g. through the API), configure it.
5744   // Configuration is based on the flags new-space-size (really the semispace
5745   // size) and old-space-size if set or the initial values of semispace_size_
5746   // and old_generation_size_ otherwise.
5747   if (!configured_) {
5748     if (!ConfigureHeapDefault()) return false;
5749   }
5750
5751   concurrent_sweeping_enabled_ = FLAG_concurrent_sweeping;
5752
5753   base::CallOnce(&initialize_gc_once, &InitializeGCOnce);
5754
5755   // Set up memory allocator.
5756   if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
5757     return false;
5758
5759   // Set up new space.
5760   if (!new_space_.SetUp(reserved_semispace_size_, max_semi_space_size_)) {
5761     return false;
5762   }
5763   new_space_top_after_last_gc_ = new_space()->top();
5764
5765   // Initialize old space.
5766   old_space_ = new OldSpace(this, OLD_SPACE, NOT_EXECUTABLE);
5767   if (old_space_ == NULL) return false;
5768   if (!old_space_->SetUp()) return false;
5769
5770   if (!isolate_->code_range()->SetUp(code_range_size_)) return false;
5771
5772   // Initialize the code space, set its maximum capacity to the old
5773   // generation size. It needs executable memory.
5774   code_space_ = new OldSpace(this, CODE_SPACE, EXECUTABLE);
5775   if (code_space_ == NULL) return false;
5776   if (!code_space_->SetUp()) return false;
5777
5778   // Initialize map space.
5779   map_space_ = new MapSpace(this, MAP_SPACE);
5780   if (map_space_ == NULL) return false;
5781   if (!map_space_->SetUp()) return false;
5782
5783   // The large object code space may contain code or data.  We set the memory
5784   // to be non-executable here for safety, but this means we need to enable it
5785   // explicitly when allocating large code objects.
5786   lo_space_ = new LargeObjectSpace(this, LO_SPACE);
5787   if (lo_space_ == NULL) return false;
5788   if (!lo_space_->SetUp()) return false;
5789
5790   // Set up the seed that is used to randomize the string hash function.
5791   DCHECK(hash_seed() == 0);
5792   if (FLAG_randomize_hashes) {
5793     if (FLAG_hash_seed == 0) {
5794       int rnd = isolate()->random_number_generator()->NextInt();
5795       set_hash_seed(Smi::FromInt(rnd & Name::kHashBitMask));
5796     } else {
5797       set_hash_seed(Smi::FromInt(FLAG_hash_seed));
5798     }
5799   }
5800
5801   for (int i = 0; i < static_cast<int>(v8::Isolate::kUseCounterFeatureCount);
5802        i++) {
5803     deferred_counters_[i] = 0;
5804   }
5805
5806
5807   LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
5808   LOG(isolate_, IntPtrTEvent("heap-available", Available()));
5809
5810   store_buffer()->SetUp();
5811
5812   mark_compact_collector()->SetUp();
5813
5814   return true;
5815 }
5816
5817
5818 bool Heap::CreateHeapObjects() {
5819   // Create initial maps.
5820   if (!CreateInitialMaps()) return false;
5821   CreateApiObjects();
5822
5823   // Create initial objects
5824   CreateInitialObjects();
5825   CHECK_EQ(0u, gc_count_);
5826
5827   set_native_contexts_list(undefined_value());
5828   set_allocation_sites_list(undefined_value());
5829   return true;
5830 }
5831
5832
5833 void Heap::SetStackLimits() {
5834   DCHECK(isolate_ != NULL);
5835   DCHECK(isolate_ == isolate());
5836   // On 64 bit machines, pointers are generally out of range of Smis.  We write
5837   // something that looks like an out of range Smi to the GC.
5838
5839   // Set up the special root array entries containing the stack limits.
5840   // These are actually addresses, but the tag makes the GC ignore it.
5841   roots_[kStackLimitRootIndex] = reinterpret_cast<Object*>(
5842       (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
5843   roots_[kRealStackLimitRootIndex] = reinterpret_cast<Object*>(
5844       (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
5845 }
5846
5847
5848 void Heap::NotifyDeserializationComplete() {
5849   deserialization_complete_ = true;
5850 #ifdef DEBUG
5851   // All pages right after bootstrapping must be marked as never-evacuate.
5852   PagedSpaces spaces(this);
5853   for (PagedSpace* s = spaces.next(); s != NULL; s = spaces.next()) {
5854     PageIterator it(s);
5855     while (it.has_next()) CHECK(it.next()->NeverEvacuate());
5856   }
5857 #endif  // DEBUG
5858 }
5859
5860
5861 void Heap::TearDown() {
5862 #ifdef VERIFY_HEAP
5863   if (FLAG_verify_heap) {
5864     Verify();
5865   }
5866 #endif
5867
5868   UpdateMaximumCommitted();
5869
5870   if (FLAG_print_cumulative_gc_stat) {
5871     PrintF("\n");
5872     PrintF("gc_count=%d ", gc_count_);
5873     PrintF("mark_sweep_count=%d ", ms_count_);
5874     PrintF("max_gc_pause=%.1f ", get_max_gc_pause());
5875     PrintF("total_gc_time=%.1f ", total_gc_time_ms_);
5876     PrintF("min_in_mutator=%.1f ", get_min_in_mutator());
5877     PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ", get_max_alive_after_gc());
5878     PrintF("total_marking_time=%.1f ", tracer_.cumulative_marking_duration());
5879     PrintF("total_sweeping_time=%.1f ", tracer_.cumulative_sweeping_duration());
5880     PrintF("\n\n");
5881   }
5882
5883   if (FLAG_print_max_heap_committed) {
5884     PrintF("\n");
5885     PrintF("maximum_committed_by_heap=%" V8_PTR_PREFIX "d ",
5886            MaximumCommittedMemory());
5887     PrintF("maximum_committed_by_new_space=%" V8_PTR_PREFIX "d ",
5888            new_space_.MaximumCommittedMemory());
5889     PrintF("maximum_committed_by_old_space=%" V8_PTR_PREFIX "d ",
5890            old_space_->MaximumCommittedMemory());
5891     PrintF("maximum_committed_by_code_space=%" V8_PTR_PREFIX "d ",
5892            code_space_->MaximumCommittedMemory());
5893     PrintF("maximum_committed_by_map_space=%" V8_PTR_PREFIX "d ",
5894            map_space_->MaximumCommittedMemory());
5895     PrintF("maximum_committed_by_lo_space=%" V8_PTR_PREFIX "d ",
5896            lo_space_->MaximumCommittedMemory());
5897     PrintF("\n\n");
5898   }
5899
5900   if (FLAG_verify_predictable) {
5901     PrintAlloctionsHash();
5902   }
5903
5904   memory_reducer_.TearDown();
5905
5906   TearDownArrayBuffers();
5907
5908   isolate_->global_handles()->TearDown();
5909
5910   external_string_table_.TearDown();
5911
5912   mark_compact_collector()->TearDown();
5913
5914   new_space_.TearDown();
5915
5916   if (old_space_ != NULL) {
5917     old_space_->TearDown();
5918     delete old_space_;
5919     old_space_ = NULL;
5920   }
5921
5922   if (code_space_ != NULL) {
5923     code_space_->TearDown();
5924     delete code_space_;
5925     code_space_ = NULL;
5926   }
5927
5928   if (map_space_ != NULL) {
5929     map_space_->TearDown();
5930     delete map_space_;
5931     map_space_ = NULL;
5932   }
5933
5934   if (lo_space_ != NULL) {
5935     lo_space_->TearDown();
5936     delete lo_space_;
5937     lo_space_ = NULL;
5938   }
5939
5940   store_buffer()->TearDown();
5941
5942   isolate_->memory_allocator()->TearDown();
5943
5944   StrongRootsList* next = NULL;
5945   for (StrongRootsList* list = strong_roots_list_; list; list = next) {
5946     next = list->next;
5947     delete list;
5948   }
5949   strong_roots_list_ = NULL;
5950 }
5951
5952
5953 void Heap::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback callback,
5954                                  GCType gc_type, bool pass_isolate) {
5955   DCHECK(callback != NULL);
5956   GCPrologueCallbackPair pair(callback, gc_type, pass_isolate);
5957   DCHECK(!gc_prologue_callbacks_.Contains(pair));
5958   return gc_prologue_callbacks_.Add(pair);
5959 }
5960
5961
5962 void Heap::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) {
5963   DCHECK(callback != NULL);
5964   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
5965     if (gc_prologue_callbacks_[i].callback == callback) {
5966       gc_prologue_callbacks_.Remove(i);
5967       return;
5968     }
5969   }
5970   UNREACHABLE();
5971 }
5972
5973
5974 void Heap::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback,
5975                                  GCType gc_type, bool pass_isolate) {
5976   DCHECK(callback != NULL);
5977   GCEpilogueCallbackPair pair(callback, gc_type, pass_isolate);
5978   DCHECK(!gc_epilogue_callbacks_.Contains(pair));
5979   return gc_epilogue_callbacks_.Add(pair);
5980 }
5981
5982
5983 void Heap::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) {
5984   DCHECK(callback != NULL);
5985   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
5986     if (gc_epilogue_callbacks_[i].callback == callback) {
5987       gc_epilogue_callbacks_.Remove(i);
5988       return;
5989     }
5990   }
5991   UNREACHABLE();
5992 }
5993
5994
5995 // TODO(ishell): Find a better place for this.
5996 void Heap::AddWeakObjectToCodeDependency(Handle<HeapObject> obj,
5997                                          Handle<DependentCode> dep) {
5998   DCHECK(!InNewSpace(*obj));
5999   DCHECK(!InNewSpace(*dep));
6000   Handle<WeakHashTable> table(weak_object_to_code_table(), isolate());
6001   table = WeakHashTable::Put(table, obj, dep);
6002   if (*table != weak_object_to_code_table())
6003     set_weak_object_to_code_table(*table);
6004   DCHECK_EQ(*dep, LookupWeakObjectToCodeDependency(obj));
6005 }
6006
6007
6008 DependentCode* Heap::LookupWeakObjectToCodeDependency(Handle<HeapObject> obj) {
6009   Object* dep = weak_object_to_code_table()->Lookup(obj);
6010   if (dep->IsDependentCode()) return DependentCode::cast(dep);
6011   return DependentCode::cast(empty_fixed_array());
6012 }
6013
6014
6015 void Heap::AddRetainedMap(Handle<Map> map) {
6016   if (FLAG_retain_maps_for_n_gc == 0) return;
6017   Handle<WeakCell> cell = Map::WeakCellForMap(map);
6018   Handle<ArrayList> array(retained_maps(), isolate());
6019   array = ArrayList::Add(
6020       array, cell, handle(Smi::FromInt(FLAG_retain_maps_for_n_gc), isolate()),
6021       ArrayList::kReloadLengthAfterAllocation);
6022   if (*array != retained_maps()) {
6023     set_retained_maps(*array);
6024   }
6025 }
6026
6027
6028 void Heap::FatalProcessOutOfMemory(const char* location, bool take_snapshot) {
6029   v8::internal::V8::FatalProcessOutOfMemory(location, take_snapshot);
6030 }
6031
6032 #ifdef DEBUG
6033
6034 class PrintHandleVisitor : public ObjectVisitor {
6035  public:
6036   void VisitPointers(Object** start, Object** end) {
6037     for (Object** p = start; p < end; p++)
6038       PrintF("  handle %p to %p\n", reinterpret_cast<void*>(p),
6039              reinterpret_cast<void*>(*p));
6040   }
6041 };
6042
6043
6044 void Heap::PrintHandles() {
6045   PrintF("Handles:\n");
6046   PrintHandleVisitor v;
6047   isolate_->handle_scope_implementer()->Iterate(&v);
6048 }
6049
6050 #endif
6051
6052 class CheckHandleCountVisitor : public ObjectVisitor {
6053  public:
6054   CheckHandleCountVisitor() : handle_count_(0) {}
6055   ~CheckHandleCountVisitor() {
6056     CHECK(handle_count_ < HandleScope::kCheckHandleThreshold);
6057   }
6058   void VisitPointers(Object** start, Object** end) {
6059     handle_count_ += end - start;
6060   }
6061
6062  private:
6063   ptrdiff_t handle_count_;
6064 };
6065
6066
6067 void Heap::CheckHandleCount() {
6068   CheckHandleCountVisitor v;
6069   isolate_->handle_scope_implementer()->Iterate(&v);
6070 }
6071
6072
6073 Space* AllSpaces::next() {
6074   switch (counter_++) {
6075     case NEW_SPACE:
6076       return heap_->new_space();
6077     case OLD_SPACE:
6078       return heap_->old_space();
6079     case CODE_SPACE:
6080       return heap_->code_space();
6081     case MAP_SPACE:
6082       return heap_->map_space();
6083     case LO_SPACE:
6084       return heap_->lo_space();
6085     default:
6086       return NULL;
6087   }
6088 }
6089
6090
6091 PagedSpace* PagedSpaces::next() {
6092   switch (counter_++) {
6093     case OLD_SPACE:
6094       return heap_->old_space();
6095     case CODE_SPACE:
6096       return heap_->code_space();
6097     case MAP_SPACE:
6098       return heap_->map_space();
6099     default:
6100       return NULL;
6101   }
6102 }
6103
6104
6105 OldSpace* OldSpaces::next() {
6106   switch (counter_++) {
6107     case OLD_SPACE:
6108       return heap_->old_space();
6109     case CODE_SPACE:
6110       return heap_->code_space();
6111     default:
6112       return NULL;
6113   }
6114 }
6115
6116
6117 SpaceIterator::SpaceIterator(Heap* heap)
6118     : heap_(heap), current_space_(FIRST_SPACE), iterator_(NULL) {}
6119
6120
6121 SpaceIterator::~SpaceIterator() {
6122   // Delete active iterator if any.
6123   delete iterator_;
6124 }
6125
6126
6127 bool SpaceIterator::has_next() {
6128   // Iterate until no more spaces.
6129   return current_space_ != LAST_SPACE;
6130 }
6131
6132
6133 ObjectIterator* SpaceIterator::next() {
6134   if (iterator_ != NULL) {
6135     delete iterator_;
6136     iterator_ = NULL;
6137     // Move to the next space
6138     current_space_++;
6139     if (current_space_ > LAST_SPACE) {
6140       return NULL;
6141     }
6142   }
6143
6144   // Return iterator for the new current space.
6145   return CreateIterator();
6146 }
6147
6148
6149 // Create an iterator for the space to iterate.
6150 ObjectIterator* SpaceIterator::CreateIterator() {
6151   DCHECK(iterator_ == NULL);
6152
6153   switch (current_space_) {
6154     case NEW_SPACE:
6155       iterator_ = new SemiSpaceIterator(heap_->new_space());
6156       break;
6157     case OLD_SPACE:
6158       iterator_ = new HeapObjectIterator(heap_->old_space());
6159       break;
6160     case CODE_SPACE:
6161       iterator_ = new HeapObjectIterator(heap_->code_space());
6162       break;
6163     case MAP_SPACE:
6164       iterator_ = new HeapObjectIterator(heap_->map_space());
6165       break;
6166     case LO_SPACE:
6167       iterator_ = new LargeObjectIterator(heap_->lo_space());
6168       break;
6169   }
6170
6171   // Return the newly allocated iterator;
6172   DCHECK(iterator_ != NULL);
6173   return iterator_;
6174 }
6175
6176
6177 class HeapObjectsFilter {
6178  public:
6179   virtual ~HeapObjectsFilter() {}
6180   virtual bool SkipObject(HeapObject* object) = 0;
6181 };
6182
6183
6184 class UnreachableObjectsFilter : public HeapObjectsFilter {
6185  public:
6186   explicit UnreachableObjectsFilter(Heap* heap) : heap_(heap) {
6187     MarkReachableObjects();
6188   }
6189
6190   ~UnreachableObjectsFilter() {
6191     heap_->mark_compact_collector()->ClearMarkbits();
6192   }
6193
6194   bool SkipObject(HeapObject* object) {
6195     if (object->IsFiller()) return true;
6196     MarkBit mark_bit = Marking::MarkBitFrom(object);
6197     return Marking::IsWhite(mark_bit);
6198   }
6199
6200  private:
6201   class MarkingVisitor : public ObjectVisitor {
6202    public:
6203     MarkingVisitor() : marking_stack_(10) {}
6204
6205     void VisitPointers(Object** start, Object** end) {
6206       for (Object** p = start; p < end; p++) {
6207         if (!(*p)->IsHeapObject()) continue;
6208         HeapObject* obj = HeapObject::cast(*p);
6209         MarkBit mark_bit = Marking::MarkBitFrom(obj);
6210         if (Marking::IsWhite(mark_bit)) {
6211           Marking::WhiteToBlack(mark_bit);
6212           marking_stack_.Add(obj);
6213         }
6214       }
6215     }
6216
6217     void TransitiveClosure() {
6218       while (!marking_stack_.is_empty()) {
6219         HeapObject* obj = marking_stack_.RemoveLast();
6220         obj->Iterate(this);
6221       }
6222     }
6223
6224    private:
6225     List<HeapObject*> marking_stack_;
6226   };
6227
6228   void MarkReachableObjects() {
6229     MarkingVisitor visitor;
6230     heap_->IterateRoots(&visitor, VISIT_ALL);
6231     visitor.TransitiveClosure();
6232   }
6233
6234   Heap* heap_;
6235   DisallowHeapAllocation no_allocation_;
6236 };
6237
6238
6239 HeapIterator::HeapIterator(Heap* heap)
6240     : make_heap_iterable_helper_(heap),
6241       no_heap_allocation_(),
6242       heap_(heap),
6243       filtering_(HeapIterator::kNoFiltering),
6244       filter_(NULL) {
6245   Init();
6246 }
6247
6248
6249 HeapIterator::HeapIterator(Heap* heap,
6250                            HeapIterator::HeapObjectsFiltering filtering)
6251     : make_heap_iterable_helper_(heap),
6252       no_heap_allocation_(),
6253       heap_(heap),
6254       filtering_(filtering),
6255       filter_(NULL) {
6256   Init();
6257 }
6258
6259
6260 HeapIterator::~HeapIterator() { Shutdown(); }
6261
6262
6263 void HeapIterator::Init() {
6264   // Start the iteration.
6265   space_iterator_ = new SpaceIterator(heap_);
6266   switch (filtering_) {
6267     case kFilterUnreachable:
6268       filter_ = new UnreachableObjectsFilter(heap_);
6269       break;
6270     default:
6271       break;
6272   }
6273   object_iterator_ = space_iterator_->next();
6274 }
6275
6276
6277 void HeapIterator::Shutdown() {
6278 #ifdef DEBUG
6279   // Assert that in filtering mode we have iterated through all
6280   // objects. Otherwise, heap will be left in an inconsistent state.
6281   if (filtering_ != kNoFiltering) {
6282     DCHECK(object_iterator_ == NULL);
6283   }
6284 #endif
6285   // Make sure the last iterator is deallocated.
6286   delete space_iterator_;
6287   space_iterator_ = NULL;
6288   object_iterator_ = NULL;
6289   delete filter_;
6290   filter_ = NULL;
6291 }
6292
6293
6294 HeapObject* HeapIterator::next() {
6295   if (filter_ == NULL) return NextObject();
6296
6297   HeapObject* obj = NextObject();
6298   while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6299   return obj;
6300 }
6301
6302
6303 HeapObject* HeapIterator::NextObject() {
6304   // No iterator means we are done.
6305   if (object_iterator_ == NULL) return NULL;
6306
6307   if (HeapObject* obj = object_iterator_->next_object()) {
6308     // If the current iterator has more objects we are fine.
6309     return obj;
6310   } else {
6311     // Go though the spaces looking for one that has objects.
6312     while (space_iterator_->has_next()) {
6313       object_iterator_ = space_iterator_->next();
6314       if (HeapObject* obj = object_iterator_->next_object()) {
6315         return obj;
6316       }
6317     }
6318   }
6319   // Done with the last space.
6320   object_iterator_ = NULL;
6321   return NULL;
6322 }
6323
6324
6325 void HeapIterator::reset() {
6326   // Restart the iterator.
6327   Shutdown();
6328   Init();
6329 }
6330
6331
6332 #ifdef DEBUG
6333
6334 Object* const PathTracer::kAnyGlobalObject = NULL;
6335
6336 class PathTracer::MarkVisitor : public ObjectVisitor {
6337  public:
6338   explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6339   void VisitPointers(Object** start, Object** end) {
6340     // Scan all HeapObject pointers in [start, end)
6341     for (Object** p = start; !tracer_->found() && (p < end); p++) {
6342       if ((*p)->IsHeapObject()) tracer_->MarkRecursively(p, this);
6343     }
6344   }
6345
6346  private:
6347   PathTracer* tracer_;
6348 };
6349
6350
6351 class PathTracer::UnmarkVisitor : public ObjectVisitor {
6352  public:
6353   explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6354   void VisitPointers(Object** start, Object** end) {
6355     // Scan all HeapObject pointers in [start, end)
6356     for (Object** p = start; p < end; p++) {
6357       if ((*p)->IsHeapObject()) tracer_->UnmarkRecursively(p, this);
6358     }
6359   }
6360
6361  private:
6362   PathTracer* tracer_;
6363 };
6364
6365
6366 void PathTracer::VisitPointers(Object** start, Object** end) {
6367   bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6368   // Visit all HeapObject pointers in [start, end)
6369   for (Object** p = start; !done && (p < end); p++) {
6370     if ((*p)->IsHeapObject()) {
6371       TracePathFrom(p);
6372       done = ((what_to_find_ == FIND_FIRST) && found_target_);
6373     }
6374   }
6375 }
6376
6377
6378 void PathTracer::Reset() {
6379   found_target_ = false;
6380   object_stack_.Clear();
6381 }
6382
6383
6384 void PathTracer::TracePathFrom(Object** root) {
6385   DCHECK((search_target_ == kAnyGlobalObject) ||
6386          search_target_->IsHeapObject());
6387   found_target_in_trace_ = false;
6388   Reset();
6389
6390   MarkVisitor mark_visitor(this);
6391   MarkRecursively(root, &mark_visitor);
6392
6393   UnmarkVisitor unmark_visitor(this);
6394   UnmarkRecursively(root, &unmark_visitor);
6395
6396   ProcessResults();
6397 }
6398
6399
6400 static bool SafeIsNativeContext(HeapObject* obj) {
6401   return obj->map() == obj->GetHeap()->raw_unchecked_native_context_map();
6402 }
6403
6404
6405 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6406   if (!(*p)->IsHeapObject()) return;
6407
6408   HeapObject* obj = HeapObject::cast(*p);
6409
6410   MapWord map_word = obj->map_word();
6411   if (!map_word.ToMap()->IsHeapObject()) return;  // visited before
6412
6413   if (found_target_in_trace_) return;  // stop if target found
6414   object_stack_.Add(obj);
6415   if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6416       (obj == search_target_)) {
6417     found_target_in_trace_ = true;
6418     found_target_ = true;
6419     return;
6420   }
6421
6422   bool is_native_context = SafeIsNativeContext(obj);
6423
6424   // not visited yet
6425   Map* map = Map::cast(map_word.ToMap());
6426
6427   MapWord marked_map_word =
6428       MapWord::FromRawValue(obj->map_word().ToRawValue() + kMarkTag);
6429   obj->set_map_word(marked_map_word);
6430
6431   // Scan the object body.
6432   if (is_native_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6433     // This is specialized to scan Context's properly.
6434     Object** start =
6435         reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize);
6436     Object** end =
6437         reinterpret_cast<Object**>(obj->address() + Context::kHeaderSize +
6438                                    Context::FIRST_WEAK_SLOT * kPointerSize);
6439     mark_visitor->VisitPointers(start, end);
6440   } else {
6441     obj->IterateBody(map->instance_type(), obj->SizeFromMap(map), mark_visitor);
6442   }
6443
6444   // Scan the map after the body because the body is a lot more interesting
6445   // when doing leak detection.
6446   MarkRecursively(reinterpret_cast<Object**>(&map), mark_visitor);
6447
6448   if (!found_target_in_trace_) {  // don't pop if found the target
6449     object_stack_.RemoveLast();
6450   }
6451 }
6452
6453
6454 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6455   if (!(*p)->IsHeapObject()) return;
6456
6457   HeapObject* obj = HeapObject::cast(*p);
6458
6459   MapWord map_word = obj->map_word();
6460   if (map_word.ToMap()->IsHeapObject()) return;  // unmarked already
6461
6462   MapWord unmarked_map_word =
6463       MapWord::FromRawValue(map_word.ToRawValue() - kMarkTag);
6464   obj->set_map_word(unmarked_map_word);
6465
6466   Map* map = Map::cast(unmarked_map_word.ToMap());
6467
6468   UnmarkRecursively(reinterpret_cast<Object**>(&map), unmark_visitor);
6469
6470   obj->IterateBody(map->instance_type(), obj->SizeFromMap(map), unmark_visitor);
6471 }
6472
6473
6474 void PathTracer::ProcessResults() {
6475   if (found_target_) {
6476     OFStream os(stdout);
6477     os << "=====================================\n"
6478        << "====        Path to object       ====\n"
6479        << "=====================================\n\n";
6480
6481     DCHECK(!object_stack_.is_empty());
6482     for (int i = 0; i < object_stack_.length(); i++) {
6483       if (i > 0) os << "\n     |\n     |\n     V\n\n";
6484       object_stack_[i]->Print(os);
6485     }
6486     os << "=====================================\n";
6487   }
6488 }
6489
6490
6491 // Triggers a depth-first traversal of reachable objects from one
6492 // given root object and finds a path to a specific heap object and
6493 // prints it.
6494 void Heap::TracePathToObjectFrom(Object* target, Object* root) {
6495   PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6496   tracer.VisitPointer(&root);
6497 }
6498
6499
6500 // Triggers a depth-first traversal of reachable objects from roots
6501 // and finds a path to a specific heap object and prints it.
6502 void Heap::TracePathToObject(Object* target) {
6503   PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6504   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6505 }
6506
6507
6508 // Triggers a depth-first traversal of reachable objects from roots
6509 // and finds a path to any global object and prints it. Useful for
6510 // determining the source for leaks of global objects.
6511 void Heap::TracePathToGlobal() {
6512   PathTracer tracer(PathTracer::kAnyGlobalObject, PathTracer::FIND_ALL,
6513                     VISIT_ALL);
6514   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6515 }
6516 #endif
6517
6518
6519 void Heap::UpdateCumulativeGCStatistics(double duration,
6520                                         double spent_in_mutator,
6521                                         double marking_time) {
6522   if (FLAG_print_cumulative_gc_stat) {
6523     total_gc_time_ms_ += duration;
6524     max_gc_pause_ = Max(max_gc_pause_, duration);
6525     max_alive_after_gc_ = Max(max_alive_after_gc_, SizeOfObjects());
6526     min_in_mutator_ = Min(min_in_mutator_, spent_in_mutator);
6527   } else if (FLAG_trace_gc_verbose) {
6528     total_gc_time_ms_ += duration;
6529   }
6530
6531   marking_time_ += marking_time;
6532 }
6533
6534
6535 int KeyedLookupCache::Hash(Handle<Map> map, Handle<Name> name) {
6536   DisallowHeapAllocation no_gc;
6537   // Uses only lower 32 bits if pointers are larger.
6538   uintptr_t addr_hash =
6539       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(*map)) >> kMapHashShift;
6540   return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6541 }
6542
6543
6544 int KeyedLookupCache::Lookup(Handle<Map> map, Handle<Name> name) {
6545   DisallowHeapAllocation no_gc;
6546   int index = (Hash(map, name) & kHashMask);
6547   for (int i = 0; i < kEntriesPerBucket; i++) {
6548     Key& key = keys_[index + i];
6549     if ((key.map == *map) && key.name->Equals(*name)) {
6550       return field_offsets_[index + i];
6551     }
6552   }
6553   return kNotFound;
6554 }
6555
6556
6557 void KeyedLookupCache::Update(Handle<Map> map, Handle<Name> name,
6558                               int field_offset) {
6559   DisallowHeapAllocation no_gc;
6560   if (!name->IsUniqueName()) {
6561     if (!StringTable::InternalizeStringIfExists(
6562              name->GetIsolate(), Handle<String>::cast(name)).ToHandle(&name)) {
6563       return;
6564     }
6565   }
6566   // This cache is cleared only between mark compact passes, so we expect the
6567   // cache to only contain old space names.
6568   DCHECK(!map->GetIsolate()->heap()->InNewSpace(*name));
6569
6570   int index = (Hash(map, name) & kHashMask);
6571   // After a GC there will be free slots, so we use them in order (this may
6572   // help to get the most frequently used one in position 0).
6573   for (int i = 0; i < kEntriesPerBucket; i++) {
6574     Key& key = keys_[index];
6575     Object* free_entry_indicator = NULL;
6576     if (key.map == free_entry_indicator) {
6577       key.map = *map;
6578       key.name = *name;
6579       field_offsets_[index + i] = field_offset;
6580       return;
6581     }
6582   }
6583   // No free entry found in this bucket, so we move them all down one and
6584   // put the new entry at position zero.
6585   for (int i = kEntriesPerBucket - 1; i > 0; i--) {
6586     Key& key = keys_[index + i];
6587     Key& key2 = keys_[index + i - 1];
6588     key = key2;
6589     field_offsets_[index + i] = field_offsets_[index + i - 1];
6590   }
6591
6592   // Write the new first entry.
6593   Key& key = keys_[index];
6594   key.map = *map;
6595   key.name = *name;
6596   field_offsets_[index] = field_offset;
6597 }
6598
6599
6600 void KeyedLookupCache::Clear() {
6601   for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
6602 }
6603
6604
6605 void DescriptorLookupCache::Clear() {
6606   for (int index = 0; index < kLength; index++) keys_[index].source = NULL;
6607 }
6608
6609
6610 void ExternalStringTable::CleanUp() {
6611   int last = 0;
6612   for (int i = 0; i < new_space_strings_.length(); ++i) {
6613     if (new_space_strings_[i] == heap_->the_hole_value()) {
6614       continue;
6615     }
6616     DCHECK(new_space_strings_[i]->IsExternalString());
6617     if (heap_->InNewSpace(new_space_strings_[i])) {
6618       new_space_strings_[last++] = new_space_strings_[i];
6619     } else {
6620       old_space_strings_.Add(new_space_strings_[i]);
6621     }
6622   }
6623   new_space_strings_.Rewind(last);
6624   new_space_strings_.Trim();
6625
6626   last = 0;
6627   for (int i = 0; i < old_space_strings_.length(); ++i) {
6628     if (old_space_strings_[i] == heap_->the_hole_value()) {
6629       continue;
6630     }
6631     DCHECK(old_space_strings_[i]->IsExternalString());
6632     DCHECK(!heap_->InNewSpace(old_space_strings_[i]));
6633     old_space_strings_[last++] = old_space_strings_[i];
6634   }
6635   old_space_strings_.Rewind(last);
6636   old_space_strings_.Trim();
6637 #ifdef VERIFY_HEAP
6638   if (FLAG_verify_heap) {
6639     Verify();
6640   }
6641 #endif
6642 }
6643
6644
6645 void ExternalStringTable::TearDown() {
6646   for (int i = 0; i < new_space_strings_.length(); ++i) {
6647     heap_->FinalizeExternalString(ExternalString::cast(new_space_strings_[i]));
6648   }
6649   new_space_strings_.Free();
6650   for (int i = 0; i < old_space_strings_.length(); ++i) {
6651     heap_->FinalizeExternalString(ExternalString::cast(old_space_strings_[i]));
6652   }
6653   old_space_strings_.Free();
6654 }
6655
6656
6657 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
6658   chunk->set_next_chunk(chunks_queued_for_free_);
6659   chunks_queued_for_free_ = chunk;
6660 }
6661
6662
6663 void Heap::FreeQueuedChunks() {
6664   if (chunks_queued_for_free_ == NULL) return;
6665   MemoryChunk* next;
6666   MemoryChunk* chunk;
6667   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6668     next = chunk->next_chunk();
6669     chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6670
6671     if (chunk->owner()->identity() == LO_SPACE) {
6672       // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
6673       // If FromAnyPointerAddress encounters a slot that belongs to a large
6674       // chunk queued for deletion it will fail to find the chunk because
6675       // it try to perform a search in the list of pages owned by of the large
6676       // object space and queued chunks were detached from that list.
6677       // To work around this we split large chunk into normal kPageSize aligned
6678       // pieces and initialize size, owner and flags field of every piece.
6679       // If FromAnyPointerAddress encounters a slot that belongs to one of
6680       // these smaller pieces it will treat it as a slot on a normal Page.
6681       Address chunk_end = chunk->address() + chunk->size();
6682       MemoryChunk* inner =
6683           MemoryChunk::FromAddress(chunk->address() + Page::kPageSize);
6684       MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
6685       while (inner <= inner_last) {
6686         // Size of a large chunk is always a multiple of
6687         // OS::AllocateAlignment() so there is always
6688         // enough space for a fake MemoryChunk header.
6689         Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
6690         // Guard against overflow.
6691         if (area_end < inner->address()) area_end = chunk_end;
6692         inner->SetArea(inner->address(), area_end);
6693         inner->set_size(Page::kPageSize);
6694         inner->set_owner(lo_space());
6695         inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
6696         inner = MemoryChunk::FromAddress(inner->address() + Page::kPageSize);
6697       }
6698     }
6699   }
6700   isolate_->heap()->store_buffer()->Compact();
6701   isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
6702   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
6703     next = chunk->next_chunk();
6704     isolate_->memory_allocator()->Free(chunk);
6705   }
6706   chunks_queued_for_free_ = NULL;
6707 }
6708
6709
6710 void Heap::RememberUnmappedPage(Address page, bool compacted) {
6711   uintptr_t p = reinterpret_cast<uintptr_t>(page);
6712   // Tag the page pointer to make it findable in the dump file.
6713   if (compacted) {
6714     p ^= 0xc1ead & (Page::kPageSize - 1);  // Cleared.
6715   } else {
6716     p ^= 0x1d1ed & (Page::kPageSize - 1);  // I died.
6717   }
6718   remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
6719       reinterpret_cast<Address>(p);
6720   remembered_unmapped_pages_index_++;
6721   remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
6722 }
6723
6724
6725 void Heap::ClearObjectStats(bool clear_last_time_stats) {
6726   memset(object_counts_, 0, sizeof(object_counts_));
6727   memset(object_sizes_, 0, sizeof(object_sizes_));
6728   if (clear_last_time_stats) {
6729     memset(object_counts_last_time_, 0, sizeof(object_counts_last_time_));
6730     memset(object_sizes_last_time_, 0, sizeof(object_sizes_last_time_));
6731   }
6732 }
6733
6734
6735 static base::LazyMutex object_stats_mutex = LAZY_MUTEX_INITIALIZER;
6736
6737
6738 void Heap::TraceObjectStat(const char* name, int count, int size, double time) {
6739   PrintIsolate(isolate_,
6740                "heap:%p, time:%f, gc:%d, type:%s, count:%d, size:%d\n",
6741                static_cast<void*>(this), time, ms_count_, name, count, size);
6742 }
6743
6744
6745 void Heap::TraceObjectStats() {
6746   base::LockGuard<base::Mutex> lock_guard(object_stats_mutex.Pointer());
6747   int index;
6748   int count;
6749   int size;
6750   int total_size = 0;
6751   double time = isolate_->time_millis_since_init();
6752 #define TRACE_OBJECT_COUNT(name)                     \
6753   count = static_cast<int>(object_counts_[name]);    \
6754   size = static_cast<int>(object_sizes_[name]) / KB; \
6755   total_size += size;                                \
6756   TraceObjectStat(#name, count, size, time);
6757   INSTANCE_TYPE_LIST(TRACE_OBJECT_COUNT)
6758 #undef TRACE_OBJECT_COUNT
6759 #define TRACE_OBJECT_COUNT(name)                      \
6760   index = FIRST_CODE_KIND_SUB_TYPE + Code::name;      \
6761   count = static_cast<int>(object_counts_[index]);    \
6762   size = static_cast<int>(object_sizes_[index]) / KB; \
6763   TraceObjectStat("*CODE_" #name, count, size, time);
6764   CODE_KIND_LIST(TRACE_OBJECT_COUNT)
6765 #undef TRACE_OBJECT_COUNT
6766 #define TRACE_OBJECT_COUNT(name)                      \
6767   index = FIRST_FIXED_ARRAY_SUB_TYPE + name;          \
6768   count = static_cast<int>(object_counts_[index]);    \
6769   size = static_cast<int>(object_sizes_[index]) / KB; \
6770   TraceObjectStat("*FIXED_ARRAY_" #name, count, size, time);
6771   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(TRACE_OBJECT_COUNT)
6772 #undef TRACE_OBJECT_COUNT
6773 #define TRACE_OBJECT_COUNT(name)                                              \
6774   index =                                                                     \
6775       FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge; \
6776   count = static_cast<int>(object_counts_[index]);                            \
6777   size = static_cast<int>(object_sizes_[index]) / KB;                         \
6778   TraceObjectStat("*CODE_AGE_" #name, count, size, time);
6779   CODE_AGE_LIST_COMPLETE(TRACE_OBJECT_COUNT)
6780 #undef TRACE_OBJECT_COUNT
6781 }
6782
6783
6784 void Heap::CheckpointObjectStats() {
6785   base::LockGuard<base::Mutex> lock_guard(object_stats_mutex.Pointer());
6786   Counters* counters = isolate()->counters();
6787 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)              \
6788   counters->count_of_##name()->Increment(                \
6789       static_cast<int>(object_counts_[name]));           \
6790   counters->count_of_##name()->Decrement(                \
6791       static_cast<int>(object_counts_last_time_[name])); \
6792   counters->size_of_##name()->Increment(                 \
6793       static_cast<int>(object_sizes_[name]));            \
6794   counters->size_of_##name()->Decrement(                 \
6795       static_cast<int>(object_sizes_last_time_[name]));
6796   INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6797 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6798   int index;
6799 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)               \
6800   index = FIRST_CODE_KIND_SUB_TYPE + Code::name;          \
6801   counters->count_of_CODE_TYPE_##name()->Increment(       \
6802       static_cast<int>(object_counts_[index]));           \
6803   counters->count_of_CODE_TYPE_##name()->Decrement(       \
6804       static_cast<int>(object_counts_last_time_[index])); \
6805   counters->size_of_CODE_TYPE_##name()->Increment(        \
6806       static_cast<int>(object_sizes_[index]));            \
6807   counters->size_of_CODE_TYPE_##name()->Decrement(        \
6808       static_cast<int>(object_sizes_last_time_[index]));
6809   CODE_KIND_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6810 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6811 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)               \
6812   index = FIRST_FIXED_ARRAY_SUB_TYPE + name;              \
6813   counters->count_of_FIXED_ARRAY_##name()->Increment(     \
6814       static_cast<int>(object_counts_[index]));           \
6815   counters->count_of_FIXED_ARRAY_##name()->Decrement(     \
6816       static_cast<int>(object_counts_last_time_[index])); \
6817   counters->size_of_FIXED_ARRAY_##name()->Increment(      \
6818       static_cast<int>(object_sizes_[index]));            \
6819   counters->size_of_FIXED_ARRAY_##name()->Decrement(      \
6820       static_cast<int>(object_sizes_last_time_[index]));
6821   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(ADJUST_LAST_TIME_OBJECT_COUNT)
6822 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6823 #define ADJUST_LAST_TIME_OBJECT_COUNT(name)                                   \
6824   index =                                                                     \
6825       FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge; \
6826   counters->count_of_CODE_AGE_##name()->Increment(                            \
6827       static_cast<int>(object_counts_[index]));                               \
6828   counters->count_of_CODE_AGE_##name()->Decrement(                            \
6829       static_cast<int>(object_counts_last_time_[index]));                     \
6830   counters->size_of_CODE_AGE_##name()->Increment(                             \
6831       static_cast<int>(object_sizes_[index]));                                \
6832   counters->size_of_CODE_AGE_##name()->Decrement(                             \
6833       static_cast<int>(object_sizes_last_time_[index]));
6834   CODE_AGE_LIST_COMPLETE(ADJUST_LAST_TIME_OBJECT_COUNT)
6835 #undef ADJUST_LAST_TIME_OBJECT_COUNT
6836
6837   MemCopy(object_counts_last_time_, object_counts_, sizeof(object_counts_));
6838   MemCopy(object_sizes_last_time_, object_sizes_, sizeof(object_sizes_));
6839   ClearObjectStats();
6840 }
6841
6842
6843 void Heap::RegisterStrongRoots(Object** start, Object** end) {
6844   StrongRootsList* list = new StrongRootsList();
6845   list->next = strong_roots_list_;
6846   list->start = start;
6847   list->end = end;
6848   strong_roots_list_ = list;
6849 }
6850
6851
6852 void Heap::UnregisterStrongRoots(Object** start) {
6853   StrongRootsList* prev = NULL;
6854   StrongRootsList* list = strong_roots_list_;
6855   while (list != nullptr) {
6856     StrongRootsList* next = list->next;
6857     if (list->start == start) {
6858       if (prev) {
6859         prev->next = next;
6860       } else {
6861         strong_roots_list_ = next;
6862       }
6863       delete list;
6864     } else {
6865       prev = list;
6866     }
6867     list = next;
6868   }
6869 }
6870
6871
6872 bool Heap::GetObjectTypeName(size_t index, const char** object_type,
6873                              const char** object_sub_type) {
6874   if (index >= OBJECT_STATS_COUNT) return false;
6875
6876   switch (static_cast<int>(index)) {
6877 #define COMPARE_AND_RETURN_NAME(name) \
6878   case name:                          \
6879     *object_type = #name;             \
6880     *object_sub_type = "";            \
6881     return true;
6882     INSTANCE_TYPE_LIST(COMPARE_AND_RETURN_NAME)
6883 #undef COMPARE_AND_RETURN_NAME
6884 #define COMPARE_AND_RETURN_NAME(name)         \
6885   case FIRST_CODE_KIND_SUB_TYPE + Code::name: \
6886     *object_type = "CODE_TYPE";               \
6887     *object_sub_type = "CODE_KIND/" #name;    \
6888     return true;
6889     CODE_KIND_LIST(COMPARE_AND_RETURN_NAME)
6890 #undef COMPARE_AND_RETURN_NAME
6891 #define COMPARE_AND_RETURN_NAME(name)     \
6892   case FIRST_FIXED_ARRAY_SUB_TYPE + name: \
6893     *object_type = "FIXED_ARRAY_TYPE";    \
6894     *object_sub_type = #name;             \
6895     return true;
6896     FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COMPARE_AND_RETURN_NAME)
6897 #undef COMPARE_AND_RETURN_NAME
6898 #define COMPARE_AND_RETURN_NAME(name)                                          \
6899   case FIRST_CODE_AGE_SUB_TYPE + Code::k##name##CodeAge - Code::kFirstCodeAge: \
6900     *object_type = "CODE_TYPE";                                                \
6901     *object_sub_type = "CODE_AGE/" #name;                                      \
6902     return true;
6903     CODE_AGE_LIST_COMPLETE(COMPARE_AND_RETURN_NAME)
6904 #undef COMPARE_AND_RETURN_NAME
6905   }
6906   return false;
6907 }
6908 }  // namespace internal
6909 }  // namespace v8