v8: Upgrade to 3.11.10.14
[platform/upstream/nodejs.git] / deps / v8 / src / heap.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "v8.h"
29
30 #include "accessors.h"
31 #include "api.h"
32 #include "bootstrapper.h"
33 #include "codegen.h"
34 #include "compilation-cache.h"
35 #include "debug.h"
36 #include "deoptimizer.h"
37 #include "global-handles.h"
38 #include "heap-profiler.h"
39 #include "incremental-marking.h"
40 #include "liveobjectlist-inl.h"
41 #include "mark-compact.h"
42 #include "natives.h"
43 #include "objects-visiting.h"
44 #include "objects-visiting-inl.h"
45 #include "once.h"
46 #include "runtime-profiler.h"
47 #include "scopeinfo.h"
48 #include "snapshot.h"
49 #include "store-buffer.h"
50 #include "v8threads.h"
51 #include "vm-state-inl.h"
52 #if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
53 #include "regexp-macro-assembler.h"
54 #include "arm/regexp-macro-assembler-arm.h"
55 #endif
56 #if V8_TARGET_ARCH_MIPS && !V8_INTERPRETED_REGEXP
57 #include "regexp-macro-assembler.h"
58 #include "mips/regexp-macro-assembler-mips.h"
59 #endif
60
61 namespace v8 {
62 namespace internal {
63
64
65 Heap::Heap()
66     : isolate_(NULL),
67 // semispace_size_ should be a power of 2 and old_generation_size_ should be
68 // a multiple of Page::kPageSize.
69 #if defined(V8_TARGET_ARCH_X64)
70 #define LUMP_OF_MEMORY (2 * MB)
71       code_range_size_(512*MB),
72 #else
73 #define LUMP_OF_MEMORY MB
74       code_range_size_(0),
75 #endif
76 #if defined(ANDROID)
77       reserved_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
78       max_semispace_size_(4 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
79       initial_semispace_size_(Page::kPageSize),
80       max_old_generation_size_(192*MB),
81       max_executable_size_(max_old_generation_size_),
82 #else
83       reserved_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
84       max_semispace_size_(8 * Max(LUMP_OF_MEMORY, Page::kPageSize)),
85       initial_semispace_size_(Page::kPageSize),
86       max_old_generation_size_(700ul * LUMP_OF_MEMORY),
87       max_executable_size_(256l * LUMP_OF_MEMORY),
88 #endif
89
90 // Variables set based on semispace_size_ and old_generation_size_ in
91 // ConfigureHeap (survived_since_last_expansion_, external_allocation_limit_)
92 // Will be 4 * reserved_semispace_size_ to ensure that young
93 // generation can be aligned to its size.
94       survived_since_last_expansion_(0),
95       sweep_generation_(0),
96       always_allocate_scope_depth_(0),
97       linear_allocation_scope_depth_(0),
98       contexts_disposed_(0),
99       global_ic_age_(0),
100       scan_on_scavenge_pages_(0),
101       new_space_(this),
102       old_pointer_space_(NULL),
103       old_data_space_(NULL),
104       code_space_(NULL),
105       map_space_(NULL),
106       cell_space_(NULL),
107       lo_space_(NULL),
108       gc_state_(NOT_IN_GC),
109       gc_post_processing_depth_(0),
110       ms_count_(0),
111       gc_count_(0),
112       remembered_unmapped_pages_index_(0),
113       unflattened_strings_length_(0),
114 #ifdef DEBUG
115       allocation_allowed_(true),
116       allocation_timeout_(0),
117       disallow_allocation_failure_(false),
118       debug_utils_(NULL),
119 #endif  // DEBUG
120       new_space_high_promotion_mode_active_(false),
121       old_gen_promotion_limit_(kMinimumPromotionLimit),
122       old_gen_allocation_limit_(kMinimumAllocationLimit),
123       old_gen_limit_factor_(1),
124       size_of_old_gen_at_last_old_space_gc_(0),
125       external_allocation_limit_(0),
126       amount_of_external_allocated_memory_(0),
127       amount_of_external_allocated_memory_at_last_global_gc_(0),
128       old_gen_exhausted_(false),
129       store_buffer_rebuilder_(store_buffer()),
130       hidden_symbol_(NULL),
131       global_gc_prologue_callback_(NULL),
132       global_gc_epilogue_callback_(NULL),
133       gc_safe_size_of_old_object_(NULL),
134       total_regexp_code_generated_(0),
135       tracer_(NULL),
136       young_survivors_after_last_gc_(0),
137       high_survival_rate_period_length_(0),
138       survival_rate_(0),
139       previous_survival_rate_trend_(Heap::STABLE),
140       survival_rate_trend_(Heap::STABLE),
141       max_gc_pause_(0),
142       max_alive_after_gc_(0),
143       min_in_mutator_(kMaxInt),
144       alive_after_last_gc_(0),
145       last_gc_end_timestamp_(0.0),
146       store_buffer_(this),
147       marking_(this),
148       incremental_marking_(this),
149       number_idle_notifications_(0),
150       last_idle_notification_gc_count_(0),
151       last_idle_notification_gc_count_init_(false),
152       mark_sweeps_since_idle_round_started_(0),
153       ms_count_at_last_idle_notification_(0),
154       gc_count_at_last_idle_gc_(0),
155       scavenges_since_last_idle_round_(kIdleScavengeThreshold),
156       promotion_queue_(this),
157       configured_(false),
158       chunks_queued_for_free_(NULL) {
159   // Allow build-time customization of the max semispace size. Building
160   // V8 with snapshots and a non-default max semispace size is much
161   // easier if you can define it as part of the build environment.
162 #if defined(V8_MAX_SEMISPACE_SIZE)
163   max_semispace_size_ = reserved_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
164 #endif
165
166   intptr_t max_virtual = OS::MaxVirtualMemory();
167
168   if (max_virtual > 0) {
169     if (code_range_size_ > 0) {
170       // Reserve no more than 1/8 of the memory for the code range.
171       code_range_size_ = Min(code_range_size_, max_virtual >> 3);
172     }
173   }
174
175   memset(roots_, 0, sizeof(roots_[0]) * kRootListLength);
176   global_contexts_list_ = NULL;
177   mark_compact_collector_.heap_ = this;
178   external_string_table_.heap_ = this;
179   // Put a dummy entry in the remembered pages so we can find the list the
180   // minidump even if there are no real unmapped pages.
181   RememberUnmappedPage(NULL, false);
182 }
183
184
185 intptr_t Heap::Capacity() {
186   if (!HasBeenSetUp()) return 0;
187
188   return new_space_.Capacity() +
189       old_pointer_space_->Capacity() +
190       old_data_space_->Capacity() +
191       code_space_->Capacity() +
192       map_space_->Capacity() +
193       cell_space_->Capacity();
194 }
195
196
197 intptr_t Heap::CommittedMemory() {
198   if (!HasBeenSetUp()) return 0;
199
200   return new_space_.CommittedMemory() +
201       old_pointer_space_->CommittedMemory() +
202       old_data_space_->CommittedMemory() +
203       code_space_->CommittedMemory() +
204       map_space_->CommittedMemory() +
205       cell_space_->CommittedMemory() +
206       lo_space_->Size();
207 }
208
209 intptr_t Heap::CommittedMemoryExecutable() {
210   if (!HasBeenSetUp()) return 0;
211
212   return isolate()->memory_allocator()->SizeExecutable();
213 }
214
215
216 intptr_t Heap::Available() {
217   if (!HasBeenSetUp()) return 0;
218
219   return new_space_.Available() +
220       old_pointer_space_->Available() +
221       old_data_space_->Available() +
222       code_space_->Available() +
223       map_space_->Available() +
224       cell_space_->Available();
225 }
226
227
228 bool Heap::HasBeenSetUp() {
229   return old_pointer_space_ != NULL &&
230          old_data_space_ != NULL &&
231          code_space_ != NULL &&
232          map_space_ != NULL &&
233          cell_space_ != NULL &&
234          lo_space_ != NULL;
235 }
236
237
238 int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
239   if (IntrusiveMarking::IsMarked(object)) {
240     return IntrusiveMarking::SizeOfMarkedObject(object);
241   }
242   return object->SizeFromMap(object->map());
243 }
244
245
246 GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space,
247                                               const char** reason) {
248   // Is global GC requested?
249   if (space != NEW_SPACE) {
250     isolate_->counters()->gc_compactor_caused_by_request()->Increment();
251     *reason = "GC in old space requested";
252     return MARK_COMPACTOR;
253   }
254
255   if (FLAG_gc_global || (FLAG_stress_compaction && (gc_count_ & 1) != 0)) {
256     *reason = "GC in old space forced by flags";
257     return MARK_COMPACTOR;
258   }
259
260   // Is enough data promoted to justify a global GC?
261   if (OldGenerationPromotionLimitReached()) {
262     isolate_->counters()->gc_compactor_caused_by_promoted_data()->Increment();
263     *reason = "promotion limit reached";
264     return MARK_COMPACTOR;
265   }
266
267   // Have allocation in OLD and LO failed?
268   if (old_gen_exhausted_) {
269     isolate_->counters()->
270         gc_compactor_caused_by_oldspace_exhaustion()->Increment();
271     *reason = "old generations exhausted";
272     return MARK_COMPACTOR;
273   }
274
275   // Is there enough space left in OLD to guarantee that a scavenge can
276   // succeed?
277   //
278   // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
279   // for object promotion. It counts only the bytes that the memory
280   // allocator has not yet allocated from the OS and assigned to any space,
281   // and does not count available bytes already in the old space or code
282   // space.  Undercounting is safe---we may get an unrequested full GC when
283   // a scavenge would have succeeded.
284   if (isolate_->memory_allocator()->MaxAvailable() <= new_space_.Size()) {
285     isolate_->counters()->
286         gc_compactor_caused_by_oldspace_exhaustion()->Increment();
287     *reason = "scavenge might not succeed";
288     return MARK_COMPACTOR;
289   }
290
291   // Default
292   *reason = NULL;
293   return SCAVENGER;
294 }
295
296
297 // TODO(1238405): Combine the infrastructure for --heap-stats and
298 // --log-gc to avoid the complicated preprocessor and flag testing.
299 void Heap::ReportStatisticsBeforeGC() {
300   // Heap::ReportHeapStatistics will also log NewSpace statistics when
301   // compiled --log-gc is set.  The following logic is used to avoid
302   // double logging.
303 #ifdef DEBUG
304   if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
305   if (FLAG_heap_stats) {
306     ReportHeapStatistics("Before GC");
307   } else if (FLAG_log_gc) {
308     new_space_.ReportStatistics();
309   }
310   if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
311 #else
312   if (FLAG_log_gc) {
313     new_space_.CollectStatistics();
314     new_space_.ReportStatistics();
315     new_space_.ClearHistograms();
316   }
317 #endif  // DEBUG
318 }
319
320
321 void Heap::PrintShortHeapStatistics() {
322   if (!FLAG_trace_gc_verbose) return;
323   PrintF("Memory allocator,   used: %8" V8_PTR_PREFIX "d"
324              ", available: %8" V8_PTR_PREFIX "d\n",
325          isolate_->memory_allocator()->Size(),
326          isolate_->memory_allocator()->Available());
327   PrintF("New space,          used: %8" V8_PTR_PREFIX "d"
328              ", available: %8" V8_PTR_PREFIX "d\n",
329          Heap::new_space_.Size(),
330          new_space_.Available());
331   PrintF("Old pointers,       used: %8" V8_PTR_PREFIX "d"
332              ", available: %8" V8_PTR_PREFIX "d"
333              ", waste: %8" V8_PTR_PREFIX "d\n",
334          old_pointer_space_->Size(),
335          old_pointer_space_->Available(),
336          old_pointer_space_->Waste());
337   PrintF("Old data space,     used: %8" V8_PTR_PREFIX "d"
338              ", available: %8" V8_PTR_PREFIX "d"
339              ", waste: %8" V8_PTR_PREFIX "d\n",
340          old_data_space_->Size(),
341          old_data_space_->Available(),
342          old_data_space_->Waste());
343   PrintF("Code space,         used: %8" V8_PTR_PREFIX "d"
344              ", available: %8" V8_PTR_PREFIX "d"
345              ", waste: %8" V8_PTR_PREFIX "d\n",
346          code_space_->Size(),
347          code_space_->Available(),
348          code_space_->Waste());
349   PrintF("Map space,          used: %8" V8_PTR_PREFIX "d"
350              ", available: %8" V8_PTR_PREFIX "d"
351              ", waste: %8" V8_PTR_PREFIX "d\n",
352          map_space_->Size(),
353          map_space_->Available(),
354          map_space_->Waste());
355   PrintF("Cell space,         used: %8" V8_PTR_PREFIX "d"
356              ", available: %8" V8_PTR_PREFIX "d"
357              ", waste: %8" V8_PTR_PREFIX "d\n",
358          cell_space_->Size(),
359          cell_space_->Available(),
360          cell_space_->Waste());
361   PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
362              ", available: %8" V8_PTR_PREFIX "d\n",
363          lo_space_->Size(),
364          lo_space_->Available());
365 }
366
367
368 // TODO(1238405): Combine the infrastructure for --heap-stats and
369 // --log-gc to avoid the complicated preprocessor and flag testing.
370 void Heap::ReportStatisticsAfterGC() {
371   // Similar to the before GC, we use some complicated logic to ensure that
372   // NewSpace statistics are logged exactly once when --log-gc is turned on.
373 #if defined(DEBUG)
374   if (FLAG_heap_stats) {
375     new_space_.CollectStatistics();
376     ReportHeapStatistics("After GC");
377   } else if (FLAG_log_gc) {
378     new_space_.ReportStatistics();
379   }
380 #else
381   if (FLAG_log_gc) new_space_.ReportStatistics();
382 #endif  // DEBUG
383 }
384
385
386 void Heap::GarbageCollectionPrologue() {
387   isolate_->transcendental_cache()->Clear();
388   ClearJSFunctionResultCaches();
389   gc_count_++;
390   unflattened_strings_length_ = 0;
391 #ifdef DEBUG
392   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
393   allow_allocation(false);
394
395   if (FLAG_verify_heap) {
396     Verify();
397   }
398
399   if (FLAG_gc_verbose) Print();
400 #endif  // DEBUG
401
402 #if defined(DEBUG)
403   ReportStatisticsBeforeGC();
404 #endif  // DEBUG
405
406   LiveObjectList::GCPrologue();
407   store_buffer()->GCPrologue();
408 }
409
410 intptr_t Heap::SizeOfObjects() {
411   intptr_t total = 0;
412   AllSpaces spaces;
413   for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
414     total += space->SizeOfObjects();
415   }
416   return total;
417 }
418
419 void Heap::GarbageCollectionEpilogue() {
420   store_buffer()->GCEpilogue();
421   LiveObjectList::GCEpilogue();
422 #ifdef DEBUG
423   allow_allocation(true);
424   ZapFromSpace();
425
426   if (FLAG_verify_heap) {
427     Verify();
428   }
429
430   if (FLAG_print_global_handles) isolate_->global_handles()->Print();
431   if (FLAG_print_handles) PrintHandles();
432   if (FLAG_gc_verbose) Print();
433   if (FLAG_code_stats) ReportCodeStatistics("After GC");
434 #endif
435
436   isolate_->counters()->alive_after_last_gc()->Set(
437       static_cast<int>(SizeOfObjects()));
438
439   isolate_->counters()->symbol_table_capacity()->Set(
440       symbol_table()->Capacity());
441   isolate_->counters()->number_of_symbols()->Set(
442       symbol_table()->NumberOfElements());
443 #if defined(DEBUG)
444   ReportStatisticsAfterGC();
445 #endif  // DEBUG
446 #ifdef ENABLE_DEBUGGER_SUPPORT
447   isolate_->debug()->AfterGarbageCollection();
448 #endif  // ENABLE_DEBUGGER_SUPPORT
449 }
450
451
452 void Heap::CollectAllGarbage(int flags, const char* gc_reason) {
453   // Since we are ignoring the return value, the exact choice of space does
454   // not matter, so long as we do not specify NEW_SPACE, which would not
455   // cause a full GC.
456   mark_compact_collector_.SetFlags(flags);
457   CollectGarbage(OLD_POINTER_SPACE, gc_reason);
458   mark_compact_collector_.SetFlags(kNoGCFlags);
459 }
460
461
462 void Heap::CollectAllAvailableGarbage(const char* gc_reason) {
463   // Since we are ignoring the return value, the exact choice of space does
464   // not matter, so long as we do not specify NEW_SPACE, which would not
465   // cause a full GC.
466   // Major GC would invoke weak handle callbacks on weakly reachable
467   // handles, but won't collect weakly reachable objects until next
468   // major GC.  Therefore if we collect aggressively and weak handle callback
469   // has been invoked, we rerun major GC to release objects which become
470   // garbage.
471   // Note: as weak callbacks can execute arbitrary code, we cannot
472   // hope that eventually there will be no weak callbacks invocations.
473   // Therefore stop recollecting after several attempts.
474   mark_compact_collector()->SetFlags(kMakeHeapIterableMask |
475                                      kReduceMemoryFootprintMask);
476   isolate_->compilation_cache()->Clear();
477   const int kMaxNumberOfAttempts = 7;
478   for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
479     if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR, gc_reason, NULL)) {
480       break;
481     }
482   }
483   mark_compact_collector()->SetFlags(kNoGCFlags);
484   new_space_.Shrink();
485   UncommitFromSpace();
486   Shrink();
487   incremental_marking()->UncommitMarkingDeque();
488 }
489
490
491 bool Heap::CollectGarbage(AllocationSpace space,
492                           GarbageCollector collector,
493                           const char* gc_reason,
494                           const char* collector_reason) {
495   // The VM is in the GC state until exiting this function.
496   VMState state(isolate_, GC);
497
498 #ifdef DEBUG
499   // Reset the allocation timeout to the GC interval, but make sure to
500   // allow at least a few allocations after a collection. The reason
501   // for this is that we have a lot of allocation sequences and we
502   // assume that a garbage collection will allow the subsequent
503   // allocation attempts to go through.
504   allocation_timeout_ = Max(6, FLAG_gc_interval);
505 #endif
506
507   if (collector == SCAVENGER && !incremental_marking()->IsStopped()) {
508     if (FLAG_trace_incremental_marking) {
509       PrintF("[IncrementalMarking] Scavenge during marking.\n");
510     }
511   }
512
513   if (collector == MARK_COMPACTOR &&
514       !mark_compact_collector()->abort_incremental_marking_ &&
515       !incremental_marking()->IsStopped() &&
516       !incremental_marking()->should_hurry() &&
517       FLAG_incremental_marking_steps) {
518     // Make progress in incremental marking.
519     const intptr_t kStepSizeWhenDelayedByScavenge = 1 * MB;
520     incremental_marking()->Step(kStepSizeWhenDelayedByScavenge,
521                                 IncrementalMarking::NO_GC_VIA_STACK_GUARD);
522     if (!incremental_marking()->IsComplete()) {
523       if (FLAG_trace_incremental_marking) {
524         PrintF("[IncrementalMarking] Delaying MarkSweep.\n");
525       }
526       collector = SCAVENGER;
527       collector_reason = "incremental marking delaying mark-sweep";
528     }
529   }
530
531   bool next_gc_likely_to_collect_more = false;
532
533   { GCTracer tracer(this, gc_reason, collector_reason);
534     GarbageCollectionPrologue();
535     // The GC count was incremented in the prologue.  Tell the tracer about
536     // it.
537     tracer.set_gc_count(gc_count_);
538
539     // Tell the tracer which collector we've selected.
540     tracer.set_collector(collector);
541
542     HistogramTimer* rate = (collector == SCAVENGER)
543         ? isolate_->counters()->gc_scavenger()
544         : isolate_->counters()->gc_compactor();
545     rate->Start();
546     next_gc_likely_to_collect_more =
547         PerformGarbageCollection(collector, &tracer);
548     rate->Stop();
549
550     GarbageCollectionEpilogue();
551   }
552
553   ASSERT(collector == SCAVENGER || incremental_marking()->IsStopped());
554   if (incremental_marking()->IsStopped()) {
555     if (incremental_marking()->WorthActivating() && NextGCIsLikelyToBeFull()) {
556       incremental_marking()->Start();
557     }
558   }
559
560   return next_gc_likely_to_collect_more;
561 }
562
563
564 void Heap::PerformScavenge() {
565   GCTracer tracer(this, NULL, NULL);
566   if (incremental_marking()->IsStopped()) {
567     PerformGarbageCollection(SCAVENGER, &tracer);
568   } else {
569     PerformGarbageCollection(MARK_COMPACTOR, &tracer);
570   }
571 }
572
573
574 #ifdef DEBUG
575 // Helper class for verifying the symbol table.
576 class SymbolTableVerifier : public ObjectVisitor {
577  public:
578   void VisitPointers(Object** start, Object** end) {
579     // Visit all HeapObject pointers in [start, end).
580     for (Object** p = start; p < end; p++) {
581       if ((*p)->IsHeapObject()) {
582         // Check that the symbol is actually a symbol.
583         ASSERT((*p)->IsTheHole() || (*p)->IsUndefined() || (*p)->IsSymbol());
584       }
585     }
586   }
587 };
588 #endif  // DEBUG
589
590
591 static void VerifySymbolTable() {
592 #ifdef DEBUG
593   SymbolTableVerifier verifier;
594   HEAP->symbol_table()->IterateElements(&verifier);
595 #endif  // DEBUG
596 }
597
598
599 static bool AbortIncrementalMarkingAndCollectGarbage(
600     Heap* heap,
601     AllocationSpace space,
602     const char* gc_reason = NULL) {
603   heap->mark_compact_collector()->SetFlags(Heap::kAbortIncrementalMarkingMask);
604   bool result = heap->CollectGarbage(space, gc_reason);
605   heap->mark_compact_collector()->SetFlags(Heap::kNoGCFlags);
606   return result;
607 }
608
609
610 void Heap::ReserveSpace(
611     int new_space_size,
612     int pointer_space_size,
613     int data_space_size,
614     int code_space_size,
615     int map_space_size,
616     int cell_space_size,
617     int large_object_size) {
618   NewSpace* new_space = Heap::new_space();
619   PagedSpace* old_pointer_space = Heap::old_pointer_space();
620   PagedSpace* old_data_space = Heap::old_data_space();
621   PagedSpace* code_space = Heap::code_space();
622   PagedSpace* map_space = Heap::map_space();
623   PagedSpace* cell_space = Heap::cell_space();
624   LargeObjectSpace* lo_space = Heap::lo_space();
625   bool gc_performed = true;
626   int counter = 0;
627   static const int kThreshold = 20;
628   while (gc_performed && counter++ < kThreshold) {
629     gc_performed = false;
630     if (!new_space->ReserveSpace(new_space_size)) {
631       Heap::CollectGarbage(NEW_SPACE,
632                            "failed to reserve space in the new space");
633       gc_performed = true;
634     }
635     if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
636       AbortIncrementalMarkingAndCollectGarbage(this, OLD_POINTER_SPACE,
637           "failed to reserve space in the old pointer space");
638       gc_performed = true;
639     }
640     if (!(old_data_space->ReserveSpace(data_space_size))) {
641       AbortIncrementalMarkingAndCollectGarbage(this, OLD_DATA_SPACE,
642           "failed to reserve space in the old data space");
643       gc_performed = true;
644     }
645     if (!(code_space->ReserveSpace(code_space_size))) {
646       AbortIncrementalMarkingAndCollectGarbage(this, CODE_SPACE,
647           "failed to reserve space in the code space");
648       gc_performed = true;
649     }
650     if (!(map_space->ReserveSpace(map_space_size))) {
651       AbortIncrementalMarkingAndCollectGarbage(this, MAP_SPACE,
652           "failed to reserve space in the map space");
653       gc_performed = true;
654     }
655     if (!(cell_space->ReserveSpace(cell_space_size))) {
656       AbortIncrementalMarkingAndCollectGarbage(this, CELL_SPACE,
657           "failed to reserve space in the cell space");
658       gc_performed = true;
659     }
660     // We add a slack-factor of 2 in order to have space for a series of
661     // large-object allocations that are only just larger than the page size.
662     large_object_size *= 2;
663     // The ReserveSpace method on the large object space checks how much
664     // we can expand the old generation.  This includes expansion caused by
665     // allocation in the other spaces.
666     large_object_size += cell_space_size + map_space_size + code_space_size +
667         data_space_size + pointer_space_size;
668     if (!(lo_space->ReserveSpace(large_object_size))) {
669       AbortIncrementalMarkingAndCollectGarbage(this, LO_SPACE,
670           "failed to reserve space in the large object space");
671       gc_performed = true;
672     }
673   }
674
675   if (gc_performed) {
676     // Failed to reserve the space after several attempts.
677     V8::FatalProcessOutOfMemory("Heap::ReserveSpace");
678   }
679 }
680
681
682 void Heap::EnsureFromSpaceIsCommitted() {
683   if (new_space_.CommitFromSpaceIfNeeded()) return;
684
685   // Committing memory to from space failed.
686   // Try shrinking and try again.
687   Shrink();
688   if (new_space_.CommitFromSpaceIfNeeded()) return;
689
690   // Committing memory to from space failed again.
691   // Memory is exhausted and we will die.
692   V8::FatalProcessOutOfMemory("Committing semi space failed.");
693 }
694
695
696 void Heap::ClearJSFunctionResultCaches() {
697   if (isolate_->bootstrapper()->IsActive()) return;
698
699   Object* context = global_contexts_list_;
700   while (!context->IsUndefined()) {
701     // Get the caches for this context. GC can happen when the context
702     // is not fully initialized, so the caches can be undefined.
703     Object* caches_or_undefined =
704         Context::cast(context)->get(Context::JSFUNCTION_RESULT_CACHES_INDEX);
705     if (!caches_or_undefined->IsUndefined()) {
706       FixedArray* caches = FixedArray::cast(caches_or_undefined);
707       // Clear the caches:
708       int length = caches->length();
709       for (int i = 0; i < length; i++) {
710         JSFunctionResultCache::cast(caches->get(i))->Clear();
711       }
712     }
713     // Get the next context:
714     context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
715   }
716 }
717
718
719
720 void Heap::ClearNormalizedMapCaches() {
721   if (isolate_->bootstrapper()->IsActive() &&
722       !incremental_marking()->IsMarking()) {
723     return;
724   }
725
726   Object* context = global_contexts_list_;
727   while (!context->IsUndefined()) {
728     // GC can happen when the context is not fully initialized,
729     // so the cache can be undefined.
730     Object* cache =
731         Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX);
732     if (!cache->IsUndefined()) {
733       NormalizedMapCache::cast(cache)->Clear();
734     }
735     context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
736   }
737 }
738
739
740 void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
741   double survival_rate =
742       (static_cast<double>(young_survivors_after_last_gc_) * 100) /
743       start_new_space_size;
744
745   if (survival_rate > kYoungSurvivalRateHighThreshold) {
746     high_survival_rate_period_length_++;
747   } else {
748     high_survival_rate_period_length_ = 0;
749   }
750
751   if (survival_rate < kYoungSurvivalRateLowThreshold) {
752     low_survival_rate_period_length_++;
753   } else {
754     low_survival_rate_period_length_ = 0;
755   }
756
757   double survival_rate_diff = survival_rate_ - survival_rate;
758
759   if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
760     set_survival_rate_trend(DECREASING);
761   } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
762     set_survival_rate_trend(INCREASING);
763   } else {
764     set_survival_rate_trend(STABLE);
765   }
766
767   survival_rate_ = survival_rate;
768 }
769
770 bool Heap::PerformGarbageCollection(GarbageCollector collector,
771                                     GCTracer* tracer) {
772   bool next_gc_likely_to_collect_more = false;
773
774   if (collector != SCAVENGER) {
775     PROFILE(isolate_, CodeMovingGCEvent());
776   }
777
778   if (FLAG_verify_heap) {
779     VerifySymbolTable();
780   }
781   if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
782     ASSERT(!allocation_allowed_);
783     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
784     global_gc_prologue_callback_();
785   }
786
787   GCType gc_type =
788       collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
789
790   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
791     if (gc_type & gc_prologue_callbacks_[i].gc_type) {
792       gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
793     }
794   }
795
796   EnsureFromSpaceIsCommitted();
797
798   int start_new_space_size = Heap::new_space()->SizeAsInt();
799
800   if (IsHighSurvivalRate()) {
801     // We speed up the incremental marker if it is running so that it
802     // does not fall behind the rate of promotion, which would cause a
803     // constantly growing old space.
804     incremental_marking()->NotifyOfHighPromotionRate();
805   }
806
807   if (collector == MARK_COMPACTOR) {
808     // Perform mark-sweep with optional compaction.
809     MarkCompact(tracer);
810     sweep_generation_++;
811     bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
812         IsStableOrIncreasingSurvivalTrend();
813
814     UpdateSurvivalRateTrend(start_new_space_size);
815
816     size_of_old_gen_at_last_old_space_gc_ = PromotedSpaceSizeOfObjects();
817
818     if (high_survival_rate_during_scavenges &&
819         IsStableOrIncreasingSurvivalTrend()) {
820       // Stable high survival rates of young objects both during partial and
821       // full collection indicate that mutator is either building or modifying
822       // a structure with a long lifetime.
823       // In this case we aggressively raise old generation memory limits to
824       // postpone subsequent mark-sweep collection and thus trade memory
825       // space for the mutation speed.
826       old_gen_limit_factor_ = 2;
827     } else {
828       old_gen_limit_factor_ = 1;
829     }
830
831     old_gen_promotion_limit_ =
832         OldGenPromotionLimit(size_of_old_gen_at_last_old_space_gc_);
833     old_gen_allocation_limit_ =
834         OldGenAllocationLimit(size_of_old_gen_at_last_old_space_gc_);
835
836     old_gen_exhausted_ = false;
837   } else {
838     tracer_ = tracer;
839     Scavenge();
840     tracer_ = NULL;
841
842     UpdateSurvivalRateTrend(start_new_space_size);
843   }
844
845   if (!new_space_high_promotion_mode_active_ &&
846       new_space_.Capacity() == new_space_.MaximumCapacity() &&
847       IsStableOrIncreasingSurvivalTrend() &&
848       IsHighSurvivalRate()) {
849     // Stable high survival rates even though young generation is at
850     // maximum capacity indicates that most objects will be promoted.
851     // To decrease scavenger pauses and final mark-sweep pauses, we
852     // have to limit maximal capacity of the young generation.
853     new_space_high_promotion_mode_active_ = true;
854     if (FLAG_trace_gc) {
855       PrintF("Limited new space size due to high promotion rate: %d MB\n",
856              new_space_.InitialCapacity() / MB);
857     }
858   } else if (new_space_high_promotion_mode_active_ &&
859       IsStableOrDecreasingSurvivalTrend() &&
860       IsLowSurvivalRate()) {
861     // Decreasing low survival rates might indicate that the above high
862     // promotion mode is over and we should allow the young generation
863     // to grow again.
864     new_space_high_promotion_mode_active_ = false;
865     if (FLAG_trace_gc) {
866       PrintF("Unlimited new space size due to low promotion rate: %d MB\n",
867              new_space_.MaximumCapacity() / MB);
868     }
869   }
870
871   if (new_space_high_promotion_mode_active_ &&
872       new_space_.Capacity() > new_space_.InitialCapacity()) {
873     new_space_.Shrink();
874   }
875
876   isolate_->counters()->objs_since_last_young()->Set(0);
877
878   gc_post_processing_depth_++;
879   { DisableAssertNoAllocation allow_allocation;
880     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
881     next_gc_likely_to_collect_more =
882         isolate_->global_handles()->PostGarbageCollectionProcessing(collector);
883   }
884   gc_post_processing_depth_--;
885
886   // Update relocatables.
887   Relocatable::PostGarbageCollectionProcessing();
888
889   if (collector == MARK_COMPACTOR) {
890     // Register the amount of external allocated memory.
891     amount_of_external_allocated_memory_at_last_global_gc_ =
892         amount_of_external_allocated_memory_;
893   }
894
895   GCCallbackFlags callback_flags = kNoGCCallbackFlags;
896   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
897     if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
898       gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
899     }
900   }
901
902   if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
903     ASSERT(!allocation_allowed_);
904     GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
905     global_gc_epilogue_callback_();
906   }
907   if (FLAG_verify_heap) {
908     VerifySymbolTable();
909   }
910
911   return next_gc_likely_to_collect_more;
912 }
913
914
915 void Heap::MarkCompact(GCTracer* tracer) {
916   gc_state_ = MARK_COMPACT;
917   LOG(isolate_, ResourceEvent("markcompact", "begin"));
918
919   mark_compact_collector_.Prepare(tracer);
920
921   ms_count_++;
922   tracer->set_full_gc_count(ms_count_);
923
924   MarkCompactPrologue();
925
926   mark_compact_collector_.CollectGarbage();
927
928   LOG(isolate_, ResourceEvent("markcompact", "end"));
929
930   gc_state_ = NOT_IN_GC;
931
932   isolate_->counters()->objs_since_last_full()->Set(0);
933
934   contexts_disposed_ = 0;
935
936   isolate_->set_context_exit_happened(false);
937 }
938
939
940 void Heap::MarkCompactPrologue() {
941   // At any old GC clear the keyed lookup cache to enable collection of unused
942   // maps.
943   isolate_->keyed_lookup_cache()->Clear();
944   isolate_->context_slot_cache()->Clear();
945   isolate_->descriptor_lookup_cache()->Clear();
946   StringSplitCache::Clear(string_split_cache());
947
948   isolate_->compilation_cache()->MarkCompactPrologue();
949
950   CompletelyClearInstanceofCache();
951
952   FlushNumberStringCache();
953   if (FLAG_cleanup_code_caches_at_gc) {
954     polymorphic_code_cache()->set_cache(undefined_value());
955   }
956
957   ClearNormalizedMapCaches();
958 }
959
960
961 Object* Heap::FindCodeObject(Address a) {
962   return isolate()->inner_pointer_to_code_cache()->
963       GcSafeFindCodeForInnerPointer(a);
964 }
965
966
967 // Helper class for copying HeapObjects
968 class ScavengeVisitor: public ObjectVisitor {
969  public:
970   explicit ScavengeVisitor(Heap* heap) : heap_(heap) {}
971
972   void VisitPointer(Object** p) { ScavengePointer(p); }
973
974   void VisitPointers(Object** start, Object** end) {
975     // Copy all HeapObject pointers in [start, end)
976     for (Object** p = start; p < end; p++) ScavengePointer(p);
977   }
978
979  private:
980   void ScavengePointer(Object** p) {
981     Object* object = *p;
982     if (!heap_->InNewSpace(object)) return;
983     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
984                          reinterpret_cast<HeapObject*>(object));
985   }
986
987   Heap* heap_;
988 };
989
990
991 #ifdef DEBUG
992 // Visitor class to verify pointers in code or data space do not point into
993 // new space.
994 class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
995  public:
996   void VisitPointers(Object** start, Object**end) {
997     for (Object** current = start; current < end; current++) {
998       if ((*current)->IsHeapObject()) {
999         ASSERT(!HEAP->InNewSpace(HeapObject::cast(*current)));
1000       }
1001     }
1002   }
1003 };
1004
1005
1006 static void VerifyNonPointerSpacePointers() {
1007   // Verify that there are no pointers to new space in spaces where we
1008   // do not expect them.
1009   VerifyNonPointerSpacePointersVisitor v;
1010   HeapObjectIterator code_it(HEAP->code_space());
1011   for (HeapObject* object = code_it.Next();
1012        object != NULL; object = code_it.Next())
1013     object->Iterate(&v);
1014
1015   // The old data space was normally swept conservatively so that the iterator
1016   // doesn't work, so we normally skip the next bit.
1017   if (!HEAP->old_data_space()->was_swept_conservatively()) {
1018     HeapObjectIterator data_it(HEAP->old_data_space());
1019     for (HeapObject* object = data_it.Next();
1020          object != NULL; object = data_it.Next())
1021       object->Iterate(&v);
1022   }
1023 }
1024 #endif
1025
1026
1027 void Heap::CheckNewSpaceExpansionCriteria() {
1028   if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
1029       survived_since_last_expansion_ > new_space_.Capacity() &&
1030       !new_space_high_promotion_mode_active_) {
1031     // Grow the size of new space if there is room to grow, enough data
1032     // has survived scavenge since the last expansion and we are not in
1033     // high promotion mode.
1034     new_space_.Grow();
1035     survived_since_last_expansion_ = 0;
1036   }
1037 }
1038
1039
1040 static bool IsUnscavengedHeapObject(Heap* heap, Object** p) {
1041   return heap->InNewSpace(*p) &&
1042       !HeapObject::cast(*p)->map_word().IsForwardingAddress();
1043 }
1044
1045
1046 void Heap::ScavengeStoreBufferCallback(
1047     Heap* heap,
1048     MemoryChunk* page,
1049     StoreBufferEvent event) {
1050   heap->store_buffer_rebuilder_.Callback(page, event);
1051 }
1052
1053
1054 void StoreBufferRebuilder::Callback(MemoryChunk* page, StoreBufferEvent event) {
1055   if (event == kStoreBufferStartScanningPagesEvent) {
1056     start_of_current_page_ = NULL;
1057     current_page_ = NULL;
1058   } else if (event == kStoreBufferScanningPageEvent) {
1059     if (current_page_ != NULL) {
1060       // If this page already overflowed the store buffer during this iteration.
1061       if (current_page_->scan_on_scavenge()) {
1062         // Then we should wipe out the entries that have been added for it.
1063         store_buffer_->SetTop(start_of_current_page_);
1064       } else if (store_buffer_->Top() - start_of_current_page_ >=
1065                  (store_buffer_->Limit() - store_buffer_->Top()) >> 2) {
1066         // Did we find too many pointers in the previous page?  The heuristic is
1067         // that no page can take more then 1/5 the remaining slots in the store
1068         // buffer.
1069         current_page_->set_scan_on_scavenge(true);
1070         store_buffer_->SetTop(start_of_current_page_);
1071       } else {
1072         // In this case the page we scanned took a reasonable number of slots in
1073         // the store buffer.  It has now been rehabilitated and is no longer
1074         // marked scan_on_scavenge.
1075         ASSERT(!current_page_->scan_on_scavenge());
1076       }
1077     }
1078     start_of_current_page_ = store_buffer_->Top();
1079     current_page_ = page;
1080   } else if (event == kStoreBufferFullEvent) {
1081     // The current page overflowed the store buffer again.  Wipe out its entries
1082     // in the store buffer and mark it scan-on-scavenge again.  This may happen
1083     // several times while scanning.
1084     if (current_page_ == NULL) {
1085       // Store Buffer overflowed while scanning promoted objects.  These are not
1086       // in any particular page, though they are likely to be clustered by the
1087       // allocation routines.
1088       store_buffer_->EnsureSpace(StoreBuffer::kStoreBufferSize);
1089     } else {
1090       // Store Buffer overflowed while scanning a particular old space page for
1091       // pointers to new space.
1092       ASSERT(current_page_ == page);
1093       ASSERT(page != NULL);
1094       current_page_->set_scan_on_scavenge(true);
1095       ASSERT(start_of_current_page_ != store_buffer_->Top());
1096       store_buffer_->SetTop(start_of_current_page_);
1097     }
1098   } else {
1099     UNREACHABLE();
1100   }
1101 }
1102
1103
1104 void PromotionQueue::Initialize() {
1105   // Assumes that a NewSpacePage exactly fits a number of promotion queue
1106   // entries (where each is a pair of intptr_t). This allows us to simplify
1107   // the test fpr when to switch pages.
1108   ASSERT((Page::kPageSize - MemoryChunk::kBodyOffset) % (2 * kPointerSize)
1109          == 0);
1110   limit_ = reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceStart());
1111   front_ = rear_ =
1112       reinterpret_cast<intptr_t*>(heap_->new_space()->ToSpaceEnd());
1113   emergency_stack_ = NULL;
1114   guard_ = false;
1115 }
1116
1117
1118 void PromotionQueue::RelocateQueueHead() {
1119   ASSERT(emergency_stack_ == NULL);
1120
1121   Page* p = Page::FromAllocationTop(reinterpret_cast<Address>(rear_));
1122   intptr_t* head_start = rear_;
1123   intptr_t* head_end =
1124       Min(front_, reinterpret_cast<intptr_t*>(p->area_end()));
1125
1126   int entries_count =
1127       static_cast<int>(head_end - head_start) / kEntrySizeInWords;
1128
1129   emergency_stack_ = new List<Entry>(2 * entries_count);
1130
1131   while (head_start != head_end) {
1132     int size = static_cast<int>(*(head_start++));
1133     HeapObject* obj = reinterpret_cast<HeapObject*>(*(head_start++));
1134     emergency_stack_->Add(Entry(obj, size));
1135   }
1136   rear_ = head_end;
1137 }
1138
1139
1140 class ScavengeWeakObjectRetainer : public WeakObjectRetainer {
1141  public:
1142   explicit ScavengeWeakObjectRetainer(Heap* heap) : heap_(heap) { }
1143
1144   virtual Object* RetainAs(Object* object) {
1145     if (!heap_->InFromSpace(object)) {
1146       return object;
1147     }
1148
1149     MapWord map_word = HeapObject::cast(object)->map_word();
1150     if (map_word.IsForwardingAddress()) {
1151       return map_word.ToForwardingAddress();
1152     }
1153     return NULL;
1154   }
1155
1156  private:
1157   Heap* heap_;
1158 };
1159
1160
1161 void Heap::Scavenge() {
1162 #ifdef DEBUG
1163   if (FLAG_verify_heap) VerifyNonPointerSpacePointers();
1164 #endif
1165
1166   gc_state_ = SCAVENGE;
1167
1168   // Implements Cheney's copying algorithm
1169   LOG(isolate_, ResourceEvent("scavenge", "begin"));
1170
1171   // Clear descriptor cache.
1172   isolate_->descriptor_lookup_cache()->Clear();
1173
1174   // Used for updating survived_since_last_expansion_ at function end.
1175   intptr_t survived_watermark = PromotedSpaceSizeOfObjects();
1176
1177   CheckNewSpaceExpansionCriteria();
1178
1179   SelectScavengingVisitorsTable();
1180
1181   incremental_marking()->PrepareForScavenge();
1182
1183   AdvanceSweepers(static_cast<int>(new_space_.Size()));
1184
1185   // Flip the semispaces.  After flipping, to space is empty, from space has
1186   // live objects.
1187   new_space_.Flip();
1188   new_space_.ResetAllocationInfo();
1189
1190   // We need to sweep newly copied objects which can be either in the
1191   // to space or promoted to the old generation.  For to-space
1192   // objects, we treat the bottom of the to space as a queue.  Newly
1193   // copied and unswept objects lie between a 'front' mark and the
1194   // allocation pointer.
1195   //
1196   // Promoted objects can go into various old-generation spaces, and
1197   // can be allocated internally in the spaces (from the free list).
1198   // We treat the top of the to space as a queue of addresses of
1199   // promoted objects.  The addresses of newly promoted and unswept
1200   // objects lie between a 'front' mark and a 'rear' mark that is
1201   // updated as a side effect of promoting an object.
1202   //
1203   // There is guaranteed to be enough room at the top of the to space
1204   // for the addresses of promoted objects: every object promoted
1205   // frees up its size in bytes from the top of the new space, and
1206   // objects are at least one pointer in size.
1207   Address new_space_front = new_space_.ToSpaceStart();
1208   promotion_queue_.Initialize();
1209
1210 #ifdef DEBUG
1211   store_buffer()->Clean();
1212 #endif
1213
1214   ScavengeVisitor scavenge_visitor(this);
1215   // Copy roots.
1216   IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
1217
1218   // Copy objects reachable from the old generation.
1219   {
1220     StoreBufferRebuildScope scope(this,
1221                                   store_buffer(),
1222                                   &ScavengeStoreBufferCallback);
1223     store_buffer()->IteratePointersToNewSpace(&ScavengeObject);
1224   }
1225
1226   // Copy objects reachable from cells by scavenging cell values directly.
1227   HeapObjectIterator cell_iterator(cell_space_);
1228   for (HeapObject* cell = cell_iterator.Next();
1229        cell != NULL; cell = cell_iterator.Next()) {
1230     if (cell->IsJSGlobalPropertyCell()) {
1231       Address value_address =
1232           reinterpret_cast<Address>(cell) +
1233           (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1234       scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1235     }
1236   }
1237
1238   // Scavenge object reachable from the global contexts list directly.
1239   scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1240
1241   new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1242   isolate_->global_handles()->IdentifyNewSpaceWeakIndependentHandles(
1243       &IsUnscavengedHeapObject);
1244   isolate_->global_handles()->IterateNewSpaceWeakIndependentRoots(
1245       &scavenge_visitor);
1246   new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1247
1248   UpdateNewSpaceReferencesInExternalStringTable(
1249       &UpdateNewSpaceReferenceInExternalStringTableEntry);
1250
1251   promotion_queue_.Destroy();
1252
1253   LiveObjectList::UpdateReferencesForScavengeGC();
1254   if (!FLAG_watch_ic_patching) {
1255     isolate()->runtime_profiler()->UpdateSamplesAfterScavenge();
1256   }
1257   incremental_marking()->UpdateMarkingDequeAfterScavenge();
1258
1259   ScavengeWeakObjectRetainer weak_object_retainer(this);
1260   ProcessWeakReferences(&weak_object_retainer);
1261
1262   ASSERT(new_space_front == new_space_.top());
1263
1264   // Set age mark.
1265   new_space_.set_age_mark(new_space_.top());
1266
1267   new_space_.LowerInlineAllocationLimit(
1268       new_space_.inline_allocation_limit_step());
1269
1270   // Update how much has survived scavenge.
1271   IncrementYoungSurvivorsCounter(static_cast<int>(
1272       (PromotedSpaceSizeOfObjects() - survived_watermark) + new_space_.Size()));
1273
1274   LOG(isolate_, ResourceEvent("scavenge", "end"));
1275
1276   gc_state_ = NOT_IN_GC;
1277
1278   scavenges_since_last_idle_round_++;
1279 }
1280
1281
1282 String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Heap* heap,
1283                                                                 Object** p) {
1284   MapWord first_word = HeapObject::cast(*p)->map_word();
1285
1286   if (!first_word.IsForwardingAddress()) {
1287     // Unreachable external string can be finalized.
1288     heap->FinalizeExternalString(String::cast(*p));
1289     return NULL;
1290   }
1291
1292   // String is still reachable.
1293   return String::cast(first_word.ToForwardingAddress());
1294 }
1295
1296
1297 void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1298     ExternalStringTableUpdaterCallback updater_func) {
1299   if (FLAG_verify_heap) {
1300     external_string_table_.Verify();
1301   }
1302
1303   if (external_string_table_.new_space_strings_.is_empty()) return;
1304
1305   Object** start = &external_string_table_.new_space_strings_[0];
1306   Object** end = start + external_string_table_.new_space_strings_.length();
1307   Object** last = start;
1308
1309   for (Object** p = start; p < end; ++p) {
1310     ASSERT(InFromSpace(*p));
1311     String* target = updater_func(this, p);
1312
1313     if (target == NULL) continue;
1314
1315     ASSERT(target->IsExternalString());
1316
1317     if (InNewSpace(target)) {
1318       // String is still in new space.  Update the table entry.
1319       *last = target;
1320       ++last;
1321     } else {
1322       // String got promoted.  Move it to the old string list.
1323       external_string_table_.AddOldString(target);
1324     }
1325   }
1326
1327   ASSERT(last <= end);
1328   external_string_table_.ShrinkNewStrings(static_cast<int>(last - start));
1329 }
1330
1331
1332 void Heap::UpdateReferencesInExternalStringTable(
1333     ExternalStringTableUpdaterCallback updater_func) {
1334
1335   // Update old space string references.
1336   if (external_string_table_.old_space_strings_.length() > 0) {
1337     Object** start = &external_string_table_.old_space_strings_[0];
1338     Object** end = start + external_string_table_.old_space_strings_.length();
1339     for (Object** p = start; p < end; ++p) *p = updater_func(this, p);
1340   }
1341
1342   UpdateNewSpaceReferencesInExternalStringTable(updater_func);
1343 }
1344
1345
1346 static Object* ProcessFunctionWeakReferences(Heap* heap,
1347                                              Object* function,
1348                                              WeakObjectRetainer* retainer,
1349                                              bool record_slots) {
1350   Object* undefined = heap->undefined_value();
1351   Object* head = undefined;
1352   JSFunction* tail = NULL;
1353   Object* candidate = function;
1354   while (candidate != undefined) {
1355     // Check whether to keep the candidate in the list.
1356     JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1357     Object* retain = retainer->RetainAs(candidate);
1358     if (retain != NULL) {
1359       if (head == undefined) {
1360         // First element in the list.
1361         head = retain;
1362       } else {
1363         // Subsequent elements in the list.
1364         ASSERT(tail != NULL);
1365         tail->set_next_function_link(retain);
1366         if (record_slots) {
1367           Object** next_function =
1368               HeapObject::RawField(tail, JSFunction::kNextFunctionLinkOffset);
1369           heap->mark_compact_collector()->RecordSlot(
1370               next_function, next_function, retain);
1371         }
1372       }
1373       // Retained function is new tail.
1374       candidate_function = reinterpret_cast<JSFunction*>(retain);
1375       tail = candidate_function;
1376
1377       ASSERT(retain->IsUndefined() || retain->IsJSFunction());
1378
1379       if (retain == undefined) break;
1380     }
1381
1382     // Move to next element in the list.
1383     candidate = candidate_function->next_function_link();
1384   }
1385
1386   // Terminate the list if there is one or more elements.
1387   if (tail != NULL) {
1388     tail->set_next_function_link(undefined);
1389   }
1390
1391   return head;
1392 }
1393
1394
1395 void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1396   Object* undefined = undefined_value();
1397   Object* head = undefined;
1398   Context* tail = NULL;
1399   Object* candidate = global_contexts_list_;
1400
1401   // We don't record weak slots during marking or scavenges.
1402   // Instead we do it once when we complete mark-compact cycle.
1403   // Note that write barrier has no effect if we are already in the middle of
1404   // compacting mark-sweep cycle and we have to record slots manually.
1405   bool record_slots =
1406       gc_state() == MARK_COMPACT &&
1407       mark_compact_collector()->is_compacting();
1408
1409   while (candidate != undefined) {
1410     // Check whether to keep the candidate in the list.
1411     Context* candidate_context = reinterpret_cast<Context*>(candidate);
1412     Object* retain = retainer->RetainAs(candidate);
1413     if (retain != NULL) {
1414       if (head == undefined) {
1415         // First element in the list.
1416         head = retain;
1417       } else {
1418         // Subsequent elements in the list.
1419         ASSERT(tail != NULL);
1420         tail->set_unchecked(this,
1421                             Context::NEXT_CONTEXT_LINK,
1422                             retain,
1423                             UPDATE_WRITE_BARRIER);
1424
1425         if (record_slots) {
1426           Object** next_context =
1427               HeapObject::RawField(
1428                   tail, FixedArray::SizeFor(Context::NEXT_CONTEXT_LINK));
1429           mark_compact_collector()->RecordSlot(
1430               next_context, next_context, retain);
1431         }
1432       }
1433       // Retained context is new tail.
1434       candidate_context = reinterpret_cast<Context*>(retain);
1435       tail = candidate_context;
1436
1437       if (retain == undefined) break;
1438
1439       // Process the weak list of optimized functions for the context.
1440       Object* function_list_head =
1441           ProcessFunctionWeakReferences(
1442               this,
1443               candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1444               retainer,
1445               record_slots);
1446       candidate_context->set_unchecked(this,
1447                                        Context::OPTIMIZED_FUNCTIONS_LIST,
1448                                        function_list_head,
1449                                        UPDATE_WRITE_BARRIER);
1450       if (record_slots) {
1451         Object** optimized_functions =
1452             HeapObject::RawField(
1453                 tail, FixedArray::SizeFor(Context::OPTIMIZED_FUNCTIONS_LIST));
1454         mark_compact_collector()->RecordSlot(
1455             optimized_functions, optimized_functions, function_list_head);
1456       }
1457     }
1458
1459     // Move to next element in the list.
1460     candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1461   }
1462
1463   // Terminate the list if there is one or more elements.
1464   if (tail != NULL) {
1465     tail->set_unchecked(this,
1466                         Context::NEXT_CONTEXT_LINK,
1467                         Heap::undefined_value(),
1468                         UPDATE_WRITE_BARRIER);
1469   }
1470
1471   // Update the head of the list of contexts.
1472   global_contexts_list_ = head;
1473 }
1474
1475
1476 void Heap::VisitExternalResources(v8::ExternalResourceVisitor* visitor) {
1477   AssertNoAllocation no_allocation;
1478
1479   class VisitorAdapter : public ObjectVisitor {
1480    public:
1481     explicit VisitorAdapter(v8::ExternalResourceVisitor* visitor)
1482         : visitor_(visitor) {}
1483     virtual void VisitPointers(Object** start, Object** end) {
1484       for (Object** p = start; p < end; p++) {
1485         if ((*p)->IsExternalString()) {
1486           visitor_->VisitExternalString(Utils::ToLocal(
1487               Handle<String>(String::cast(*p))));
1488         }
1489       }
1490     }
1491    private:
1492     v8::ExternalResourceVisitor* visitor_;
1493   } visitor_adapter(visitor);
1494   external_string_table_.Iterate(&visitor_adapter);
1495 }
1496
1497
1498 class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1499  public:
1500   static inline void VisitPointer(Heap* heap, Object** p) {
1501     Object* object = *p;
1502     if (!heap->InNewSpace(object)) return;
1503     Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1504                          reinterpret_cast<HeapObject*>(object));
1505   }
1506 };
1507
1508
1509 Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1510                          Address new_space_front) {
1511   do {
1512     SemiSpace::AssertValidRange(new_space_front, new_space_.top());
1513     // The addresses new_space_front and new_space_.top() define a
1514     // queue of unprocessed copied objects.  Process them until the
1515     // queue is empty.
1516     while (new_space_front != new_space_.top()) {
1517       if (!NewSpacePage::IsAtEnd(new_space_front)) {
1518         HeapObject* object = HeapObject::FromAddress(new_space_front);
1519         new_space_front +=
1520           NewSpaceScavenger::IterateBody(object->map(), object);
1521       } else {
1522         new_space_front =
1523             NewSpacePage::FromLimit(new_space_front)->next_page()->area_start();
1524       }
1525     }
1526
1527     // Promote and process all the to-be-promoted objects.
1528     {
1529       StoreBufferRebuildScope scope(this,
1530                                     store_buffer(),
1531                                     &ScavengeStoreBufferCallback);
1532       while (!promotion_queue()->is_empty()) {
1533         HeapObject* target;
1534         int size;
1535         promotion_queue()->remove(&target, &size);
1536
1537         // Promoted object might be already partially visited
1538         // during old space pointer iteration. Thus we search specificly
1539         // for pointers to from semispace instead of looking for pointers
1540         // to new space.
1541         ASSERT(!target->IsMap());
1542         IterateAndMarkPointersToFromSpace(target->address(),
1543                                           target->address() + size,
1544                                           &ScavengeObject);
1545       }
1546     }
1547
1548     // Take another spin if there are now unswept objects in new space
1549     // (there are currently no more unswept promoted objects).
1550   } while (new_space_front != new_space_.top());
1551
1552   return new_space_front;
1553 }
1554
1555
1556 STATIC_ASSERT((FixedDoubleArray::kHeaderSize & kDoubleAlignmentMask) == 0);
1557
1558
1559 INLINE(static HeapObject* EnsureDoubleAligned(Heap* heap,
1560                                               HeapObject* object,
1561                                               int size));
1562
1563 static HeapObject* EnsureDoubleAligned(Heap* heap,
1564                                        HeapObject* object,
1565                                        int size) {
1566   if ((OffsetFrom(object->address()) & kDoubleAlignmentMask) != 0) {
1567     heap->CreateFillerObjectAt(object->address(), kPointerSize);
1568     return HeapObject::FromAddress(object->address() + kPointerSize);
1569   } else {
1570     heap->CreateFillerObjectAt(object->address() + size - kPointerSize,
1571                                kPointerSize);
1572     return object;
1573   }
1574 }
1575
1576
1577 enum LoggingAndProfiling {
1578   LOGGING_AND_PROFILING_ENABLED,
1579   LOGGING_AND_PROFILING_DISABLED
1580 };
1581
1582
1583 enum MarksHandling { TRANSFER_MARKS, IGNORE_MARKS };
1584
1585
1586 template<MarksHandling marks_handling,
1587          LoggingAndProfiling logging_and_profiling_mode>
1588 class ScavengingVisitor : public StaticVisitorBase {
1589  public:
1590   static void Initialize() {
1591     table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1592     table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1593     table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1594     table_.Register(kVisitByteArray, &EvacuateByteArray);
1595     table_.Register(kVisitFixedArray, &EvacuateFixedArray);
1596     table_.Register(kVisitFixedDoubleArray, &EvacuateFixedDoubleArray);
1597
1598     table_.Register(kVisitGlobalContext,
1599                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1600                         template VisitSpecialized<Context::kSize>);
1601
1602     table_.Register(kVisitConsString,
1603                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1604                         template VisitSpecialized<ConsString::kSize>);
1605
1606     table_.Register(kVisitSlicedString,
1607                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1608                         template VisitSpecialized<SlicedString::kSize>);
1609
1610     table_.Register(kVisitSharedFunctionInfo,
1611                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1612                         template VisitSpecialized<SharedFunctionInfo::kSize>);
1613
1614     table_.Register(kVisitJSWeakMap,
1615                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1616                     Visit);
1617
1618     table_.Register(kVisitJSRegExp,
1619                     &ObjectEvacuationStrategy<POINTER_OBJECT>::
1620                     Visit);
1621
1622     if (marks_handling == IGNORE_MARKS) {
1623       table_.Register(kVisitJSFunction,
1624                       &ObjectEvacuationStrategy<POINTER_OBJECT>::
1625                           template VisitSpecialized<JSFunction::kSize>);
1626     } else {
1627       table_.Register(kVisitJSFunction, &EvacuateJSFunction);
1628     }
1629
1630     table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1631                                    kVisitDataObject,
1632                                    kVisitDataObjectGeneric>();
1633
1634     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1635                                    kVisitJSObject,
1636                                    kVisitJSObjectGeneric>();
1637
1638     table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1639                                    kVisitStruct,
1640                                    kVisitStructGeneric>();
1641   }
1642
1643   static VisitorDispatchTable<ScavengingCallback>* GetTable() {
1644     return &table_;
1645   }
1646
1647  private:
1648   enum ObjectContents  { DATA_OBJECT, POINTER_OBJECT };
1649   enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1650
1651   static void RecordCopiedObject(Heap* heap, HeapObject* obj) {
1652     bool should_record = false;
1653 #ifdef DEBUG
1654     should_record = FLAG_heap_stats;
1655 #endif
1656     should_record = should_record || FLAG_log_gc;
1657     if (should_record) {
1658       if (heap->new_space()->Contains(obj)) {
1659         heap->new_space()->RecordAllocation(obj);
1660       } else {
1661         heap->new_space()->RecordPromotion(obj);
1662       }
1663     }
1664   }
1665
1666   // Helper function used by CopyObject to copy a source object to an
1667   // allocated target object and update the forwarding pointer in the source
1668   // object.  Returns the target object.
1669   INLINE(static void MigrateObject(Heap* heap,
1670                                    HeapObject* source,
1671                                    HeapObject* target,
1672                                    int size)) {
1673     // Copy the content of source to target.
1674     heap->CopyBlock(target->address(), source->address(), size);
1675
1676     // Set the forwarding address.
1677     source->set_map_word(MapWord::FromForwardingAddress(target));
1678
1679     if (logging_and_profiling_mode == LOGGING_AND_PROFILING_ENABLED) {
1680       // Update NewSpace stats if necessary.
1681       RecordCopiedObject(heap, target);
1682       HEAP_PROFILE(heap, ObjectMoveEvent(source->address(), target->address()));
1683       Isolate* isolate = heap->isolate();
1684       if (isolate->logger()->is_logging() ||
1685           CpuProfiler::is_profiling(isolate)) {
1686         if (target->IsSharedFunctionInfo()) {
1687           PROFILE(isolate, SharedFunctionInfoMoveEvent(
1688               source->address(), target->address()));
1689         }
1690       }
1691     }
1692
1693     if (marks_handling == TRANSFER_MARKS) {
1694       if (Marking::TransferColor(source, target)) {
1695         MemoryChunk::IncrementLiveBytesFromGC(target->address(), size);
1696       }
1697     }
1698   }
1699
1700
1701   template<ObjectContents object_contents,
1702            SizeRestriction size_restriction,
1703            int alignment>
1704   static inline void EvacuateObject(Map* map,
1705                                     HeapObject** slot,
1706                                     HeapObject* object,
1707                                     int object_size) {
1708     SLOW_ASSERT((size_restriction != SMALL) ||
1709                 (object_size <= Page::kMaxNonCodeHeapObjectSize));
1710     SLOW_ASSERT(object->Size() == object_size);
1711
1712     int allocation_size = object_size;
1713     if (alignment != kObjectAlignment) {
1714       ASSERT(alignment == kDoubleAlignment);
1715       allocation_size += kPointerSize;
1716     }
1717
1718     Heap* heap = map->GetHeap();
1719     if (heap->ShouldBePromoted(object->address(), object_size)) {
1720       MaybeObject* maybe_result;
1721
1722       if ((size_restriction != SMALL) &&
1723           (allocation_size > Page::kMaxNonCodeHeapObjectSize)) {
1724         maybe_result = heap->lo_space()->AllocateRaw(allocation_size,
1725                                                      NOT_EXECUTABLE);
1726       } else {
1727         if (object_contents == DATA_OBJECT) {
1728           maybe_result = heap->old_data_space()->AllocateRaw(allocation_size);
1729         } else {
1730           maybe_result =
1731               heap->old_pointer_space()->AllocateRaw(allocation_size);
1732         }
1733       }
1734
1735       Object* result = NULL;  // Initialization to please compiler.
1736       if (maybe_result->ToObject(&result)) {
1737         HeapObject* target = HeapObject::cast(result);
1738
1739         if (alignment != kObjectAlignment) {
1740           target = EnsureDoubleAligned(heap, target, allocation_size);
1741         }
1742
1743         // Order is important: slot might be inside of the target if target
1744         // was allocated over a dead object and slot comes from the store
1745         // buffer.
1746         *slot = target;
1747         MigrateObject(heap, object, target, object_size);
1748
1749         if (object_contents == POINTER_OBJECT) {
1750           if (map->instance_type() == JS_FUNCTION_TYPE) {
1751             heap->promotion_queue()->insert(
1752                 target, JSFunction::kNonWeakFieldsEndOffset);
1753           } else {
1754             heap->promotion_queue()->insert(target, object_size);
1755           }
1756         }
1757
1758         heap->tracer()->increment_promoted_objects_size(object_size);
1759         return;
1760       }
1761     }
1762     MaybeObject* allocation = heap->new_space()->AllocateRaw(allocation_size);
1763     heap->promotion_queue()->SetNewLimit(heap->new_space()->top());
1764     Object* result = allocation->ToObjectUnchecked();
1765     HeapObject* target = HeapObject::cast(result);
1766
1767     if (alignment != kObjectAlignment) {
1768       target = EnsureDoubleAligned(heap, target, allocation_size);
1769     }
1770
1771     // Order is important: slot might be inside of the target if target
1772     // was allocated over a dead object and slot comes from the store
1773     // buffer.
1774     *slot = target;
1775     MigrateObject(heap, object, target, object_size);
1776     return;
1777   }
1778
1779
1780   static inline void EvacuateJSFunction(Map* map,
1781                                         HeapObject** slot,
1782                                         HeapObject* object) {
1783     ObjectEvacuationStrategy<POINTER_OBJECT>::
1784         template VisitSpecialized<JSFunction::kSize>(map, slot, object);
1785
1786     HeapObject* target = *slot;
1787     MarkBit mark_bit = Marking::MarkBitFrom(target);
1788     if (Marking::IsBlack(mark_bit)) {
1789       // This object is black and it might not be rescanned by marker.
1790       // We should explicitly record code entry slot for compaction because
1791       // promotion queue processing (IterateAndMarkPointersToFromSpace) will
1792       // miss it as it is not HeapObject-tagged.
1793       Address code_entry_slot =
1794           target->address() + JSFunction::kCodeEntryOffset;
1795       Code* code = Code::cast(Code::GetObjectFromEntryAddress(code_entry_slot));
1796       map->GetHeap()->mark_compact_collector()->
1797           RecordCodeEntrySlot(code_entry_slot, code);
1798     }
1799   }
1800
1801
1802   static inline void EvacuateFixedArray(Map* map,
1803                                         HeapObject** slot,
1804                                         HeapObject* object) {
1805     int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1806     EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(map,
1807                                                  slot,
1808                                                  object,
1809                                                  object_size);
1810   }
1811
1812
1813   static inline void EvacuateFixedDoubleArray(Map* map,
1814                                               HeapObject** slot,
1815                                               HeapObject* object) {
1816     int length = reinterpret_cast<FixedDoubleArray*>(object)->length();
1817     int object_size = FixedDoubleArray::SizeFor(length);
1818     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kDoubleAlignment>(
1819         map,
1820         slot,
1821         object,
1822         object_size);
1823   }
1824
1825
1826   static inline void EvacuateByteArray(Map* map,
1827                                        HeapObject** slot,
1828                                        HeapObject* object) {
1829     int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1830     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1831         map, slot, object, object_size);
1832   }
1833
1834
1835   static inline void EvacuateSeqAsciiString(Map* map,
1836                                             HeapObject** slot,
1837                                             HeapObject* object) {
1838     int object_size = SeqAsciiString::cast(object)->
1839         SeqAsciiStringSize(map->instance_type());
1840     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1841         map, slot, object, object_size);
1842   }
1843
1844
1845   static inline void EvacuateSeqTwoByteString(Map* map,
1846                                               HeapObject** slot,
1847                                               HeapObject* object) {
1848     int object_size = SeqTwoByteString::cast(object)->
1849         SeqTwoByteStringSize(map->instance_type());
1850     EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE, kObjectAlignment>(
1851         map, slot, object, object_size);
1852   }
1853
1854
1855   static inline bool IsShortcutCandidate(int type) {
1856     return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1857   }
1858
1859   static inline void EvacuateShortcutCandidate(Map* map,
1860                                                HeapObject** slot,
1861                                                HeapObject* object) {
1862     ASSERT(IsShortcutCandidate(map->instance_type()));
1863
1864     Heap* heap = map->GetHeap();
1865
1866     if (marks_handling == IGNORE_MARKS &&
1867         ConsString::cast(object)->unchecked_second() ==
1868         heap->empty_string()) {
1869       HeapObject* first =
1870           HeapObject::cast(ConsString::cast(object)->unchecked_first());
1871
1872       *slot = first;
1873
1874       if (!heap->InNewSpace(first)) {
1875         object->set_map_word(MapWord::FromForwardingAddress(first));
1876         return;
1877       }
1878
1879       MapWord first_word = first->map_word();
1880       if (first_word.IsForwardingAddress()) {
1881         HeapObject* target = first_word.ToForwardingAddress();
1882
1883         *slot = target;
1884         object->set_map_word(MapWord::FromForwardingAddress(target));
1885         return;
1886       }
1887
1888       heap->DoScavengeObject(first->map(), slot, first);
1889       object->set_map_word(MapWord::FromForwardingAddress(*slot));
1890       return;
1891     }
1892
1893     int object_size = ConsString::kSize;
1894     EvacuateObject<POINTER_OBJECT, SMALL, kObjectAlignment>(
1895         map, slot, object, object_size);
1896   }
1897
1898   template<ObjectContents object_contents>
1899   class ObjectEvacuationStrategy {
1900    public:
1901     template<int object_size>
1902     static inline void VisitSpecialized(Map* map,
1903                                         HeapObject** slot,
1904                                         HeapObject* object) {
1905       EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1906           map, slot, object, object_size);
1907     }
1908
1909     static inline void Visit(Map* map,
1910                              HeapObject** slot,
1911                              HeapObject* object) {
1912       int object_size = map->instance_size();
1913       EvacuateObject<object_contents, SMALL, kObjectAlignment>(
1914           map, slot, object, object_size);
1915     }
1916   };
1917
1918   static VisitorDispatchTable<ScavengingCallback> table_;
1919 };
1920
1921
1922 template<MarksHandling marks_handling,
1923          LoggingAndProfiling logging_and_profiling_mode>
1924 VisitorDispatchTable<ScavengingCallback>
1925     ScavengingVisitor<marks_handling, logging_and_profiling_mode>::table_;
1926
1927
1928 static void InitializeScavengingVisitorsTables() {
1929   ScavengingVisitor<TRANSFER_MARKS,
1930                     LOGGING_AND_PROFILING_DISABLED>::Initialize();
1931   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_DISABLED>::Initialize();
1932   ScavengingVisitor<TRANSFER_MARKS,
1933                     LOGGING_AND_PROFILING_ENABLED>::Initialize();
1934   ScavengingVisitor<IGNORE_MARKS, LOGGING_AND_PROFILING_ENABLED>::Initialize();
1935 }
1936
1937
1938 void Heap::SelectScavengingVisitorsTable() {
1939   bool logging_and_profiling =
1940       isolate()->logger()->is_logging() ||
1941       CpuProfiler::is_profiling(isolate()) ||
1942       (isolate()->heap_profiler() != NULL &&
1943        isolate()->heap_profiler()->is_profiling());
1944
1945   if (!incremental_marking()->IsMarking()) {
1946     if (!logging_and_profiling) {
1947       scavenging_visitors_table_.CopyFrom(
1948           ScavengingVisitor<IGNORE_MARKS,
1949                             LOGGING_AND_PROFILING_DISABLED>::GetTable());
1950     } else {
1951       scavenging_visitors_table_.CopyFrom(
1952           ScavengingVisitor<IGNORE_MARKS,
1953                             LOGGING_AND_PROFILING_ENABLED>::GetTable());
1954     }
1955   } else {
1956     if (!logging_and_profiling) {
1957       scavenging_visitors_table_.CopyFrom(
1958           ScavengingVisitor<TRANSFER_MARKS,
1959                             LOGGING_AND_PROFILING_DISABLED>::GetTable());
1960     } else {
1961       scavenging_visitors_table_.CopyFrom(
1962           ScavengingVisitor<TRANSFER_MARKS,
1963                             LOGGING_AND_PROFILING_ENABLED>::GetTable());
1964     }
1965
1966     if (incremental_marking()->IsCompacting()) {
1967       // When compacting forbid short-circuiting of cons-strings.
1968       // Scavenging code relies on the fact that new space object
1969       // can't be evacuated into evacuation candidate but
1970       // short-circuiting violates this assumption.
1971       scavenging_visitors_table_.Register(
1972           StaticVisitorBase::kVisitShortcutCandidate,
1973           scavenging_visitors_table_.GetVisitorById(
1974               StaticVisitorBase::kVisitConsString));
1975     }
1976   }
1977 }
1978
1979
1980 void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1981   SLOW_ASSERT(HEAP->InFromSpace(object));
1982   MapWord first_word = object->map_word();
1983   SLOW_ASSERT(!first_word.IsForwardingAddress());
1984   Map* map = first_word.ToMap();
1985   map->GetHeap()->DoScavengeObject(map, p, object);
1986 }
1987
1988
1989 MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1990                                       int instance_size) {
1991   Object* result;
1992   { MaybeObject* maybe_result = AllocateRawMap();
1993     if (!maybe_result->ToObject(&result)) return maybe_result;
1994   }
1995
1996   // Map::cast cannot be used due to uninitialized map field.
1997   reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1998   reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1999   reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
2000   reinterpret_cast<Map*>(result)->set_visitor_id(
2001         StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2002   reinterpret_cast<Map*>(result)->set_inobject_properties(0);
2003   reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
2004   reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
2005   reinterpret_cast<Map*>(result)->set_bit_field(0);
2006   reinterpret_cast<Map*>(result)->set_bit_field2(0);
2007   return result;
2008 }
2009
2010
2011 MaybeObject* Heap::AllocateMap(InstanceType instance_type,
2012                                int instance_size,
2013                                ElementsKind elements_kind) {
2014   Object* result;
2015   { MaybeObject* maybe_result = AllocateRawMap();
2016     if (!maybe_result->ToObject(&result)) return maybe_result;
2017   }
2018
2019   Map* map = reinterpret_cast<Map*>(result);
2020   map->set_map_no_write_barrier(meta_map());
2021   map->set_instance_type(instance_type);
2022   map->set_visitor_id(
2023       StaticVisitorBase::GetVisitorId(instance_type, instance_size));
2024   map->set_prototype(null_value(), SKIP_WRITE_BARRIER);
2025   map->set_constructor(null_value(), SKIP_WRITE_BARRIER);
2026   map->set_instance_size(instance_size);
2027   map->set_inobject_properties(0);
2028   map->set_pre_allocated_property_fields(0);
2029   map->init_instance_descriptors();
2030   map->set_code_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2031   map->init_prototype_transitions(undefined_value());
2032   map->set_unused_property_fields(0);
2033   map->set_bit_field(0);
2034   map->set_bit_field2(1 << Map::kIsExtensible);
2035   map->set_elements_kind(elements_kind);
2036
2037   // If the map object is aligned fill the padding area with Smi 0 objects.
2038   if (Map::kPadStart < Map::kSize) {
2039     memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
2040            0,
2041            Map::kSize - Map::kPadStart);
2042   }
2043   return map;
2044 }
2045
2046
2047 MaybeObject* Heap::AllocateCodeCache() {
2048   CodeCache* code_cache;
2049   { MaybeObject* maybe_code_cache = AllocateStruct(CODE_CACHE_TYPE);
2050     if (!maybe_code_cache->To(&code_cache)) return maybe_code_cache;
2051   }
2052   code_cache->set_default_cache(empty_fixed_array(), SKIP_WRITE_BARRIER);
2053   code_cache->set_normal_type_cache(undefined_value(), SKIP_WRITE_BARRIER);
2054   return code_cache;
2055 }
2056
2057
2058 MaybeObject* Heap::AllocatePolymorphicCodeCache() {
2059   return AllocateStruct(POLYMORPHIC_CODE_CACHE_TYPE);
2060 }
2061
2062
2063 MaybeObject* Heap::AllocateAccessorPair() {
2064   AccessorPair* accessors;
2065   { MaybeObject* maybe_accessors = AllocateStruct(ACCESSOR_PAIR_TYPE);
2066     if (!maybe_accessors->To(&accessors)) return maybe_accessors;
2067   }
2068   accessors->set_getter(the_hole_value(), SKIP_WRITE_BARRIER);
2069   accessors->set_setter(the_hole_value(), SKIP_WRITE_BARRIER);
2070   return accessors;
2071 }
2072
2073
2074 MaybeObject* Heap::AllocateTypeFeedbackInfo() {
2075   TypeFeedbackInfo* info;
2076   { MaybeObject* maybe_info = AllocateStruct(TYPE_FEEDBACK_INFO_TYPE);
2077     if (!maybe_info->To(&info)) return maybe_info;
2078   }
2079   info->set_ic_total_count(0);
2080   info->set_ic_with_type_info_count(0);
2081   info->set_type_feedback_cells(TypeFeedbackCells::cast(empty_fixed_array()),
2082                                 SKIP_WRITE_BARRIER);
2083   return info;
2084 }
2085
2086
2087 MaybeObject* Heap::AllocateAliasedArgumentsEntry(int aliased_context_slot) {
2088   AliasedArgumentsEntry* entry;
2089   { MaybeObject* maybe_entry = AllocateStruct(ALIASED_ARGUMENTS_ENTRY_TYPE);
2090     if (!maybe_entry->To(&entry)) return maybe_entry;
2091   }
2092   entry->set_aliased_context_slot(aliased_context_slot);
2093   return entry;
2094 }
2095
2096
2097 const Heap::StringTypeTable Heap::string_type_table[] = {
2098 #define STRING_TYPE_ELEMENT(type, size, name, camel_name)                      \
2099   {type, size, k##camel_name##MapRootIndex},
2100   STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
2101 #undef STRING_TYPE_ELEMENT
2102 };
2103
2104
2105 const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
2106 #define CONSTANT_SYMBOL_ELEMENT(name, contents)                                \
2107   {contents, k##name##RootIndex},
2108   SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
2109 #undef CONSTANT_SYMBOL_ELEMENT
2110 };
2111
2112
2113 const Heap::StructTable Heap::struct_table[] = {
2114 #define STRUCT_TABLE_ELEMENT(NAME, Name, name)                                 \
2115   { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
2116   STRUCT_LIST(STRUCT_TABLE_ELEMENT)
2117 #undef STRUCT_TABLE_ELEMENT
2118 };
2119
2120
2121 bool Heap::CreateInitialMaps() {
2122   Object* obj;
2123   { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
2124     if (!maybe_obj->ToObject(&obj)) return false;
2125   }
2126   // Map::cast cannot be used due to uninitialized map field.
2127   Map* new_meta_map = reinterpret_cast<Map*>(obj);
2128   set_meta_map(new_meta_map);
2129   new_meta_map->set_map(new_meta_map);
2130
2131   { MaybeObject* maybe_obj =
2132         AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2133     if (!maybe_obj->ToObject(&obj)) return false;
2134   }
2135   set_fixed_array_map(Map::cast(obj));
2136
2137   { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
2138     if (!maybe_obj->ToObject(&obj)) return false;
2139   }
2140   set_oddball_map(Map::cast(obj));
2141
2142   // Allocate the empty array.
2143   { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2144     if (!maybe_obj->ToObject(&obj)) return false;
2145   }
2146   set_empty_fixed_array(FixedArray::cast(obj));
2147
2148   { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2149     if (!maybe_obj->ToObject(&obj)) return false;
2150   }
2151   set_null_value(Oddball::cast(obj));
2152   Oddball::cast(obj)->set_kind(Oddball::kNull);
2153
2154   { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_POINTER_SPACE);
2155     if (!maybe_obj->ToObject(&obj)) return false;
2156   }
2157   set_undefined_value(Oddball::cast(obj));
2158   Oddball::cast(obj)->set_kind(Oddball::kUndefined);
2159   ASSERT(!InNewSpace(undefined_value()));
2160
2161   // Allocate the empty descriptor array.
2162   { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
2163     if (!maybe_obj->ToObject(&obj)) return false;
2164   }
2165   set_empty_descriptor_array(DescriptorArray::cast(obj));
2166
2167   // Fix the instance_descriptors for the existing maps.
2168   meta_map()->init_instance_descriptors();
2169   meta_map()->set_code_cache(empty_fixed_array());
2170   meta_map()->init_prototype_transitions(undefined_value());
2171
2172   fixed_array_map()->init_instance_descriptors();
2173   fixed_array_map()->set_code_cache(empty_fixed_array());
2174   fixed_array_map()->init_prototype_transitions(undefined_value());
2175
2176   oddball_map()->init_instance_descriptors();
2177   oddball_map()->set_code_cache(empty_fixed_array());
2178   oddball_map()->init_prototype_transitions(undefined_value());
2179
2180   // Fix prototype object for existing maps.
2181   meta_map()->set_prototype(null_value());
2182   meta_map()->set_constructor(null_value());
2183
2184   fixed_array_map()->set_prototype(null_value());
2185   fixed_array_map()->set_constructor(null_value());
2186
2187   oddball_map()->set_prototype(null_value());
2188   oddball_map()->set_constructor(null_value());
2189
2190   { MaybeObject* maybe_obj =
2191         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2192     if (!maybe_obj->ToObject(&obj)) return false;
2193   }
2194   set_fixed_cow_array_map(Map::cast(obj));
2195   ASSERT(fixed_array_map() != fixed_cow_array_map());
2196
2197   { MaybeObject* maybe_obj =
2198         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2199     if (!maybe_obj->ToObject(&obj)) return false;
2200   }
2201   set_scope_info_map(Map::cast(obj));
2202
2203   { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
2204     if (!maybe_obj->ToObject(&obj)) return false;
2205   }
2206   set_heap_number_map(Map::cast(obj));
2207
2208   { MaybeObject* maybe_obj = AllocateMap(FOREIGN_TYPE, Foreign::kSize);
2209     if (!maybe_obj->ToObject(&obj)) return false;
2210   }
2211   set_foreign_map(Map::cast(obj));
2212
2213   for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
2214     const StringTypeTable& entry = string_type_table[i];
2215     { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2216       if (!maybe_obj->ToObject(&obj)) return false;
2217     }
2218     roots_[entry.index] = Map::cast(obj);
2219   }
2220
2221   { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
2222     if (!maybe_obj->ToObject(&obj)) return false;
2223   }
2224   set_undetectable_string_map(Map::cast(obj));
2225   Map::cast(obj)->set_is_undetectable();
2226
2227   { MaybeObject* maybe_obj =
2228         AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
2229     if (!maybe_obj->ToObject(&obj)) return false;
2230   }
2231   set_undetectable_ascii_string_map(Map::cast(obj));
2232   Map::cast(obj)->set_is_undetectable();
2233
2234   { MaybeObject* maybe_obj =
2235         AllocateMap(FIXED_DOUBLE_ARRAY_TYPE, kVariableSizeSentinel);
2236     if (!maybe_obj->ToObject(&obj)) return false;
2237   }
2238   set_fixed_double_array_map(Map::cast(obj));
2239
2240   { MaybeObject* maybe_obj =
2241         AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
2242     if (!maybe_obj->ToObject(&obj)) return false;
2243   }
2244   set_byte_array_map(Map::cast(obj));
2245
2246   { MaybeObject* maybe_obj =
2247         AllocateMap(FREE_SPACE_TYPE, kVariableSizeSentinel);
2248     if (!maybe_obj->ToObject(&obj)) return false;
2249   }
2250   set_free_space_map(Map::cast(obj));
2251
2252   { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
2253     if (!maybe_obj->ToObject(&obj)) return false;
2254   }
2255   set_empty_byte_array(ByteArray::cast(obj));
2256
2257   { MaybeObject* maybe_obj =
2258         AllocateMap(EXTERNAL_PIXEL_ARRAY_TYPE, ExternalArray::kAlignedSize);
2259     if (!maybe_obj->ToObject(&obj)) return false;
2260   }
2261   set_external_pixel_array_map(Map::cast(obj));
2262
2263   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
2264                                          ExternalArray::kAlignedSize);
2265     if (!maybe_obj->ToObject(&obj)) return false;
2266   }
2267   set_external_byte_array_map(Map::cast(obj));
2268
2269   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
2270                                          ExternalArray::kAlignedSize);
2271     if (!maybe_obj->ToObject(&obj)) return false;
2272   }
2273   set_external_unsigned_byte_array_map(Map::cast(obj));
2274
2275   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
2276                                          ExternalArray::kAlignedSize);
2277     if (!maybe_obj->ToObject(&obj)) return false;
2278   }
2279   set_external_short_array_map(Map::cast(obj));
2280
2281   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
2282                                          ExternalArray::kAlignedSize);
2283     if (!maybe_obj->ToObject(&obj)) return false;
2284   }
2285   set_external_unsigned_short_array_map(Map::cast(obj));
2286
2287   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
2288                                          ExternalArray::kAlignedSize);
2289     if (!maybe_obj->ToObject(&obj)) return false;
2290   }
2291   set_external_int_array_map(Map::cast(obj));
2292
2293   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
2294                                          ExternalArray::kAlignedSize);
2295     if (!maybe_obj->ToObject(&obj)) return false;
2296   }
2297   set_external_unsigned_int_array_map(Map::cast(obj));
2298
2299   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
2300                                          ExternalArray::kAlignedSize);
2301     if (!maybe_obj->ToObject(&obj)) return false;
2302   }
2303   set_external_float_array_map(Map::cast(obj));
2304
2305   { MaybeObject* maybe_obj =
2306         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2307     if (!maybe_obj->ToObject(&obj)) return false;
2308   }
2309   set_non_strict_arguments_elements_map(Map::cast(obj));
2310
2311   { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_DOUBLE_ARRAY_TYPE,
2312                                          ExternalArray::kAlignedSize);
2313     if (!maybe_obj->ToObject(&obj)) return false;
2314   }
2315   set_external_double_array_map(Map::cast(obj));
2316
2317   { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
2318     if (!maybe_obj->ToObject(&obj)) return false;
2319   }
2320   set_code_map(Map::cast(obj));
2321
2322   { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
2323                                          JSGlobalPropertyCell::kSize);
2324     if (!maybe_obj->ToObject(&obj)) return false;
2325   }
2326   set_global_property_cell_map(Map::cast(obj));
2327
2328   { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
2329     if (!maybe_obj->ToObject(&obj)) return false;
2330   }
2331   set_one_pointer_filler_map(Map::cast(obj));
2332
2333   { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
2334     if (!maybe_obj->ToObject(&obj)) return false;
2335   }
2336   set_two_pointer_filler_map(Map::cast(obj));
2337
2338   for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
2339     const StructTable& entry = struct_table[i];
2340     { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
2341       if (!maybe_obj->ToObject(&obj)) return false;
2342     }
2343     roots_[entry.index] = Map::cast(obj);
2344   }
2345
2346   { MaybeObject* maybe_obj =
2347         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2348     if (!maybe_obj->ToObject(&obj)) return false;
2349   }
2350   set_hash_table_map(Map::cast(obj));
2351
2352   { MaybeObject* maybe_obj =
2353         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2354     if (!maybe_obj->ToObject(&obj)) return false;
2355   }
2356   set_function_context_map(Map::cast(obj));
2357
2358   { MaybeObject* maybe_obj =
2359         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2360     if (!maybe_obj->ToObject(&obj)) return false;
2361   }
2362   set_catch_context_map(Map::cast(obj));
2363
2364   { MaybeObject* maybe_obj =
2365         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2366     if (!maybe_obj->ToObject(&obj)) return false;
2367   }
2368   set_with_context_map(Map::cast(obj));
2369
2370   { MaybeObject* maybe_obj =
2371         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2372     if (!maybe_obj->ToObject(&obj)) return false;
2373   }
2374   set_block_context_map(Map::cast(obj));
2375
2376   { MaybeObject* maybe_obj =
2377         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2378     if (!maybe_obj->ToObject(&obj)) return false;
2379   }
2380   set_module_context_map(Map::cast(obj));
2381
2382   { MaybeObject* maybe_obj =
2383         AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
2384     if (!maybe_obj->ToObject(&obj)) return false;
2385   }
2386   Map* global_context_map = Map::cast(obj);
2387   global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
2388   set_global_context_map(global_context_map);
2389
2390   { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
2391                                          SharedFunctionInfo::kAlignedSize);
2392     if (!maybe_obj->ToObject(&obj)) return false;
2393   }
2394   set_shared_function_info_map(Map::cast(obj));
2395
2396   { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
2397                                          JSMessageObject::kSize);
2398     if (!maybe_obj->ToObject(&obj)) return false;
2399   }
2400   set_message_object_map(Map::cast(obj));
2401
2402   ASSERT(!InNewSpace(empty_fixed_array()));
2403   return true;
2404 }
2405
2406
2407 MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
2408   // Statically ensure that it is safe to allocate heap numbers in paged
2409   // spaces.
2410   STATIC_ASSERT(HeapNumber::kSize <= Page::kNonCodeObjectAreaSize);
2411   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2412
2413   Object* result;
2414   { MaybeObject* maybe_result =
2415         AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
2416     if (!maybe_result->ToObject(&result)) return maybe_result;
2417   }
2418
2419   HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2420   HeapNumber::cast(result)->set_value(value);
2421   return result;
2422 }
2423
2424
2425 MaybeObject* Heap::AllocateHeapNumber(double value) {
2426   // Use general version, if we're forced to always allocate.
2427   if (always_allocate()) return AllocateHeapNumber(value, TENURED);
2428
2429   // This version of AllocateHeapNumber is optimized for
2430   // allocation in new space.
2431   STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxNonCodeHeapObjectSize);
2432   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2433   Object* result;
2434   { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
2435     if (!maybe_result->ToObject(&result)) return maybe_result;
2436   }
2437   HeapObject::cast(result)->set_map_no_write_barrier(heap_number_map());
2438   HeapNumber::cast(result)->set_value(value);
2439   return result;
2440 }
2441
2442
2443 MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
2444   Object* result;
2445   { MaybeObject* maybe_result = AllocateRawCell();
2446     if (!maybe_result->ToObject(&result)) return maybe_result;
2447   }
2448   HeapObject::cast(result)->set_map_no_write_barrier(
2449       global_property_cell_map());
2450   JSGlobalPropertyCell::cast(result)->set_value(value);
2451   return result;
2452 }
2453
2454
2455 MaybeObject* Heap::CreateOddball(const char* to_string,
2456                                  Object* to_number,
2457                                  byte kind) {
2458   Object* result;
2459   { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_POINTER_SPACE);
2460     if (!maybe_result->ToObject(&result)) return maybe_result;
2461   }
2462   return Oddball::cast(result)->Initialize(to_string, to_number, kind);
2463 }
2464
2465
2466 bool Heap::CreateApiObjects() {
2467   Object* obj;
2468
2469   { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2470     if (!maybe_obj->ToObject(&obj)) return false;
2471   }
2472   // Don't use Smi-only elements optimizations for objects with the neander
2473   // map. There are too many cases where element values are set directly with a
2474   // bottleneck to trap the Smi-only -> fast elements transition, and there
2475   // appears to be no benefit for optimize this case.
2476   Map* new_neander_map = Map::cast(obj);
2477   new_neander_map->set_elements_kind(TERMINAL_FAST_ELEMENTS_KIND);
2478   set_neander_map(new_neander_map);
2479
2480   { MaybeObject* maybe_obj = AllocateJSObjectFromMap(neander_map());
2481     if (!maybe_obj->ToObject(&obj)) return false;
2482   }
2483   Object* elements;
2484   { MaybeObject* maybe_elements = AllocateFixedArray(2);
2485     if (!maybe_elements->ToObject(&elements)) return false;
2486   }
2487   FixedArray::cast(elements)->set(0, Smi::FromInt(0));
2488   JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
2489   set_message_listeners(JSObject::cast(obj));
2490
2491   return true;
2492 }
2493
2494
2495 void Heap::CreateJSEntryStub() {
2496   JSEntryStub stub;
2497   set_js_entry_code(*stub.GetCode());
2498 }
2499
2500
2501 void Heap::CreateJSConstructEntryStub() {
2502   JSConstructEntryStub stub;
2503   set_js_construct_entry_code(*stub.GetCode());
2504 }
2505
2506
2507 void Heap::CreateFixedStubs() {
2508   // Here we create roots for fixed stubs. They are needed at GC
2509   // for cooking and uncooking (check out frames.cc).
2510   // The eliminates the need for doing dictionary lookup in the
2511   // stub cache for these stubs.
2512   HandleScope scope;
2513   // gcc-4.4 has problem generating correct code of following snippet:
2514   // {  JSEntryStub stub;
2515   //    js_entry_code_ = *stub.GetCode();
2516   // }
2517   // {  JSConstructEntryStub stub;
2518   //    js_construct_entry_code_ = *stub.GetCode();
2519   // }
2520   // To workaround the problem, make separate functions without inlining.
2521   Heap::CreateJSEntryStub();
2522   Heap::CreateJSConstructEntryStub();
2523
2524   // Create stubs that should be there, so we don't unexpectedly have to
2525   // create them if we need them during the creation of another stub.
2526   // Stub creation mixes raw pointers and handles in an unsafe manner so
2527   // we cannot create stubs while we are creating stubs.
2528   CodeStub::GenerateStubsAheadOfTime();
2529 }
2530
2531
2532 bool Heap::CreateInitialObjects() {
2533   Object* obj;
2534
2535   // The -0 value must be set before NumberFromDouble works.
2536   { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
2537     if (!maybe_obj->ToObject(&obj)) return false;
2538   }
2539   set_minus_zero_value(HeapNumber::cast(obj));
2540   ASSERT(signbit(minus_zero_value()->Number()) != 0);
2541
2542   { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
2543     if (!maybe_obj->ToObject(&obj)) return false;
2544   }
2545   set_nan_value(HeapNumber::cast(obj));
2546
2547   { MaybeObject* maybe_obj = AllocateHeapNumber(V8_INFINITY, TENURED);
2548     if (!maybe_obj->ToObject(&obj)) return false;
2549   }
2550   set_infinity_value(HeapNumber::cast(obj));
2551
2552   // The hole has not been created yet, but we want to put something
2553   // predictable in the gaps in the symbol table, so lets make that Smi zero.
2554   set_the_hole_value(reinterpret_cast<Oddball*>(Smi::FromInt(0)));
2555
2556   // Allocate initial symbol table.
2557   { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
2558     if (!maybe_obj->ToObject(&obj)) return false;
2559   }
2560   // Don't use set_symbol_table() due to asserts.
2561   roots_[kSymbolTableRootIndex] = obj;
2562
2563   // Finish initializing oddballs after creating symboltable.
2564   { MaybeObject* maybe_obj =
2565         undefined_value()->Initialize("undefined",
2566                                       nan_value(),
2567                                       Oddball::kUndefined);
2568     if (!maybe_obj->ToObject(&obj)) return false;
2569   }
2570
2571   // Initialize the null_value.
2572   { MaybeObject* maybe_obj =
2573         null_value()->Initialize("null", Smi::FromInt(0), Oddball::kNull);
2574     if (!maybe_obj->ToObject(&obj)) return false;
2575   }
2576
2577   { MaybeObject* maybe_obj = CreateOddball("true",
2578                                            Smi::FromInt(1),
2579                                            Oddball::kTrue);
2580     if (!maybe_obj->ToObject(&obj)) return false;
2581   }
2582   set_true_value(Oddball::cast(obj));
2583
2584   { MaybeObject* maybe_obj = CreateOddball("false",
2585                                            Smi::FromInt(0),
2586                                            Oddball::kFalse);
2587     if (!maybe_obj->ToObject(&obj)) return false;
2588   }
2589   set_false_value(Oddball::cast(obj));
2590
2591   { MaybeObject* maybe_obj = CreateOddball("hole",
2592                                            Smi::FromInt(-1),
2593                                            Oddball::kTheHole);
2594     if (!maybe_obj->ToObject(&obj)) return false;
2595   }
2596   set_the_hole_value(Oddball::cast(obj));
2597
2598   { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2599                                            Smi::FromInt(-4),
2600                                            Oddball::kArgumentMarker);
2601     if (!maybe_obj->ToObject(&obj)) return false;
2602   }
2603   set_arguments_marker(Oddball::cast(obj));
2604
2605   { MaybeObject* maybe_obj = CreateOddball("no_interceptor_result_sentinel",
2606                                            Smi::FromInt(-2),
2607                                            Oddball::kOther);
2608     if (!maybe_obj->ToObject(&obj)) return false;
2609   }
2610   set_no_interceptor_result_sentinel(obj);
2611
2612   { MaybeObject* maybe_obj = CreateOddball("termination_exception",
2613                                            Smi::FromInt(-3),
2614                                            Oddball::kOther);
2615     if (!maybe_obj->ToObject(&obj)) return false;
2616   }
2617   set_termination_exception(obj);
2618
2619   // Allocate the empty string.
2620   { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2621     if (!maybe_obj->ToObject(&obj)) return false;
2622   }
2623   set_empty_string(String::cast(obj));
2624
2625   for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
2626     { MaybeObject* maybe_obj =
2627           LookupAsciiSymbol(constant_symbol_table[i].contents);
2628       if (!maybe_obj->ToObject(&obj)) return false;
2629     }
2630     roots_[constant_symbol_table[i].index] = String::cast(obj);
2631   }
2632
2633   // Allocate the hidden symbol which is used to identify the hidden properties
2634   // in JSObjects. The hash code has a special value so that it will not match
2635   // the empty string when searching for the property. It cannot be part of the
2636   // loop above because it needs to be allocated manually with the special
2637   // hash code in place. The hash code for the hidden_symbol is zero to ensure
2638   // that it will always be at the first entry in property descriptors.
2639   { MaybeObject* maybe_obj =
2640         AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2641     if (!maybe_obj->ToObject(&obj)) return false;
2642   }
2643   hidden_symbol_ = String::cast(obj);
2644
2645   // Allocate the foreign for __proto__.
2646   { MaybeObject* maybe_obj =
2647         AllocateForeign((Address) &Accessors::ObjectPrototype);
2648     if (!maybe_obj->ToObject(&obj)) return false;
2649   }
2650   set_prototype_accessors(Foreign::cast(obj));
2651
2652   // Allocate the code_stubs dictionary. The initial size is set to avoid
2653   // expanding the dictionary during bootstrapping.
2654   { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(128);
2655     if (!maybe_obj->ToObject(&obj)) return false;
2656   }
2657   set_code_stubs(UnseededNumberDictionary::cast(obj));
2658
2659
2660   // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2661   // is set to avoid expanding the dictionary during bootstrapping.
2662   { MaybeObject* maybe_obj = UnseededNumberDictionary::Allocate(64);
2663     if (!maybe_obj->ToObject(&obj)) return false;
2664   }
2665   set_non_monomorphic_cache(UnseededNumberDictionary::cast(obj));
2666
2667   { MaybeObject* maybe_obj = AllocatePolymorphicCodeCache();
2668     if (!maybe_obj->ToObject(&obj)) return false;
2669   }
2670   set_polymorphic_code_cache(PolymorphicCodeCache::cast(obj));
2671
2672   set_instanceof_cache_function(Smi::FromInt(0));
2673   set_instanceof_cache_map(Smi::FromInt(0));
2674   set_instanceof_cache_answer(Smi::FromInt(0));
2675
2676   CreateFixedStubs();
2677
2678   // Allocate the dictionary of intrinsic function names.
2679   { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2680     if (!maybe_obj->ToObject(&obj)) return false;
2681   }
2682   { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(this,
2683                                                                        obj);
2684     if (!maybe_obj->ToObject(&obj)) return false;
2685   }
2686   set_intrinsic_function_names(StringDictionary::cast(obj));
2687
2688   { MaybeObject* maybe_obj = AllocateInitialNumberStringCache();
2689     if (!maybe_obj->ToObject(&obj)) return false;
2690   }
2691   set_number_string_cache(FixedArray::cast(obj));
2692
2693   // Allocate cache for single character ASCII strings.
2694   { MaybeObject* maybe_obj =
2695         AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2696     if (!maybe_obj->ToObject(&obj)) return false;
2697   }
2698   set_single_character_string_cache(FixedArray::cast(obj));
2699
2700   // Allocate cache for string split.
2701   { MaybeObject* maybe_obj =
2702         AllocateFixedArray(StringSplitCache::kStringSplitCacheSize, TENURED);
2703     if (!maybe_obj->ToObject(&obj)) return false;
2704   }
2705   set_string_split_cache(FixedArray::cast(obj));
2706
2707   // Allocate cache for external strings pointing to native source code.
2708   { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2709     if (!maybe_obj->ToObject(&obj)) return false;
2710   }
2711   set_natives_source_cache(FixedArray::cast(obj));
2712
2713   // Handling of script id generation is in FACTORY->NewScript.
2714   set_last_script_id(undefined_value());
2715
2716   // Initialize keyed lookup cache.
2717   isolate_->keyed_lookup_cache()->Clear();
2718
2719   // Initialize context slot cache.
2720   isolate_->context_slot_cache()->Clear();
2721
2722   // Initialize descriptor cache.
2723   isolate_->descriptor_lookup_cache()->Clear();
2724
2725   // Initialize compilation cache.
2726   isolate_->compilation_cache()->Clear();
2727
2728   return true;
2729 }
2730
2731
2732 Object* StringSplitCache::Lookup(
2733     FixedArray* cache, String* string, String* pattern) {
2734   if (!string->IsSymbol() || !pattern->IsSymbol()) return Smi::FromInt(0);
2735   uint32_t hash = string->Hash();
2736   uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2737       ~(kArrayEntriesPerCacheEntry - 1));
2738   if (cache->get(index + kStringOffset) == string &&
2739       cache->get(index + kPatternOffset) == pattern) {
2740     return cache->get(index + kArrayOffset);
2741   }
2742   index = ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2743   if (cache->get(index + kStringOffset) == string &&
2744       cache->get(index + kPatternOffset) == pattern) {
2745     return cache->get(index + kArrayOffset);
2746   }
2747   return Smi::FromInt(0);
2748 }
2749
2750
2751 void StringSplitCache::Enter(Heap* heap,
2752                              FixedArray* cache,
2753                              String* string,
2754                              String* pattern,
2755                              FixedArray* array) {
2756   if (!string->IsSymbol() || !pattern->IsSymbol()) return;
2757   uint32_t hash = string->Hash();
2758   uint32_t index = ((hash & (kStringSplitCacheSize - 1)) &
2759       ~(kArrayEntriesPerCacheEntry - 1));
2760   if (cache->get(index + kStringOffset) == Smi::FromInt(0)) {
2761     cache->set(index + kStringOffset, string);
2762     cache->set(index + kPatternOffset, pattern);
2763     cache->set(index + kArrayOffset, array);
2764   } else {
2765     uint32_t index2 =
2766         ((index + kArrayEntriesPerCacheEntry) & (kStringSplitCacheSize - 1));
2767     if (cache->get(index2 + kStringOffset) == Smi::FromInt(0)) {
2768       cache->set(index2 + kStringOffset, string);
2769       cache->set(index2 + kPatternOffset, pattern);
2770       cache->set(index2 + kArrayOffset, array);
2771     } else {
2772       cache->set(index2 + kStringOffset, Smi::FromInt(0));
2773       cache->set(index2 + kPatternOffset, Smi::FromInt(0));
2774       cache->set(index2 + kArrayOffset, Smi::FromInt(0));
2775       cache->set(index + kStringOffset, string);
2776       cache->set(index + kPatternOffset, pattern);
2777       cache->set(index + kArrayOffset, array);
2778     }
2779   }
2780   if (array->length() < 100) {  // Limit how many new symbols we want to make.
2781     for (int i = 0; i < array->length(); i++) {
2782       String* str = String::cast(array->get(i));
2783       Object* symbol;
2784       MaybeObject* maybe_symbol = heap->LookupSymbol(str);
2785       if (maybe_symbol->ToObject(&symbol)) {
2786         array->set(i, symbol);
2787       }
2788     }
2789   }
2790   array->set_map_no_write_barrier(heap->fixed_cow_array_map());
2791 }
2792
2793
2794 void StringSplitCache::Clear(FixedArray* cache) {
2795   for (int i = 0; i < kStringSplitCacheSize; i++) {
2796     cache->set(i, Smi::FromInt(0));
2797   }
2798 }
2799
2800
2801 MaybeObject* Heap::AllocateInitialNumberStringCache() {
2802   MaybeObject* maybe_obj =
2803       AllocateFixedArray(kInitialNumberStringCacheSize * 2, TENURED);
2804   return maybe_obj;
2805 }
2806
2807
2808 int Heap::FullSizeNumberStringCacheLength() {
2809   // Compute the size of the number string cache based on the max newspace size.
2810   // The number string cache has a minimum size based on twice the initial cache
2811   // size to ensure that it is bigger after being made 'full size'.
2812   int number_string_cache_size = max_semispace_size_ / 512;
2813   number_string_cache_size = Max(kInitialNumberStringCacheSize * 2,
2814                                  Min(0x4000, number_string_cache_size));
2815   // There is a string and a number per entry so the length is twice the number
2816   // of entries.
2817   return number_string_cache_size * 2;
2818 }
2819
2820
2821 void Heap::AllocateFullSizeNumberStringCache() {
2822   // The idea is to have a small number string cache in the snapshot to keep
2823   // boot-time memory usage down.  If we expand the number string cache already
2824   // while creating the snapshot then that didn't work out.
2825   ASSERT(!Serializer::enabled());
2826   MaybeObject* maybe_obj =
2827       AllocateFixedArray(FullSizeNumberStringCacheLength(), TENURED);
2828   Object* new_cache;
2829   if (maybe_obj->ToObject(&new_cache)) {
2830     // We don't bother to repopulate the cache with entries from the old cache.
2831     // It will be repopulated soon enough with new strings.
2832     set_number_string_cache(FixedArray::cast(new_cache));
2833   }
2834   // If allocation fails then we just return without doing anything.  It is only
2835   // a cache, so best effort is OK here.
2836 }
2837
2838
2839 void Heap::FlushNumberStringCache() {
2840   // Flush the number to string cache.
2841   int len = number_string_cache()->length();
2842   for (int i = 0; i < len; i++) {
2843     number_string_cache()->set_undefined(this, i);
2844   }
2845 }
2846
2847
2848 static inline int double_get_hash(double d) {
2849   DoubleRepresentation rep(d);
2850   return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
2851 }
2852
2853
2854 static inline int smi_get_hash(Smi* smi) {
2855   return smi->value();
2856 }
2857
2858
2859 Object* Heap::GetNumberStringCache(Object* number) {
2860   int hash;
2861   int mask = (number_string_cache()->length() >> 1) - 1;
2862   if (number->IsSmi()) {
2863     hash = smi_get_hash(Smi::cast(number)) & mask;
2864   } else {
2865     hash = double_get_hash(number->Number()) & mask;
2866   }
2867   Object* key = number_string_cache()->get(hash * 2);
2868   if (key == number) {
2869     return String::cast(number_string_cache()->get(hash * 2 + 1));
2870   } else if (key->IsHeapNumber() &&
2871              number->IsHeapNumber() &&
2872              key->Number() == number->Number()) {
2873     return String::cast(number_string_cache()->get(hash * 2 + 1));
2874   }
2875   return undefined_value();
2876 }
2877
2878
2879 void Heap::SetNumberStringCache(Object* number, String* string) {
2880   int hash;
2881   int mask = (number_string_cache()->length() >> 1) - 1;
2882   if (number->IsSmi()) {
2883     hash = smi_get_hash(Smi::cast(number)) & mask;
2884   } else {
2885     hash = double_get_hash(number->Number()) & mask;
2886   }
2887   if (number_string_cache()->get(hash * 2) != undefined_value() &&
2888       number_string_cache()->length() != FullSizeNumberStringCacheLength()) {
2889     // The first time we have a hash collision, we move to the full sized
2890     // number string cache.
2891     AllocateFullSizeNumberStringCache();
2892     return;
2893   }
2894   number_string_cache()->set(hash * 2, number);
2895   number_string_cache()->set(hash * 2 + 1, string);
2896 }
2897
2898
2899 MaybeObject* Heap::NumberToString(Object* number,
2900                                   bool check_number_string_cache) {
2901   isolate_->counters()->number_to_string_runtime()->Increment();
2902   if (check_number_string_cache) {
2903     Object* cached = GetNumberStringCache(number);
2904     if (cached != undefined_value()) {
2905       return cached;
2906     }
2907   }
2908
2909   char arr[100];
2910   Vector<char> buffer(arr, ARRAY_SIZE(arr));
2911   const char* str;
2912   if (number->IsSmi()) {
2913     int num = Smi::cast(number)->value();
2914     str = IntToCString(num, buffer);
2915   } else {
2916     double num = HeapNumber::cast(number)->value();
2917     str = DoubleToCString(num, buffer);
2918   }
2919
2920   Object* js_string;
2921   MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2922   if (maybe_js_string->ToObject(&js_string)) {
2923     SetNumberStringCache(number, String::cast(js_string));
2924   }
2925   return maybe_js_string;
2926 }
2927
2928
2929 MaybeObject* Heap::Uint32ToString(uint32_t value,
2930                                   bool check_number_string_cache) {
2931   Object* number;
2932   MaybeObject* maybe = NumberFromUint32(value);
2933   if (!maybe->To<Object>(&number)) return maybe;
2934   return NumberToString(number, check_number_string_cache);
2935 }
2936
2937
2938 Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2939   return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2940 }
2941
2942
2943 Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2944     ExternalArrayType array_type) {
2945   switch (array_type) {
2946     case kExternalByteArray:
2947       return kExternalByteArrayMapRootIndex;
2948     case kExternalUnsignedByteArray:
2949       return kExternalUnsignedByteArrayMapRootIndex;
2950     case kExternalShortArray:
2951       return kExternalShortArrayMapRootIndex;
2952     case kExternalUnsignedShortArray:
2953       return kExternalUnsignedShortArrayMapRootIndex;
2954     case kExternalIntArray:
2955       return kExternalIntArrayMapRootIndex;
2956     case kExternalUnsignedIntArray:
2957       return kExternalUnsignedIntArrayMapRootIndex;
2958     case kExternalFloatArray:
2959       return kExternalFloatArrayMapRootIndex;
2960     case kExternalDoubleArray:
2961       return kExternalDoubleArrayMapRootIndex;
2962     case kExternalPixelArray:
2963       return kExternalPixelArrayMapRootIndex;
2964     default:
2965       UNREACHABLE();
2966       return kUndefinedValueRootIndex;
2967   }
2968 }
2969
2970
2971 MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
2972   // We need to distinguish the minus zero value and this cannot be
2973   // done after conversion to int. Doing this by comparing bit
2974   // patterns is faster than using fpclassify() et al.
2975   static const DoubleRepresentation minus_zero(-0.0);
2976
2977   DoubleRepresentation rep(value);
2978   if (rep.bits == minus_zero.bits) {
2979     return AllocateHeapNumber(-0.0, pretenure);
2980   }
2981
2982   int int_value = FastD2I(value);
2983   if (value == int_value && Smi::IsValid(int_value)) {
2984     return Smi::FromInt(int_value);
2985   }
2986
2987   // Materialize the value in the heap.
2988   return AllocateHeapNumber(value, pretenure);
2989 }
2990
2991
2992 MaybeObject* Heap::AllocateForeign(Address address, PretenureFlag pretenure) {
2993   // Statically ensure that it is safe to allocate foreigns in paged spaces.
2994   STATIC_ASSERT(Foreign::kSize <= Page::kMaxNonCodeHeapObjectSize);
2995   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2996   Foreign* result;
2997   MaybeObject* maybe_result = Allocate(foreign_map(), space);
2998   if (!maybe_result->To(&result)) return maybe_result;
2999   result->set_foreign_address(address);
3000   return result;
3001 }
3002
3003
3004 MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
3005   SharedFunctionInfo* share;
3006   MaybeObject* maybe = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
3007   if (!maybe->To<SharedFunctionInfo>(&share)) return maybe;
3008
3009   // Set pointer fields.
3010   share->set_name(name);
3011   Code* illegal = isolate_->builtins()->builtin(Builtins::kIllegal);
3012   share->set_code(illegal);
3013   share->set_scope_info(ScopeInfo::Empty());
3014   Code* construct_stub =
3015       isolate_->builtins()->builtin(Builtins::kJSConstructStubGeneric);
3016   share->set_construct_stub(construct_stub);
3017   share->set_instance_class_name(Object_symbol());
3018   share->set_function_data(undefined_value(), SKIP_WRITE_BARRIER);
3019   share->set_script(undefined_value(), SKIP_WRITE_BARRIER);
3020   share->set_debug_info(undefined_value(), SKIP_WRITE_BARRIER);
3021   share->set_inferred_name(empty_string(), SKIP_WRITE_BARRIER);
3022   share->set_initial_map(undefined_value(), SKIP_WRITE_BARRIER);
3023   share->set_this_property_assignments(undefined_value(), SKIP_WRITE_BARRIER);
3024   share->set_ast_node_count(0);
3025   share->set_stress_deopt_counter(FLAG_deopt_every_n_times);
3026   share->set_counters(0);
3027
3028   // Set integer fields (smi or int, depending on the architecture).
3029   share->set_length(0);
3030   share->set_formal_parameter_count(0);
3031   share->set_expected_nof_properties(0);
3032   share->set_num_literals(0);
3033   share->set_start_position_and_type(0);
3034   share->set_end_position(0);
3035   share->set_function_token_position(0);
3036   // All compiler hints default to false or 0.
3037   share->set_compiler_hints(0);
3038   share->set_this_property_assignments_count(0);
3039   share->set_opt_count(0);
3040
3041   return share;
3042 }
3043
3044
3045 MaybeObject* Heap::AllocateJSMessageObject(String* type,
3046                                            JSArray* arguments,
3047                                            int start_position,
3048                                            int end_position,
3049                                            Object* script,
3050                                            Object* stack_trace,
3051                                            Object* stack_frames) {
3052   Object* result;
3053   { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
3054     if (!maybe_result->ToObject(&result)) return maybe_result;
3055   }
3056   JSMessageObject* message = JSMessageObject::cast(result);
3057   message->set_properties(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3058   message->initialize_elements();
3059   message->set_elements(Heap::empty_fixed_array(), SKIP_WRITE_BARRIER);
3060   message->set_type(type);
3061   message->set_arguments(arguments);
3062   message->set_start_position(start_position);
3063   message->set_end_position(end_position);
3064   message->set_script(script);
3065   message->set_stack_trace(stack_trace);
3066   message->set_stack_frames(stack_frames);
3067   return result;
3068 }
3069
3070
3071
3072 // Returns true for a character in a range.  Both limits are inclusive.
3073 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
3074   // This makes uses of the the unsigned wraparound.
3075   return character - from <= to - from;
3076 }
3077
3078
3079 MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
3080     Heap* heap,
3081     uint32_t c1,
3082     uint32_t c2) {
3083   String* symbol;
3084   // Numeric strings have a different hash algorithm not known by
3085   // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
3086   if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
3087       heap->symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
3088     return symbol;
3089   // Now we know the length is 2, we might as well make use of that fact
3090   // when building the new string.
3091   } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) {  // We can do this
3092     ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1));  // because of this.
3093     Object* result;
3094     { MaybeObject* maybe_result = heap->AllocateRawAsciiString(2);
3095       if (!maybe_result->ToObject(&result)) return maybe_result;
3096     }
3097     char* dest = SeqAsciiString::cast(result)->GetChars();
3098     dest[0] = c1;
3099     dest[1] = c2;
3100     return result;
3101   } else {
3102     Object* result;
3103     { MaybeObject* maybe_result = heap->AllocateRawTwoByteString(2);
3104       if (!maybe_result->ToObject(&result)) return maybe_result;
3105     }
3106     uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3107     dest[0] = c1;
3108     dest[1] = c2;
3109     return result;
3110   }
3111 }
3112
3113
3114 MaybeObject* Heap::AllocateConsString(String* first, String* second) {
3115   int first_length = first->length();
3116   if (first_length == 0) {
3117     return second;
3118   }
3119
3120   int second_length = second->length();
3121   if (second_length == 0) {
3122     return first;
3123   }
3124
3125   int length = first_length + second_length;
3126
3127   // Optimization for 2-byte strings often used as keys in a decompression
3128   // dictionary.  Check whether we already have the string in the symbol
3129   // table to prevent creation of many unneccesary strings.
3130   if (length == 2) {
3131     unsigned c1 = first->Get(0);
3132     unsigned c2 = second->Get(0);
3133     return MakeOrFindTwoCharacterString(this, c1, c2);
3134   }
3135
3136   bool first_is_ascii = first->IsAsciiRepresentation();
3137   bool second_is_ascii = second->IsAsciiRepresentation();
3138   bool is_ascii = first_is_ascii && second_is_ascii;
3139
3140   // Make sure that an out of memory exception is thrown if the length
3141   // of the new cons string is too large.
3142   if (length > String::kMaxLength || length < 0) {
3143     isolate()->context()->mark_out_of_memory();
3144     return Failure::OutOfMemoryException();
3145   }
3146
3147   bool is_ascii_data_in_two_byte_string = false;
3148   if (!is_ascii) {
3149     // At least one of the strings uses two-byte representation so we
3150     // can't use the fast case code for short ASCII strings below, but
3151     // we can try to save memory if all chars actually fit in ASCII.
3152     is_ascii_data_in_two_byte_string =
3153         first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
3154     if (is_ascii_data_in_two_byte_string) {
3155       isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3156     }
3157   }
3158
3159   // If the resulting string is small make a flat string.
3160   if (length < ConsString::kMinLength) {
3161     // Note that neither of the two inputs can be a slice because:
3162     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
3163     ASSERT(first->IsFlat());
3164     ASSERT(second->IsFlat());
3165     if (is_ascii) {
3166       Object* result;
3167       { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3168         if (!maybe_result->ToObject(&result)) return maybe_result;
3169       }
3170       // Copy the characters into the new object.
3171       char* dest = SeqAsciiString::cast(result)->GetChars();
3172       // Copy first part.
3173       const char* src;
3174       if (first->IsExternalString()) {
3175         src = ExternalAsciiString::cast(first)->GetChars();
3176       } else {
3177         src = SeqAsciiString::cast(first)->GetChars();
3178       }
3179       for (int i = 0; i < first_length; i++) *dest++ = src[i];
3180       // Copy second part.
3181       if (second->IsExternalString()) {
3182         src = ExternalAsciiString::cast(second)->GetChars();
3183       } else {
3184         src = SeqAsciiString::cast(second)->GetChars();
3185       }
3186       for (int i = 0; i < second_length; i++) *dest++ = src[i];
3187       return result;
3188     } else {
3189       if (is_ascii_data_in_two_byte_string) {
3190         Object* result;
3191         { MaybeObject* maybe_result = AllocateRawAsciiString(length);
3192           if (!maybe_result->ToObject(&result)) return maybe_result;
3193         }
3194         // Copy the characters into the new object.
3195         char* dest = SeqAsciiString::cast(result)->GetChars();
3196         String::WriteToFlat(first, dest, 0, first_length);
3197         String::WriteToFlat(second, dest + first_length, 0, second_length);
3198         isolate_->counters()->string_add_runtime_ext_to_ascii()->Increment();
3199         return result;
3200       }
3201
3202       Object* result;
3203       { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
3204         if (!maybe_result->ToObject(&result)) return maybe_result;
3205       }
3206       // Copy the characters into the new object.
3207       uc16* dest = SeqTwoByteString::cast(result)->GetChars();
3208       String::WriteToFlat(first, dest, 0, first_length);
3209       String::WriteToFlat(second, dest + first_length, 0, second_length);
3210       return result;
3211     }
3212   }
3213
3214   Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
3215       cons_ascii_string_map() : cons_string_map();
3216
3217   Object* result;
3218   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3219     if (!maybe_result->ToObject(&result)) return maybe_result;
3220   }
3221
3222   AssertNoAllocation no_gc;
3223   ConsString* cons_string = ConsString::cast(result);
3224   WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
3225   cons_string->set_length(length);
3226   cons_string->set_hash_field(String::kEmptyHashField);
3227   cons_string->set_first(first, mode);
3228   cons_string->set_second(second, mode);
3229   return result;
3230 }
3231
3232
3233 MaybeObject* Heap::AllocateSubString(String* buffer,
3234                                      int start,
3235                                      int end,
3236                                      PretenureFlag pretenure) {
3237   int length = end - start;
3238   if (length <= 0) {
3239     return empty_string();
3240   } else if (length == 1) {
3241     return LookupSingleCharacterStringFromCode(buffer->Get(start));
3242   } else if (length == 2) {
3243     // Optimization for 2-byte strings often used as keys in a decompression
3244     // dictionary.  Check whether we already have the string in the symbol
3245     // table to prevent creation of many unneccesary strings.
3246     unsigned c1 = buffer->Get(start);
3247     unsigned c2 = buffer->Get(start + 1);
3248     return MakeOrFindTwoCharacterString(this, c1, c2);
3249   }
3250
3251   // Make an attempt to flatten the buffer to reduce access time.
3252   buffer = buffer->TryFlattenGetString();
3253
3254   if (!FLAG_string_slices ||
3255       !buffer->IsFlat() ||
3256       length < SlicedString::kMinLength ||
3257       pretenure == TENURED) {
3258     Object* result;
3259     // WriteToFlat takes care of the case when an indirect string has a
3260     // different encoding from its underlying string.  These encodings may
3261     // differ because of externalization.
3262     bool is_ascii = buffer->IsAsciiRepresentation();
3263     { MaybeObject* maybe_result = is_ascii
3264                                   ? AllocateRawAsciiString(length, pretenure)
3265                                   : AllocateRawTwoByteString(length, pretenure);
3266       if (!maybe_result->ToObject(&result)) return maybe_result;
3267     }
3268     String* string_result = String::cast(result);
3269     // Copy the characters into the new object.
3270     if (is_ascii) {
3271       ASSERT(string_result->IsAsciiRepresentation());
3272       char* dest = SeqAsciiString::cast(string_result)->GetChars();
3273       String::WriteToFlat(buffer, dest, start, end);
3274     } else {
3275       ASSERT(string_result->IsTwoByteRepresentation());
3276       uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
3277       String::WriteToFlat(buffer, dest, start, end);
3278     }
3279     return result;
3280   }
3281
3282   ASSERT(buffer->IsFlat());
3283 #if DEBUG
3284   if (FLAG_verify_heap) {
3285     buffer->StringVerify();
3286   }
3287 #endif
3288
3289   Object* result;
3290   // When slicing an indirect string we use its encoding for a newly created
3291   // slice and don't check the encoding of the underlying string.  This is safe
3292   // even if the encodings are different because of externalization.  If an
3293   // indirect ASCII string is pointing to a two-byte string, the two-byte char
3294   // codes of the underlying string must still fit into ASCII (because
3295   // externalization must not change char codes).
3296   { Map* map = buffer->IsAsciiRepresentation()
3297                  ? sliced_ascii_string_map()
3298                  : sliced_string_map();
3299     MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3300     if (!maybe_result->ToObject(&result)) return maybe_result;
3301   }
3302
3303   AssertNoAllocation no_gc;
3304   SlicedString* sliced_string = SlicedString::cast(result);
3305   sliced_string->set_length(length);
3306   sliced_string->set_hash_field(String::kEmptyHashField);
3307   if (buffer->IsConsString()) {
3308     ConsString* cons = ConsString::cast(buffer);
3309     ASSERT(cons->second()->length() == 0);
3310     sliced_string->set_parent(cons->first());
3311     sliced_string->set_offset(start);
3312   } else if (buffer->IsSlicedString()) {
3313     // Prevent nesting sliced strings.
3314     SlicedString* parent_slice = SlicedString::cast(buffer);
3315     sliced_string->set_parent(parent_slice->parent());
3316     sliced_string->set_offset(start + parent_slice->offset());
3317   } else {
3318     sliced_string->set_parent(buffer);
3319     sliced_string->set_offset(start);
3320   }
3321   ASSERT(sliced_string->parent()->IsSeqString() ||
3322          sliced_string->parent()->IsExternalString());
3323   return result;
3324 }
3325
3326
3327 MaybeObject* Heap::AllocateExternalStringFromAscii(
3328     const ExternalAsciiString::Resource* resource) {
3329   size_t length = resource->length();
3330   if (length > static_cast<size_t>(String::kMaxLength)) {
3331     isolate()->context()->mark_out_of_memory();
3332     return Failure::OutOfMemoryException();
3333   }
3334
3335   ASSERT(String::IsAscii(resource->data(), static_cast<int>(length)));
3336
3337   Map* map = external_ascii_string_map();
3338   Object* result;
3339   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3340     if (!maybe_result->ToObject(&result)) return maybe_result;
3341   }
3342
3343   ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
3344   external_string->set_length(static_cast<int>(length));
3345   external_string->set_hash_field(String::kEmptyHashField);
3346   external_string->set_resource(resource);
3347
3348   return result;
3349 }
3350
3351
3352 MaybeObject* Heap::AllocateExternalStringFromTwoByte(
3353     const ExternalTwoByteString::Resource* resource) {
3354   size_t length = resource->length();
3355   if (length > static_cast<size_t>(String::kMaxLength)) {
3356     isolate()->context()->mark_out_of_memory();
3357     return Failure::OutOfMemoryException();
3358   }
3359
3360   // For small strings we check whether the resource contains only
3361   // ASCII characters.  If yes, we use a different string map.
3362   static const size_t kAsciiCheckLengthLimit = 32;
3363   bool is_ascii = length <= kAsciiCheckLengthLimit &&
3364       String::IsAscii(resource->data(), static_cast<int>(length));
3365   Map* map = is_ascii ?
3366       external_string_with_ascii_data_map() : external_string_map();
3367   Object* result;
3368   { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
3369     if (!maybe_result->ToObject(&result)) return maybe_result;
3370   }
3371
3372   ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
3373   external_string->set_length(static_cast<int>(length));
3374   external_string->set_hash_field(String::kEmptyHashField);
3375   external_string->set_resource(resource);
3376
3377   return result;
3378 }
3379
3380
3381 MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
3382   if (code <= String::kMaxAsciiCharCode) {
3383     Object* value = single_character_string_cache()->get(code);
3384     if (value != undefined_value()) return value;
3385
3386     char buffer[1];
3387     buffer[0] = static_cast<char>(code);
3388     Object* result;
3389     MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
3390
3391     if (!maybe_result->ToObject(&result)) return maybe_result;
3392     single_character_string_cache()->set(code, result);
3393     return result;
3394   }
3395
3396   Object* result;
3397   { MaybeObject* maybe_result = AllocateRawTwoByteString(1);
3398     if (!maybe_result->ToObject(&result)) return maybe_result;
3399   }
3400   String* answer = String::cast(result);
3401   answer->Set(0, code);
3402   return answer;
3403 }
3404
3405
3406 MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
3407   if (length < 0 || length > ByteArray::kMaxLength) {
3408     return Failure::OutOfMemoryException();
3409   }
3410   if (pretenure == NOT_TENURED) {
3411     return AllocateByteArray(length);
3412   }
3413   int size = ByteArray::SizeFor(length);
3414   Object* result;
3415   { MaybeObject* maybe_result = (size <= Page::kMaxNonCodeHeapObjectSize)
3416                    ? old_data_space_->AllocateRaw(size)
3417                    : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
3418     if (!maybe_result->ToObject(&result)) return maybe_result;
3419   }
3420
3421   reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3422       byte_array_map());
3423   reinterpret_cast<ByteArray*>(result)->set_length(length);
3424   return result;
3425 }
3426
3427
3428 MaybeObject* Heap::AllocateByteArray(int length) {
3429   if (length < 0 || length > ByteArray::kMaxLength) {
3430     return Failure::OutOfMemoryException();
3431   }
3432   int size = ByteArray::SizeFor(length);
3433   AllocationSpace space =
3434       (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : NEW_SPACE;
3435   Object* result;
3436   { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
3437     if (!maybe_result->ToObject(&result)) return maybe_result;
3438   }
3439
3440   reinterpret_cast<ByteArray*>(result)->set_map_no_write_barrier(
3441       byte_array_map());
3442   reinterpret_cast<ByteArray*>(result)->set_length(length);
3443   return result;
3444 }
3445
3446
3447 void Heap::CreateFillerObjectAt(Address addr, int size) {
3448   if (size == 0) return;
3449   HeapObject* filler = HeapObject::FromAddress(addr);
3450   if (size == kPointerSize) {
3451     filler->set_map_no_write_barrier(one_pointer_filler_map());
3452   } else if (size == 2 * kPointerSize) {
3453     filler->set_map_no_write_barrier(two_pointer_filler_map());
3454   } else {
3455     filler->set_map_no_write_barrier(free_space_map());
3456     FreeSpace::cast(filler)->set_size(size);
3457   }
3458 }
3459
3460
3461 MaybeObject* Heap::AllocateExternalArray(int length,
3462                                          ExternalArrayType array_type,
3463                                          void* external_pointer,
3464                                          PretenureFlag pretenure) {
3465   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3466   Object* result;
3467   { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
3468                                             space,
3469                                             OLD_DATA_SPACE);
3470     if (!maybe_result->ToObject(&result)) return maybe_result;
3471   }
3472
3473   reinterpret_cast<ExternalArray*>(result)->set_map_no_write_barrier(
3474       MapForExternalArrayType(array_type));
3475   reinterpret_cast<ExternalArray*>(result)->set_length(length);
3476   reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
3477       external_pointer);
3478
3479   return result;
3480 }
3481
3482
3483 MaybeObject* Heap::CreateCode(const CodeDesc& desc,
3484                               Code::Flags flags,
3485                               Handle<Object> self_reference,
3486                               bool immovable) {
3487   // Allocate ByteArray before the Code object, so that we do not risk
3488   // leaving uninitialized Code object (and breaking the heap).
3489   ByteArray* reloc_info;
3490   MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
3491   if (!maybe_reloc_info->To(&reloc_info)) return maybe_reloc_info;
3492
3493   // Compute size.
3494   int body_size = RoundUp(desc.instr_size, kObjectAlignment);
3495   int obj_size = Code::SizeFor(body_size);
3496   ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
3497   MaybeObject* maybe_result;
3498   // Large code objects and code objects which should stay at a fixed address
3499   // are allocated in large object space.
3500   if (obj_size > code_space()->AreaSize() || immovable) {
3501     maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3502   } else {
3503     maybe_result = code_space_->AllocateRaw(obj_size);
3504   }
3505
3506   Object* result;
3507   if (!maybe_result->ToObject(&result)) return maybe_result;
3508
3509   // Initialize the object
3510   HeapObject::cast(result)->set_map_no_write_barrier(code_map());
3511   Code* code = Code::cast(result);
3512   ASSERT(!isolate_->code_range()->exists() ||
3513       isolate_->code_range()->contains(code->address()));
3514   code->set_instruction_size(desc.instr_size);
3515   code->set_relocation_info(reloc_info);
3516   code->set_flags(flags);
3517   if (code->is_call_stub() || code->is_keyed_call_stub()) {
3518     code->set_check_type(RECEIVER_MAP_CHECK);
3519   }
3520   code->set_deoptimization_data(empty_fixed_array(), SKIP_WRITE_BARRIER);
3521   code->set_type_feedback_info(undefined_value(), SKIP_WRITE_BARRIER);
3522   code->set_handler_table(empty_fixed_array(), SKIP_WRITE_BARRIER);
3523   code->set_gc_metadata(Smi::FromInt(0));
3524   code->set_ic_age(global_ic_age_);
3525   // Allow self references to created code object by patching the handle to
3526   // point to the newly allocated Code object.
3527   if (!self_reference.is_null()) {
3528     *(self_reference.location()) = code;
3529   }
3530   // Migrate generated code.
3531   // The generated code can contain Object** values (typically from handles)
3532   // that are dereferenced during the copy to point directly to the actual heap
3533   // objects. These pointers can include references to the code object itself,
3534   // through the self_reference parameter.
3535   code->CopyFrom(desc);
3536
3537 #ifdef DEBUG
3538   if (FLAG_verify_heap) {
3539     code->Verify();
3540   }
3541 #endif
3542   return code;
3543 }
3544
3545
3546 MaybeObject* Heap::CopyCode(Code* code) {
3547   // Allocate an object the same size as the code object.
3548   int obj_size = code->Size();
3549   MaybeObject* maybe_result;
3550   if (obj_size > code_space()->AreaSize()) {
3551     maybe_result = lo_space_->AllocateRaw(obj_size, EXECUTABLE);
3552   } else {
3553     maybe_result = code_space_->AllocateRaw(obj_size);
3554   }
3555
3556   Object* result;
3557   if (!maybe_result->ToObject(&result)) return maybe_result;
3558
3559   // Copy code object.
3560   Address old_addr = code->address();
3561   Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3562   CopyBlock(new_addr, old_addr, obj_size);
3563   // Relocate the copy.
3564   Code* new_code = Code::cast(result);
3565   ASSERT(!isolate_->code_range()->exists() ||
3566       isolate_->code_range()->contains(code->address()));
3567   new_code->Relocate(new_addr - old_addr);
3568   return new_code;
3569 }
3570
3571
3572 MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
3573   // Allocate ByteArray before the Code object, so that we do not risk
3574   // leaving uninitialized Code object (and breaking the heap).
3575   Object* reloc_info_array;
3576   { MaybeObject* maybe_reloc_info_array =
3577         AllocateByteArray(reloc_info.length(), TENURED);
3578     if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
3579       return maybe_reloc_info_array;
3580     }
3581   }
3582
3583   int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
3584
3585   int new_obj_size = Code::SizeFor(new_body_size);
3586
3587   Address old_addr = code->address();
3588
3589   size_t relocation_offset =
3590       static_cast<size_t>(code->instruction_end() - old_addr);
3591
3592   MaybeObject* maybe_result;
3593   if (new_obj_size > code_space()->AreaSize()) {
3594     maybe_result = lo_space_->AllocateRaw(new_obj_size, EXECUTABLE);
3595   } else {
3596     maybe_result = code_space_->AllocateRaw(new_obj_size);
3597   }
3598
3599   Object* result;
3600   if (!maybe_result->ToObject(&result)) return maybe_result;
3601
3602   // Copy code object.
3603   Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
3604
3605   // Copy header and instructions.
3606   memcpy(new_addr, old_addr, relocation_offset);
3607
3608   Code* new_code = Code::cast(result);
3609   new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
3610
3611   // Copy patched rinfo.
3612   memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
3613
3614   // Relocate the copy.
3615   ASSERT(!isolate_->code_range()->exists() ||
3616       isolate_->code_range()->contains(code->address()));
3617   new_code->Relocate(new_addr - old_addr);
3618
3619 #ifdef DEBUG
3620   if (FLAG_verify_heap) {
3621     code->Verify();
3622   }
3623 #endif
3624   return new_code;
3625 }
3626
3627
3628 MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
3629   ASSERT(gc_state_ == NOT_IN_GC);
3630   ASSERT(map->instance_type() != MAP_TYPE);
3631   // If allocation failures are disallowed, we may allocate in a different
3632   // space when new space is full and the object is not a large object.
3633   AllocationSpace retry_space =
3634       (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
3635   Object* result;
3636   { MaybeObject* maybe_result =
3637         AllocateRaw(map->instance_size(), space, retry_space);
3638     if (!maybe_result->ToObject(&result)) return maybe_result;
3639   }
3640   // No need for write barrier since object is white and map is in old space.
3641   HeapObject::cast(result)->set_map_no_write_barrier(map);
3642   return result;
3643 }
3644
3645
3646 void Heap::InitializeFunction(JSFunction* function,
3647                               SharedFunctionInfo* shared,
3648                               Object* prototype) {
3649   ASSERT(!prototype->IsMap());
3650   function->initialize_properties();
3651   function->initialize_elements();
3652   function->set_shared(shared);
3653   function->set_code(shared->code());
3654   function->set_prototype_or_initial_map(prototype);
3655   function->set_context(undefined_value());
3656   function->set_literals_or_bindings(empty_fixed_array());
3657   function->set_next_function_link(undefined_value());
3658 }
3659
3660
3661 MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
3662   // Allocate the prototype.  Make sure to use the object function
3663   // from the function's context, since the function can be from a
3664   // different context.
3665   JSFunction* object_function =
3666       function->context()->global_context()->object_function();
3667
3668   // Each function prototype gets a copy of the object function map.
3669   // This avoid unwanted sharing of maps between prototypes of different
3670   // constructors.
3671   Map* new_map;
3672   ASSERT(object_function->has_initial_map());
3673   { MaybeObject* maybe_map =
3674         object_function->initial_map()->CopyDropTransitions(
3675             DescriptorArray::MAY_BE_SHARED);
3676     if (!maybe_map->To<Map>(&new_map)) return maybe_map;
3677   }
3678   Object* prototype;
3679   { MaybeObject* maybe_prototype = AllocateJSObjectFromMap(new_map);
3680     if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3681   }
3682   // When creating the prototype for the function we must set its
3683   // constructor to the function.
3684   Object* result;
3685   { MaybeObject* maybe_result =
3686         JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
3687             constructor_symbol(), function, DONT_ENUM);
3688     if (!maybe_result->ToObject(&result)) return maybe_result;
3689   }
3690   return prototype;
3691 }
3692
3693
3694 MaybeObject* Heap::AllocateFunction(Map* function_map,
3695                                     SharedFunctionInfo* shared,
3696                                     Object* prototype,
3697                                     PretenureFlag pretenure) {
3698   AllocationSpace space =
3699       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3700   Object* result;
3701   { MaybeObject* maybe_result = Allocate(function_map, space);
3702     if (!maybe_result->ToObject(&result)) return maybe_result;
3703   }
3704   InitializeFunction(JSFunction::cast(result), shared, prototype);
3705   return result;
3706 }
3707
3708
3709 MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
3710   // To get fast allocation and map sharing for arguments objects we
3711   // allocate them based on an arguments boilerplate.
3712
3713   JSObject* boilerplate;
3714   int arguments_object_size;
3715   bool strict_mode_callee = callee->IsJSFunction() &&
3716       !JSFunction::cast(callee)->shared()->is_classic_mode();
3717   if (strict_mode_callee) {
3718     boilerplate =
3719         isolate()->context()->global_context()->
3720             strict_mode_arguments_boilerplate();
3721     arguments_object_size = kArgumentsObjectSizeStrict;
3722   } else {
3723     boilerplate =
3724         isolate()->context()->global_context()->arguments_boilerplate();
3725     arguments_object_size = kArgumentsObjectSize;
3726   }
3727
3728   // This calls Copy directly rather than using Heap::AllocateRaw so we
3729   // duplicate the check here.
3730   ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
3731
3732   // Check that the size of the boilerplate matches our
3733   // expectations. The ArgumentsAccessStub::GenerateNewObject relies
3734   // on the size being a known constant.
3735   ASSERT(arguments_object_size == boilerplate->map()->instance_size());
3736
3737   // Do the allocation.
3738   Object* result;
3739   { MaybeObject* maybe_result =
3740         AllocateRaw(arguments_object_size, NEW_SPACE, OLD_POINTER_SPACE);
3741     if (!maybe_result->ToObject(&result)) return maybe_result;
3742   }
3743
3744   // Copy the content. The arguments boilerplate doesn't have any
3745   // fields that point to new space so it's safe to skip the write
3746   // barrier here.
3747   CopyBlock(HeapObject::cast(result)->address(),
3748             boilerplate->address(),
3749             JSObject::kHeaderSize);
3750
3751   // Set the length property.
3752   JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsLengthIndex,
3753                                                 Smi::FromInt(length),
3754                                                 SKIP_WRITE_BARRIER);
3755   // Set the callee property for non-strict mode arguments object only.
3756   if (!strict_mode_callee) {
3757     JSObject::cast(result)->InObjectPropertyAtPut(kArgumentsCalleeIndex,
3758                                                   callee);
3759   }
3760
3761   // Check the state of the object
3762   ASSERT(JSObject::cast(result)->HasFastProperties());
3763   ASSERT(JSObject::cast(result)->HasFastObjectElements());
3764
3765   return result;
3766 }
3767
3768
3769 static bool HasDuplicates(DescriptorArray* descriptors) {
3770   int count = descriptors->number_of_descriptors();
3771   if (count > 1) {
3772     String* prev_key = descriptors->GetKey(0);
3773     for (int i = 1; i != count; i++) {
3774       String* current_key = descriptors->GetKey(i);
3775       if (prev_key == current_key) return true;
3776       prev_key = current_key;
3777     }
3778   }
3779   return false;
3780 }
3781
3782
3783 MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
3784   ASSERT(!fun->has_initial_map());
3785
3786   // First create a new map with the size and number of in-object properties
3787   // suggested by the function.
3788   int instance_size = fun->shared()->CalculateInstanceSize();
3789   int in_object_properties = fun->shared()->CalculateInObjectProperties();
3790   Object* map_obj;
3791   { MaybeObject* maybe_map_obj = AllocateMap(JS_OBJECT_TYPE, instance_size);
3792     if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3793   }
3794
3795   // Fetch or allocate prototype.
3796   Object* prototype;
3797   if (fun->has_instance_prototype()) {
3798     prototype = fun->instance_prototype();
3799   } else {
3800     { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3801       if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3802     }
3803   }
3804   Map* map = Map::cast(map_obj);
3805   map->set_inobject_properties(in_object_properties);
3806   map->set_unused_property_fields(in_object_properties);
3807   map->set_prototype(prototype);
3808   ASSERT(map->has_fast_object_elements());
3809
3810   // If the function has only simple this property assignments add
3811   // field descriptors for these to the initial map as the object
3812   // cannot be constructed without having these properties.  Guard by
3813   // the inline_new flag so we only change the map if we generate a
3814   // specialized construct stub.
3815   ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
3816   if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
3817     int count = fun->shared()->this_property_assignments_count();
3818     if (count > in_object_properties) {
3819       // Inline constructor can only handle inobject properties.
3820       fun->shared()->ForbidInlineConstructor();
3821     } else {
3822       DescriptorArray* descriptors;
3823       { MaybeObject* maybe_descriptors_obj =
3824             DescriptorArray::Allocate(count, DescriptorArray::MAY_BE_SHARED);
3825         if (!maybe_descriptors_obj->To<DescriptorArray>(&descriptors)) {
3826           return maybe_descriptors_obj;
3827         }
3828       }
3829       DescriptorArray::WhitenessWitness witness(descriptors);
3830       for (int i = 0; i < count; i++) {
3831         String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3832         ASSERT(name->IsSymbol());
3833         FieldDescriptor field(name, i, NONE);
3834         field.SetEnumerationIndex(i);
3835         descriptors->Set(i, &field, witness);
3836       }
3837       descriptors->SetNextEnumerationIndex(count);
3838       descriptors->SortUnchecked(witness);
3839
3840       // The descriptors may contain duplicates because the compiler does not
3841       // guarantee the uniqueness of property names (it would have required
3842       // quadratic time). Once the descriptors are sorted we can check for
3843       // duplicates in linear time.
3844       if (HasDuplicates(descriptors)) {
3845         fun->shared()->ForbidInlineConstructor();
3846       } else {
3847         map->set_instance_descriptors(descriptors);
3848         map->set_pre_allocated_property_fields(count);
3849         map->set_unused_property_fields(in_object_properties - count);
3850       }
3851     }
3852   }
3853
3854   fun->shared()->StartInobjectSlackTracking(map);
3855
3856   return map;
3857 }
3858
3859
3860 void Heap::InitializeJSObjectFromMap(JSObject* obj,
3861                                      FixedArray* properties,
3862                                      Map* map) {
3863   obj->set_properties(properties);
3864   obj->initialize_elements();
3865   // TODO(1240798): Initialize the object's body using valid initial values
3866   // according to the object's initial map.  For example, if the map's
3867   // instance type is JS_ARRAY_TYPE, the length field should be initialized
3868   // to a number (e.g. Smi::FromInt(0)) and the elements initialized to a
3869   // fixed array (e.g. Heap::empty_fixed_array()).  Currently, the object
3870   // verification code has to cope with (temporarily) invalid objects.  See
3871   // for example, JSArray::JSArrayVerify).
3872   Object* filler;
3873   // We cannot always fill with one_pointer_filler_map because objects
3874   // created from API functions expect their internal fields to be initialized
3875   // with undefined_value.
3876   // Pre-allocated fields need to be initialized with undefined_value as well
3877   // so that object accesses before the constructor completes (e.g. in the
3878   // debugger) will not cause a crash.
3879   if (map->constructor()->IsJSFunction() &&
3880       JSFunction::cast(map->constructor())->shared()->
3881           IsInobjectSlackTrackingInProgress()) {
3882     // We might want to shrink the object later.
3883     ASSERT(obj->GetInternalFieldCount() == 0);
3884     filler = Heap::one_pointer_filler_map();
3885   } else {
3886     filler = Heap::undefined_value();
3887   }
3888   obj->InitializeBody(map, Heap::undefined_value(), filler);
3889 }
3890
3891
3892 MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
3893   // JSFunctions should be allocated using AllocateFunction to be
3894   // properly initialized.
3895   ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3896
3897   // Both types of global objects should be allocated using
3898   // AllocateGlobalObject to be properly initialized.
3899   ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3900   ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3901
3902   // Allocate the backing storage for the properties.
3903   int prop_size =
3904       map->pre_allocated_property_fields() +
3905       map->unused_property_fields() -
3906       map->inobject_properties();
3907   ASSERT(prop_size >= 0);
3908   Object* properties;
3909   { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3910     if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3911   }
3912
3913   // Allocate the JSObject.
3914   AllocationSpace space =
3915       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3916   if (map->instance_size() > Page::kMaxNonCodeHeapObjectSize) space = LO_SPACE;
3917   Object* obj;
3918   { MaybeObject* maybe_obj = Allocate(map, space);
3919     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3920   }
3921
3922   // Initialize the JSObject.
3923   InitializeJSObjectFromMap(JSObject::cast(obj),
3924                             FixedArray::cast(properties),
3925                             map);
3926   ASSERT(JSObject::cast(obj)->HasFastSmiOrObjectElements());
3927   return obj;
3928 }
3929
3930
3931 MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3932                                     PretenureFlag pretenure) {
3933   // Allocate the initial map if absent.
3934   if (!constructor->has_initial_map()) {
3935     Object* initial_map;
3936     { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3937       if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3938     }
3939     constructor->set_initial_map(Map::cast(initial_map));
3940     Map::cast(initial_map)->set_constructor(constructor);
3941   }
3942   // Allocate the object based on the constructors initial map.
3943   MaybeObject* result = AllocateJSObjectFromMap(
3944       constructor->initial_map(), pretenure);
3945 #ifdef DEBUG
3946   // Make sure result is NOT a global object if valid.
3947   Object* non_failure;
3948   ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3949 #endif
3950   return result;
3951 }
3952
3953
3954 MaybeObject* Heap::AllocateJSModule() {
3955   // Allocate a fresh map. Modules do not have a prototype.
3956   Map* map;
3957   MaybeObject* maybe_map = AllocateMap(JS_MODULE_TYPE, JSModule::kSize);
3958   if (!maybe_map->To(&map)) return maybe_map;
3959   // Allocate the object based on the map.
3960   return AllocateJSObjectFromMap(map, TENURED);
3961 }
3962
3963
3964 MaybeObject* Heap::AllocateJSArrayAndStorage(
3965     ElementsKind elements_kind,
3966     int length,
3967     int capacity,
3968     ArrayStorageAllocationMode mode,
3969     PretenureFlag pretenure) {
3970   ASSERT(capacity >= length);
3971   if (length != 0 && mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE) {
3972     elements_kind = GetHoleyElementsKind(elements_kind);
3973   }
3974   MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
3975   JSArray* array;
3976   if (!maybe_array->To(&array)) return maybe_array;
3977
3978   if (capacity == 0) {
3979     array->set_length(Smi::FromInt(0));
3980     array->set_elements(empty_fixed_array());
3981     return array;
3982   }
3983
3984   FixedArrayBase* elms;
3985   MaybeObject* maybe_elms = NULL;
3986   if (elements_kind == FAST_DOUBLE_ELEMENTS) {
3987     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3988       maybe_elms = AllocateUninitializedFixedDoubleArray(capacity);
3989     } else {
3990       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3991       maybe_elms = AllocateFixedDoubleArrayWithHoles(capacity);
3992     }
3993   } else {
3994     ASSERT(IsFastSmiOrObjectElementsKind(elements_kind));
3995     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
3996       maybe_elms = AllocateUninitializedFixedArray(capacity);
3997     } else {
3998       ASSERT(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
3999       maybe_elms = AllocateFixedArrayWithHoles(capacity);
4000     }
4001   }
4002   if (!maybe_elms->To(&elms)) return maybe_elms;
4003
4004   array->set_elements(elms);
4005   array->set_length(Smi::FromInt(length));
4006   return array;
4007 }
4008
4009
4010 MaybeObject* Heap::AllocateJSArrayWithElements(
4011     FixedArrayBase* elements,
4012     ElementsKind elements_kind,
4013     PretenureFlag pretenure) {
4014   MaybeObject* maybe_array = AllocateJSArray(elements_kind, pretenure);
4015   JSArray* array;
4016   if (!maybe_array->To(&array)) return maybe_array;
4017
4018   array->set_elements(elements);
4019   array->set_length(Smi::FromInt(elements->length()));
4020   array->ValidateElements();
4021   return array;
4022 }
4023
4024
4025 MaybeObject* Heap::AllocateJSProxy(Object* handler, Object* prototype) {
4026   // Allocate map.
4027   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4028   // maps. Will probably depend on the identity of the handler object, too.
4029   Map* map;
4030   MaybeObject* maybe_map_obj = AllocateMap(JS_PROXY_TYPE, JSProxy::kSize);
4031   if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4032   map->set_prototype(prototype);
4033
4034   // Allocate the proxy object.
4035   JSProxy* result;
4036   MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4037   if (!maybe_result->To<JSProxy>(&result)) return maybe_result;
4038   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4039   result->set_handler(handler);
4040   result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4041   return result;
4042 }
4043
4044
4045 MaybeObject* Heap::AllocateJSFunctionProxy(Object* handler,
4046                                            Object* call_trap,
4047                                            Object* construct_trap,
4048                                            Object* prototype) {
4049   // Allocate map.
4050   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
4051   // maps. Will probably depend on the identity of the handler object, too.
4052   Map* map;
4053   MaybeObject* maybe_map_obj =
4054       AllocateMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
4055   if (!maybe_map_obj->To<Map>(&map)) return maybe_map_obj;
4056   map->set_prototype(prototype);
4057
4058   // Allocate the proxy object.
4059   JSFunctionProxy* result;
4060   MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
4061   if (!maybe_result->To<JSFunctionProxy>(&result)) return maybe_result;
4062   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
4063   result->set_handler(handler);
4064   result->set_hash(undefined_value(), SKIP_WRITE_BARRIER);
4065   result->set_call_trap(call_trap);
4066   result->set_construct_trap(construct_trap);
4067   return result;
4068 }
4069
4070
4071 MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
4072   ASSERT(constructor->has_initial_map());
4073   Map* map = constructor->initial_map();
4074
4075   // Make sure no field properties are described in the initial map.
4076   // This guarantees us that normalizing the properties does not
4077   // require us to change property values to JSGlobalPropertyCells.
4078   ASSERT(map->NextFreePropertyIndex() == 0);
4079
4080   // Make sure we don't have a ton of pre-allocated slots in the
4081   // global objects. They will be unused once we normalize the object.
4082   ASSERT(map->unused_property_fields() == 0);
4083   ASSERT(map->inobject_properties() == 0);
4084
4085   // Initial size of the backing store to avoid resize of the storage during
4086   // bootstrapping. The size differs between the JS global object ad the
4087   // builtins object.
4088   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
4089
4090   // Allocate a dictionary object for backing storage.
4091   Object* obj;
4092   { MaybeObject* maybe_obj =
4093         StringDictionary::Allocate(
4094             map->NumberOfDescribedProperties() * 2 + initial_size);
4095     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4096   }
4097   StringDictionary* dictionary = StringDictionary::cast(obj);
4098
4099   // The global object might be created from an object template with accessors.
4100   // Fill these accessors into the dictionary.
4101   DescriptorArray* descs = map->instance_descriptors();
4102   for (int i = 0; i < descs->number_of_descriptors(); i++) {
4103     PropertyDetails details = descs->GetDetails(i);
4104     ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
4105     PropertyDetails d =
4106         PropertyDetails(details.attributes(), CALLBACKS, details.index());
4107     Object* value = descs->GetCallbacksObject(i);
4108     { MaybeObject* maybe_value = AllocateJSGlobalPropertyCell(value);
4109       if (!maybe_value->ToObject(&value)) return maybe_value;
4110     }
4111
4112     Object* result;
4113     { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
4114       if (!maybe_result->ToObject(&result)) return maybe_result;
4115     }
4116     dictionary = StringDictionary::cast(result);
4117   }
4118
4119   // Allocate the global object and initialize it with the backing store.
4120   { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
4121     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4122   }
4123   JSObject* global = JSObject::cast(obj);
4124   InitializeJSObjectFromMap(global, dictionary, map);
4125
4126   // Create a new map for the global object.
4127   { MaybeObject* maybe_obj = map->CopyDropDescriptors();
4128     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4129   }
4130   Map* new_map = Map::cast(obj);
4131
4132   // Set up the global object as a normalized object.
4133   global->set_map(new_map);
4134   global->map()->clear_instance_descriptors();
4135   global->set_properties(dictionary);
4136
4137   // Make sure result is a global object with properties in dictionary.
4138   ASSERT(global->IsGlobalObject());
4139   ASSERT(!global->HasFastProperties());
4140   return global;
4141 }
4142
4143
4144 MaybeObject* Heap::CopyJSObject(JSObject* source) {
4145   // Never used to copy functions.  If functions need to be copied we
4146   // have to be careful to clear the literals array.
4147   SLOW_ASSERT(!source->IsJSFunction());
4148
4149   // Make the clone.
4150   Map* map = source->map();
4151   int object_size = map->instance_size();
4152   Object* clone;
4153
4154   WriteBarrierMode wb_mode = UPDATE_WRITE_BARRIER;
4155
4156   // If we're forced to always allocate, we use the general allocation
4157   // functions which may leave us with an object in old space.
4158   if (always_allocate()) {
4159     { MaybeObject* maybe_clone =
4160           AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
4161       if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4162     }
4163     Address clone_address = HeapObject::cast(clone)->address();
4164     CopyBlock(clone_address,
4165               source->address(),
4166               object_size);
4167     // Update write barrier for all fields that lie beyond the header.
4168     RecordWrites(clone_address,
4169                  JSObject::kHeaderSize,
4170                  (object_size - JSObject::kHeaderSize) / kPointerSize);
4171   } else {
4172     wb_mode = SKIP_WRITE_BARRIER;
4173     { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
4174       if (!maybe_clone->ToObject(&clone)) return maybe_clone;
4175     }
4176     SLOW_ASSERT(InNewSpace(clone));
4177     // Since we know the clone is allocated in new space, we can copy
4178     // the contents without worrying about updating the write barrier.
4179     CopyBlock(HeapObject::cast(clone)->address(),
4180               source->address(),
4181               object_size);
4182   }
4183
4184   SLOW_ASSERT(
4185       JSObject::cast(clone)->GetElementsKind() == source->GetElementsKind());
4186   FixedArrayBase* elements = FixedArrayBase::cast(source->elements());
4187   FixedArray* properties = FixedArray::cast(source->properties());
4188   // Update elements if necessary.
4189   if (elements->length() > 0) {
4190     Object* elem;
4191     { MaybeObject* maybe_elem;
4192       if (elements->map() == fixed_cow_array_map()) {
4193         maybe_elem = FixedArray::cast(elements);
4194       } else if (source->HasFastDoubleElements()) {
4195         maybe_elem = CopyFixedDoubleArray(FixedDoubleArray::cast(elements));
4196       } else {
4197         maybe_elem = CopyFixedArray(FixedArray::cast(elements));
4198       }
4199       if (!maybe_elem->ToObject(&elem)) return maybe_elem;
4200     }
4201     JSObject::cast(clone)->set_elements(FixedArrayBase::cast(elem), wb_mode);
4202   }
4203   // Update properties if necessary.
4204   if (properties->length() > 0) {
4205     Object* prop;
4206     { MaybeObject* maybe_prop = CopyFixedArray(properties);
4207       if (!maybe_prop->ToObject(&prop)) return maybe_prop;
4208     }
4209     JSObject::cast(clone)->set_properties(FixedArray::cast(prop), wb_mode);
4210   }
4211   // Return the new clone.
4212   return clone;
4213 }
4214
4215
4216 MaybeObject* Heap::ReinitializeJSReceiver(
4217     JSReceiver* object, InstanceType type, int size) {
4218   ASSERT(type >= FIRST_JS_OBJECT_TYPE);
4219
4220   // Allocate fresh map.
4221   // TODO(rossberg): Once we optimize proxies, cache these maps.
4222   Map* map;
4223   MaybeObject* maybe = AllocateMap(type, size);
4224   if (!maybe->To<Map>(&map)) return maybe;
4225
4226   // Check that the receiver has at least the size of the fresh object.
4227   int size_difference = object->map()->instance_size() - map->instance_size();
4228   ASSERT(size_difference >= 0);
4229
4230   map->set_prototype(object->map()->prototype());
4231
4232   // Allocate the backing storage for the properties.
4233   int prop_size = map->unused_property_fields() - map->inobject_properties();
4234   Object* properties;
4235   maybe = AllocateFixedArray(prop_size, TENURED);
4236   if (!maybe->ToObject(&properties)) return maybe;
4237
4238   // Functions require some allocation, which might fail here.
4239   SharedFunctionInfo* shared = NULL;
4240   if (type == JS_FUNCTION_TYPE) {
4241     String* name;
4242     maybe = LookupAsciiSymbol("<freezing call trap>");
4243     if (!maybe->To<String>(&name)) return maybe;
4244     maybe = AllocateSharedFunctionInfo(name);
4245     if (!maybe->To<SharedFunctionInfo>(&shared)) return maybe;
4246   }
4247
4248   // Because of possible retries of this function after failure,
4249   // we must NOT fail after this point, where we have changed the type!
4250
4251   // Reset the map for the object.
4252   object->set_map(map);
4253   JSObject* jsobj = JSObject::cast(object);
4254
4255   // Reinitialize the object from the constructor map.
4256   InitializeJSObjectFromMap(jsobj, FixedArray::cast(properties), map);
4257
4258   // Functions require some minimal initialization.
4259   if (type == JS_FUNCTION_TYPE) {
4260     map->set_function_with_prototype(true);
4261     InitializeFunction(JSFunction::cast(object), shared, the_hole_value());
4262     JSFunction::cast(object)->set_context(
4263         isolate()->context()->global_context());
4264   }
4265
4266   // Put in filler if the new object is smaller than the old.
4267   if (size_difference > 0) {
4268     CreateFillerObjectAt(
4269         object->address() + map->instance_size(), size_difference);
4270   }
4271
4272   return object;
4273 }
4274
4275
4276 MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
4277                                              JSGlobalProxy* object) {
4278   ASSERT(constructor->has_initial_map());
4279   Map* map = constructor->initial_map();
4280
4281   // Check that the already allocated object has the same size and type as
4282   // objects allocated using the constructor.
4283   ASSERT(map->instance_size() == object->map()->instance_size());
4284   ASSERT(map->instance_type() == object->map()->instance_type());
4285
4286   // Allocate the backing storage for the properties.
4287   int prop_size = map->unused_property_fields() - map->inobject_properties();
4288   Object* properties;
4289   { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
4290     if (!maybe_properties->ToObject(&properties)) return maybe_properties;
4291   }
4292
4293   // Reset the map for the object.
4294   object->set_map(constructor->initial_map());
4295
4296   // Reinitialize the object from the constructor map.
4297   InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
4298   return object;
4299 }
4300
4301
4302 MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
4303                                            PretenureFlag pretenure) {
4304   if (string.length() == 1) {
4305     return Heap::LookupSingleCharacterStringFromCode(string[0]);
4306   }
4307   Object* result;
4308   { MaybeObject* maybe_result =
4309         AllocateRawAsciiString(string.length(), pretenure);
4310     if (!maybe_result->ToObject(&result)) return maybe_result;
4311   }
4312
4313   // Copy the characters into the new object.
4314   SeqAsciiString* string_result = SeqAsciiString::cast(result);
4315   for (int i = 0; i < string.length(); i++) {
4316     string_result->SeqAsciiStringSet(i, string[i]);
4317   }
4318   return result;
4319 }
4320
4321
4322 MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
4323                                               PretenureFlag pretenure) {
4324   // Count the number of characters in the UTF-8 string and check if
4325   // it is an ASCII string.
4326   Access<UnicodeCache::Utf8Decoder>
4327       decoder(isolate_->unicode_cache()->utf8_decoder());
4328   decoder->Reset(string.start(), string.length());
4329   int chars = 0;
4330   while (decoder->has_more()) {
4331     uint32_t r = decoder->GetNext();
4332     if (r <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
4333       chars++;
4334     } else {
4335       chars += 2;
4336     }
4337   }
4338
4339   Object* result;
4340   { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
4341     if (!maybe_result->ToObject(&result)) return maybe_result;
4342   }
4343
4344   // Convert and copy the characters into the new object.
4345   String* string_result = String::cast(result);
4346   decoder->Reset(string.start(), string.length());
4347   int i = 0;
4348   while (i < chars) {
4349     uint32_t r = decoder->GetNext();
4350     if (r > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4351       string_result->Set(i++, unibrow::Utf16::LeadSurrogate(r));
4352       string_result->Set(i++, unibrow::Utf16::TrailSurrogate(r));
4353     } else {
4354       string_result->Set(i++, r);
4355     }
4356   }
4357   return result;
4358 }
4359
4360
4361 MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
4362                                              PretenureFlag pretenure) {
4363   // Check if the string is an ASCII string.
4364   MaybeObject* maybe_result;
4365   if (String::IsAscii(string.start(), string.length())) {
4366     maybe_result = AllocateRawAsciiString(string.length(), pretenure);
4367   } else {  // It's not an ASCII string.
4368     maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
4369   }
4370   Object* result;
4371   if (!maybe_result->ToObject(&result)) return maybe_result;
4372
4373   // Copy the characters into the new object, which may be either ASCII or
4374   // UTF-16.
4375   String* string_result = String::cast(result);
4376   for (int i = 0; i < string.length(); i++) {
4377     string_result->Set(i, string[i]);
4378   }
4379   return result;
4380 }
4381
4382
4383 Map* Heap::SymbolMapForString(String* string) {
4384   // If the string is in new space it cannot be used as a symbol.
4385   if (InNewSpace(string)) return NULL;
4386
4387   // Find the corresponding symbol map for strings.
4388   switch (string->map()->instance_type()) {
4389     case STRING_TYPE: return symbol_map();
4390     case ASCII_STRING_TYPE: return ascii_symbol_map();
4391     case CONS_STRING_TYPE: return cons_symbol_map();
4392     case CONS_ASCII_STRING_TYPE: return cons_ascii_symbol_map();
4393     case EXTERNAL_STRING_TYPE: return external_symbol_map();
4394     case EXTERNAL_ASCII_STRING_TYPE: return external_ascii_symbol_map();
4395     case EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4396       return external_symbol_with_ascii_data_map();
4397     case SHORT_EXTERNAL_STRING_TYPE: return short_external_symbol_map();
4398     case SHORT_EXTERNAL_ASCII_STRING_TYPE:
4399       return short_external_ascii_symbol_map();
4400     case SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE:
4401       return short_external_symbol_with_ascii_data_map();
4402     default: return NULL;  // No match found.
4403   }
4404 }
4405
4406
4407 MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
4408                                           int chars,
4409                                           uint32_t hash_field) {
4410   ASSERT(chars >= 0);
4411   // Ensure the chars matches the number of characters in the buffer.
4412   ASSERT(static_cast<unsigned>(chars) == buffer->Utf16Length());
4413   // Determine whether the string is ASCII.
4414   bool is_ascii = true;
4415   while (buffer->has_more()) {
4416     if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
4417       is_ascii = false;
4418       break;
4419     }
4420   }
4421   buffer->Rewind();
4422
4423   // Compute map and object size.
4424   int size;
4425   Map* map;
4426
4427   if (is_ascii) {
4428     if (chars > SeqAsciiString::kMaxLength) {
4429       return Failure::OutOfMemoryException();
4430     }
4431     map = ascii_symbol_map();
4432     size = SeqAsciiString::SizeFor(chars);
4433   } else {
4434     if (chars > SeqTwoByteString::kMaxLength) {
4435       return Failure::OutOfMemoryException();
4436     }
4437     map = symbol_map();
4438     size = SeqTwoByteString::SizeFor(chars);
4439   }
4440
4441   // Allocate string.
4442   Object* result;
4443   { MaybeObject* maybe_result = (size > Page::kMaxNonCodeHeapObjectSize)
4444                    ? lo_space_->AllocateRaw(size, NOT_EXECUTABLE)
4445                    : old_data_space_->AllocateRaw(size);
4446     if (!maybe_result->ToObject(&result)) return maybe_result;
4447   }
4448
4449   reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(map);
4450   // Set length and hash fields of the allocated string.
4451   String* answer = String::cast(result);
4452   answer->set_length(chars);
4453   answer->set_hash_field(hash_field);
4454
4455   ASSERT_EQ(size, answer->Size());
4456
4457   // Fill in the characters.
4458   int i = 0;
4459   while (i < chars) {
4460     uint32_t character = buffer->GetNext();
4461     if (character > unibrow::Utf16::kMaxNonSurrogateCharCode) {
4462       answer->Set(i++, unibrow::Utf16::LeadSurrogate(character));
4463       answer->Set(i++, unibrow::Utf16::TrailSurrogate(character));
4464     } else {
4465       answer->Set(i++, character);
4466     }
4467   }
4468   return answer;
4469 }
4470
4471
4472 MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
4473   if (length < 0 || length > SeqAsciiString::kMaxLength) {
4474     return Failure::OutOfMemoryException();
4475   }
4476
4477   int size = SeqAsciiString::SizeFor(length);
4478   ASSERT(size <= SeqAsciiString::kMaxSize);
4479
4480   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4481   AllocationSpace retry_space = OLD_DATA_SPACE;
4482
4483   if (space == NEW_SPACE) {
4484     if (size > kMaxObjectSizeInNewSpace) {
4485       // Allocate in large object space, retry space will be ignored.
4486       space = LO_SPACE;
4487     } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4488       // Allocate in new space, retry in large object space.
4489       retry_space = LO_SPACE;
4490     }
4491   } else if (space == OLD_DATA_SPACE &&
4492              size > Page::kMaxNonCodeHeapObjectSize) {
4493     space = LO_SPACE;
4494   }
4495   Object* result;
4496   { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4497     if (!maybe_result->ToObject(&result)) return maybe_result;
4498   }
4499
4500   // Partially initialize the object.
4501   HeapObject::cast(result)->set_map_no_write_barrier(ascii_string_map());
4502   String::cast(result)->set_length(length);
4503   String::cast(result)->set_hash_field(String::kEmptyHashField);
4504   ASSERT_EQ(size, HeapObject::cast(result)->Size());
4505
4506 #ifdef DEBUG
4507   if (FLAG_verify_heap) {
4508     // Initialize string's content to ensure ASCII-ness (character range 0-127)
4509     // as required when verifying the heap.
4510     char* dest = SeqAsciiString::cast(result)->GetChars();
4511     memset(dest, 0x0F, length * kCharSize);
4512   }
4513 #endif  // DEBUG
4514
4515   return result;
4516 }
4517
4518
4519 MaybeObject* Heap::AllocateRawTwoByteString(int length,
4520                                             PretenureFlag pretenure) {
4521   if (length < 0 || length > SeqTwoByteString::kMaxLength) {
4522     return Failure::OutOfMemoryException();
4523   }
4524   int size = SeqTwoByteString::SizeFor(length);
4525   ASSERT(size <= SeqTwoByteString::kMaxSize);
4526   AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4527   AllocationSpace retry_space = OLD_DATA_SPACE;
4528
4529   if (space == NEW_SPACE) {
4530     if (size > kMaxObjectSizeInNewSpace) {
4531       // Allocate in large object space, retry space will be ignored.
4532       space = LO_SPACE;
4533     } else if (size > Page::kMaxNonCodeHeapObjectSize) {
4534       // Allocate in new space, retry in large object space.
4535       retry_space = LO_SPACE;
4536     }
4537   } else if (space == OLD_DATA_SPACE &&
4538              size > Page::kMaxNonCodeHeapObjectSize) {
4539     space = LO_SPACE;
4540   }
4541   Object* result;
4542   { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
4543     if (!maybe_result->ToObject(&result)) return maybe_result;
4544   }
4545
4546   // Partially initialize the object.
4547   HeapObject::cast(result)->set_map_no_write_barrier(string_map());
4548   String::cast(result)->set_length(length);
4549   String::cast(result)->set_hash_field(String::kEmptyHashField);
4550   ASSERT_EQ(size, HeapObject::cast(result)->Size());
4551   return result;
4552 }
4553
4554
4555 MaybeObject* Heap::AllocateJSArray(
4556     ElementsKind elements_kind,
4557     PretenureFlag pretenure) {
4558   Context* global_context = isolate()->context()->global_context();
4559   JSFunction* array_function = global_context->array_function();
4560   Map* map = array_function->initial_map();
4561   Object* maybe_map_array = global_context->js_array_maps();
4562   if (!maybe_map_array->IsUndefined()) {
4563     Object* maybe_transitioned_map =
4564         FixedArray::cast(maybe_map_array)->get(elements_kind);
4565     if (!maybe_transitioned_map->IsUndefined()) {
4566       map = Map::cast(maybe_transitioned_map);
4567     }
4568   }
4569
4570   return AllocateJSObjectFromMap(map, pretenure);
4571 }
4572
4573
4574 MaybeObject* Heap::AllocateEmptyFixedArray() {
4575   int size = FixedArray::SizeFor(0);
4576   Object* result;
4577   { MaybeObject* maybe_result =
4578         AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4579     if (!maybe_result->ToObject(&result)) return maybe_result;
4580   }
4581   // Initialize the object.
4582   reinterpret_cast<FixedArray*>(result)->set_map_no_write_barrier(
4583       fixed_array_map());
4584   reinterpret_cast<FixedArray*>(result)->set_length(0);
4585   return result;
4586 }
4587
4588
4589 MaybeObject* Heap::AllocateRawFixedArray(int length) {
4590   if (length < 0 || length > FixedArray::kMaxLength) {
4591     return Failure::OutOfMemoryException();
4592   }
4593   ASSERT(length > 0);
4594   // Use the general function if we're forced to always allocate.
4595   if (always_allocate()) return AllocateFixedArray(length, TENURED);
4596   // Allocate the raw data for a fixed array.
4597   int size = FixedArray::SizeFor(length);
4598   return size <= kMaxObjectSizeInNewSpace
4599       ? new_space_.AllocateRaw(size)
4600       : lo_space_->AllocateRaw(size, NOT_EXECUTABLE);
4601 }
4602
4603
4604 MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
4605   int len = src->length();
4606   Object* obj;
4607   { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
4608     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4609   }
4610   if (InNewSpace(obj)) {
4611     HeapObject* dst = HeapObject::cast(obj);
4612     dst->set_map_no_write_barrier(map);
4613     CopyBlock(dst->address() + kPointerSize,
4614               src->address() + kPointerSize,
4615               FixedArray::SizeFor(len) - kPointerSize);
4616     return obj;
4617   }
4618   HeapObject::cast(obj)->set_map_no_write_barrier(map);
4619   FixedArray* result = FixedArray::cast(obj);
4620   result->set_length(len);
4621
4622   // Copy the content
4623   AssertNoAllocation no_gc;
4624   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
4625   for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
4626   return result;
4627 }
4628
4629
4630 MaybeObject* Heap::CopyFixedDoubleArrayWithMap(FixedDoubleArray* src,
4631                                                Map* map) {
4632   int len = src->length();
4633   Object* obj;
4634   { MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(len, NOT_TENURED);
4635     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4636   }
4637   HeapObject* dst = HeapObject::cast(obj);
4638   dst->set_map_no_write_barrier(map);
4639   CopyBlock(
4640       dst->address() + FixedDoubleArray::kLengthOffset,
4641       src->address() + FixedDoubleArray::kLengthOffset,
4642       FixedDoubleArray::SizeFor(len) - FixedDoubleArray::kLengthOffset);
4643   return obj;
4644 }
4645
4646
4647 MaybeObject* Heap::AllocateFixedArray(int length) {
4648   ASSERT(length >= 0);
4649   if (length == 0) return empty_fixed_array();
4650   Object* result;
4651   { MaybeObject* maybe_result = AllocateRawFixedArray(length);
4652     if (!maybe_result->ToObject(&result)) return maybe_result;
4653   }
4654   // Initialize header.
4655   FixedArray* array = reinterpret_cast<FixedArray*>(result);
4656   array->set_map_no_write_barrier(fixed_array_map());
4657   array->set_length(length);
4658   // Initialize body.
4659   ASSERT(!InNewSpace(undefined_value()));
4660   MemsetPointer(array->data_start(), undefined_value(), length);
4661   return result;
4662 }
4663
4664
4665 MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
4666   if (length < 0 || length > FixedArray::kMaxLength) {
4667     return Failure::OutOfMemoryException();
4668   }
4669
4670   AllocationSpace space =
4671       (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
4672   int size = FixedArray::SizeFor(length);
4673   if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4674     // Too big for new space.
4675     space = LO_SPACE;
4676   } else if (space == OLD_POINTER_SPACE &&
4677              size > Page::kMaxNonCodeHeapObjectSize) {
4678     // Too big for old pointer space.
4679     space = LO_SPACE;
4680   }
4681
4682   AllocationSpace retry_space =
4683       (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_POINTER_SPACE : LO_SPACE;
4684
4685   return AllocateRaw(size, space, retry_space);
4686 }
4687
4688
4689 MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
4690     Heap* heap,
4691     int length,
4692     PretenureFlag pretenure,
4693     Object* filler) {
4694   ASSERT(length >= 0);
4695   ASSERT(heap->empty_fixed_array()->IsFixedArray());
4696   if (length == 0) return heap->empty_fixed_array();
4697
4698   ASSERT(!heap->InNewSpace(filler));
4699   Object* result;
4700   { MaybeObject* maybe_result = heap->AllocateRawFixedArray(length, pretenure);
4701     if (!maybe_result->ToObject(&result)) return maybe_result;
4702   }
4703
4704   HeapObject::cast(result)->set_map_no_write_barrier(heap->fixed_array_map());
4705   FixedArray* array = FixedArray::cast(result);
4706   array->set_length(length);
4707   MemsetPointer(array->data_start(), filler, length);
4708   return array;
4709 }
4710
4711
4712 MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
4713   return AllocateFixedArrayWithFiller(this,
4714                                       length,
4715                                       pretenure,
4716                                       undefined_value());
4717 }
4718
4719
4720 MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
4721                                                PretenureFlag pretenure) {
4722   return AllocateFixedArrayWithFiller(this,
4723                                       length,
4724                                       pretenure,
4725                                       the_hole_value());
4726 }
4727
4728
4729 MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
4730   if (length == 0) return empty_fixed_array();
4731
4732   Object* obj;
4733   { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
4734     if (!maybe_obj->ToObject(&obj)) return maybe_obj;
4735   }
4736
4737   reinterpret_cast<FixedArray*>(obj)->set_map_no_write_barrier(
4738       fixed_array_map());
4739   FixedArray::cast(obj)->set_length(length);
4740   return obj;
4741 }
4742
4743
4744 MaybeObject* Heap::AllocateEmptyFixedDoubleArray() {
4745   int size = FixedDoubleArray::SizeFor(0);
4746   Object* result;
4747   { MaybeObject* maybe_result =
4748         AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
4749     if (!maybe_result->ToObject(&result)) return maybe_result;
4750   }
4751   // Initialize the object.
4752   reinterpret_cast<FixedDoubleArray*>(result)->set_map_no_write_barrier(
4753       fixed_double_array_map());
4754   reinterpret_cast<FixedDoubleArray*>(result)->set_length(0);
4755   return result;
4756 }
4757
4758
4759 MaybeObject* Heap::AllocateUninitializedFixedDoubleArray(
4760     int length,
4761     PretenureFlag pretenure) {
4762   if (length == 0) return empty_fixed_array();
4763
4764   Object* elements_object;
4765   MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4766   if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4767   FixedDoubleArray* elements =
4768       reinterpret_cast<FixedDoubleArray*>(elements_object);
4769
4770   elements->set_map_no_write_barrier(fixed_double_array_map());
4771   elements->set_length(length);
4772   return elements;
4773 }
4774
4775
4776 MaybeObject* Heap::AllocateFixedDoubleArrayWithHoles(
4777     int length,
4778     PretenureFlag pretenure) {
4779   if (length == 0) return empty_fixed_array();
4780
4781   Object* elements_object;
4782   MaybeObject* maybe_obj = AllocateRawFixedDoubleArray(length, pretenure);
4783   if (!maybe_obj->ToObject(&elements_object)) return maybe_obj;
4784   FixedDoubleArray* elements =
4785       reinterpret_cast<FixedDoubleArray*>(elements_object);
4786
4787   for (int i = 0; i < length; ++i) {
4788     elements->set_the_hole(i);
4789   }
4790
4791   elements->set_map_no_write_barrier(fixed_double_array_map());
4792   elements->set_length(length);
4793   return elements;
4794 }
4795
4796
4797 MaybeObject* Heap::AllocateRawFixedDoubleArray(int length,
4798                                                PretenureFlag pretenure) {
4799   if (length < 0 || length > FixedDoubleArray::kMaxLength) {
4800     return Failure::OutOfMemoryException();
4801   }
4802
4803   AllocationSpace space =
4804       (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
4805   int size = FixedDoubleArray::SizeFor(length);
4806
4807 #ifndef V8_HOST_ARCH_64_BIT
4808   size += kPointerSize;
4809 #endif
4810
4811   if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
4812     // Too big for new space.
4813     space = LO_SPACE;
4814   } else if (space == OLD_DATA_SPACE &&
4815              size > Page::kMaxNonCodeHeapObjectSize) {
4816     // Too big for old data space.
4817     space = LO_SPACE;
4818   }
4819
4820   AllocationSpace retry_space =
4821       (size <= Page::kMaxNonCodeHeapObjectSize) ? OLD_DATA_SPACE : LO_SPACE;
4822
4823   HeapObject* object;
4824   { MaybeObject* maybe_object = AllocateRaw(size, space, retry_space);
4825     if (!maybe_object->To<HeapObject>(&object)) return maybe_object;
4826   }
4827
4828   return EnsureDoubleAligned(this, object, size);
4829 }
4830
4831
4832 MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
4833   Object* result;
4834   { MaybeObject* maybe_result = AllocateFixedArray(length, pretenure);
4835     if (!maybe_result->ToObject(&result)) return maybe_result;
4836   }
4837   reinterpret_cast<HeapObject*>(result)->set_map_no_write_barrier(
4838       hash_table_map());
4839   ASSERT(result->IsHashTable());
4840   return result;
4841 }
4842
4843
4844 MaybeObject* Heap::AllocateGlobalContext() {
4845   Object* result;
4846   { MaybeObject* maybe_result =
4847         AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
4848     if (!maybe_result->ToObject(&result)) return maybe_result;
4849   }
4850   Context* context = reinterpret_cast<Context*>(result);
4851   context->set_map_no_write_barrier(global_context_map());
4852   context->set_js_array_maps(undefined_value());
4853   ASSERT(context->IsGlobalContext());
4854   ASSERT(result->IsContext());
4855   return result;
4856 }
4857
4858
4859 MaybeObject* Heap::AllocateModuleContext(Context* previous,
4860                                          ScopeInfo* scope_info) {
4861   Object* result;
4862   { MaybeObject* maybe_result =
4863         AllocateFixedArrayWithHoles(scope_info->ContextLength(), TENURED);
4864     if (!maybe_result->ToObject(&result)) return maybe_result;
4865   }
4866   Context* context = reinterpret_cast<Context*>(result);
4867   context->set_map_no_write_barrier(module_context_map());
4868   context->set_previous(previous);
4869   context->set_extension(scope_info);
4870   context->set_global(previous->global());
4871   return context;
4872 }
4873
4874
4875 MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
4876   ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
4877   Object* result;
4878   { MaybeObject* maybe_result = AllocateFixedArray(length);
4879     if (!maybe_result->ToObject(&result)) return maybe_result;
4880   }
4881   Context* context = reinterpret_cast<Context*>(result);
4882   context->set_map_no_write_barrier(function_context_map());
4883   context->set_closure(function);
4884   context->set_previous(function->context());
4885   context->set_extension(NULL);
4886   context->set_global(function->context()->global());
4887   return context;
4888 }
4889
4890
4891 MaybeObject* Heap::AllocateCatchContext(JSFunction* function,
4892                                         Context* previous,
4893                                         String* name,
4894                                         Object* thrown_object) {
4895   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
4896   Object* result;
4897   { MaybeObject* maybe_result =
4898         AllocateFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
4899     if (!maybe_result->ToObject(&result)) return maybe_result;
4900   }
4901   Context* context = reinterpret_cast<Context*>(result);
4902   context->set_map_no_write_barrier(catch_context_map());
4903   context->set_closure(function);
4904   context->set_previous(previous);
4905   context->set_extension(name);
4906   context->set_global(previous->global());
4907   context->set(Context::THROWN_OBJECT_INDEX, thrown_object);
4908   return context;
4909 }
4910
4911
4912 MaybeObject* Heap::AllocateWithContext(JSFunction* function,
4913                                        Context* previous,
4914                                        JSObject* extension) {
4915   Object* result;
4916   { MaybeObject* maybe_result = AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
4917     if (!maybe_result->ToObject(&result)) return maybe_result;
4918   }
4919   Context* context = reinterpret_cast<Context*>(result);
4920   context->set_map_no_write_barrier(with_context_map());
4921   context->set_closure(function);
4922   context->set_previous(previous);
4923   context->set_extension(extension);
4924   context->set_global(previous->global());
4925   return context;
4926 }
4927
4928
4929 MaybeObject* Heap::AllocateBlockContext(JSFunction* function,
4930                                         Context* previous,
4931                                         ScopeInfo* scope_info) {
4932   Object* result;
4933   { MaybeObject* maybe_result =
4934         AllocateFixedArrayWithHoles(scope_info->ContextLength());
4935     if (!maybe_result->ToObject(&result)) return maybe_result;
4936   }
4937   Context* context = reinterpret_cast<Context*>(result);
4938   context->set_map_no_write_barrier(block_context_map());
4939   context->set_closure(function);
4940   context->set_previous(previous);
4941   context->set_extension(scope_info);
4942   context->set_global(previous->global());
4943   return context;
4944 }
4945
4946
4947 MaybeObject* Heap::AllocateScopeInfo(int length) {
4948   FixedArray* scope_info;
4949   MaybeObject* maybe_scope_info = AllocateFixedArray(length, TENURED);
4950   if (!maybe_scope_info->To(&scope_info)) return maybe_scope_info;
4951   scope_info->set_map_no_write_barrier(scope_info_map());
4952   return scope_info;
4953 }
4954
4955
4956 MaybeObject* Heap::AllocateStruct(InstanceType type) {
4957   Map* map;
4958   switch (type) {
4959 #define MAKE_CASE(NAME, Name, name) \
4960     case NAME##_TYPE: map = name##_map(); break;
4961 STRUCT_LIST(MAKE_CASE)
4962 #undef MAKE_CASE
4963     default:
4964       UNREACHABLE();
4965       return Failure::InternalError();
4966   }
4967   int size = map->instance_size();
4968   AllocationSpace space =
4969       (size > Page::kMaxNonCodeHeapObjectSize) ? LO_SPACE : OLD_POINTER_SPACE;
4970   Object* result;
4971   { MaybeObject* maybe_result = Allocate(map, space);
4972     if (!maybe_result->ToObject(&result)) return maybe_result;
4973   }
4974   Struct::cast(result)->InitializeBody(size);
4975   return result;
4976 }
4977
4978
4979 bool Heap::IsHeapIterable() {
4980   return (!old_pointer_space()->was_swept_conservatively() &&
4981           !old_data_space()->was_swept_conservatively());
4982 }
4983
4984
4985 void Heap::EnsureHeapIsIterable() {
4986   ASSERT(IsAllocationAllowed());
4987   if (!IsHeapIterable()) {
4988     CollectAllGarbage(kMakeHeapIterableMask, "Heap::EnsureHeapIsIterable");
4989   }
4990   ASSERT(IsHeapIterable());
4991 }
4992
4993
4994 void Heap::AdvanceIdleIncrementalMarking(intptr_t step_size) {
4995   incremental_marking()->Step(step_size,
4996                               IncrementalMarking::NO_GC_VIA_STACK_GUARD);
4997
4998   if (incremental_marking()->IsComplete()) {
4999     bool uncommit = false;
5000     if (gc_count_at_last_idle_gc_ == gc_count_) {
5001       // No GC since the last full GC, the mutator is probably not active.
5002       isolate_->compilation_cache()->Clear();
5003       uncommit = true;
5004     }
5005     CollectAllGarbage(kNoGCFlags, "idle notification: finalize incremental");
5006     gc_count_at_last_idle_gc_ = gc_count_;
5007     if (uncommit) {
5008       new_space_.Shrink();
5009       UncommitFromSpace();
5010     }
5011   }
5012 }
5013
5014
5015 bool Heap::IdleNotification(int hint) {
5016   // Hints greater than this value indicate that
5017   // the embedder is requesting a lot of GC work.
5018   const int kMaxHint = 1000;
5019   // Minimal hint that allows to do full GC.
5020   const int kMinHintForFullGC = 100;
5021   intptr_t size_factor = Min(Max(hint, 20), kMaxHint) / 4;
5022   // The size factor is in range [5..250]. The numbers here are chosen from
5023   // experiments. If you changes them, make sure to test with
5024   // chrome/performance_ui_tests --gtest_filter="GeneralMixMemoryTest.*
5025   intptr_t step_size = size_factor * IncrementalMarking::kAllocatedThreshold;
5026
5027   if (contexts_disposed_ > 0) {
5028     if (hint >= kMaxHint) {
5029       // The embedder is requesting a lot of GC work after context disposal,
5030       // we age inline caches so that they don't keep objects from
5031       // the old context alive.
5032       AgeInlineCaches();
5033     }
5034     int mark_sweep_time = Min(TimeMarkSweepWouldTakeInMs(), 1000);
5035     if (hint >= mark_sweep_time && !FLAG_expose_gc &&
5036         incremental_marking()->IsStopped()) {
5037       HistogramTimerScope scope(isolate_->counters()->gc_context());
5038       CollectAllGarbage(kReduceMemoryFootprintMask,
5039                         "idle notification: contexts disposed");
5040     } else {
5041       AdvanceIdleIncrementalMarking(step_size);
5042       contexts_disposed_ = 0;
5043     }
5044     // Make sure that we have no pending context disposals.
5045     // Take into account that we might have decided to delay full collection
5046     // because incremental marking is in progress.
5047     ASSERT((contexts_disposed_ == 0) || !incremental_marking()->IsStopped());
5048     // After context disposal there is likely a lot of garbage remaining, reset
5049     // the idle notification counters in order to trigger more incremental GCs
5050     // on subsequent idle notifications.
5051     StartIdleRound();
5052     return false;
5053   }
5054
5055   if (!FLAG_incremental_marking || FLAG_expose_gc || Serializer::enabled()) {
5056     return IdleGlobalGC();
5057   }
5058
5059   // By doing small chunks of GC work in each IdleNotification,
5060   // perform a round of incremental GCs and after that wait until
5061   // the mutator creates enough garbage to justify a new round.
5062   // An incremental GC progresses as follows:
5063   // 1. many incremental marking steps,
5064   // 2. one old space mark-sweep-compact,
5065   // 3. many lazy sweep steps.
5066   // Use mark-sweep-compact events to count incremental GCs in a round.
5067
5068
5069   if (incremental_marking()->IsStopped()) {
5070     if (!IsSweepingComplete() &&
5071         !AdvanceSweepers(static_cast<int>(step_size))) {
5072       return false;
5073     }
5074   }
5075
5076   if (mark_sweeps_since_idle_round_started_ >= kMaxMarkSweepsInIdleRound) {
5077     if (EnoughGarbageSinceLastIdleRound()) {
5078       StartIdleRound();
5079     } else {
5080       return true;
5081     }
5082   }
5083
5084   int new_mark_sweeps = ms_count_ - ms_count_at_last_idle_notification_;
5085   mark_sweeps_since_idle_round_started_ += new_mark_sweeps;
5086   ms_count_at_last_idle_notification_ = ms_count_;
5087
5088   int remaining_mark_sweeps = kMaxMarkSweepsInIdleRound -
5089                               mark_sweeps_since_idle_round_started_;
5090
5091   if (remaining_mark_sweeps <= 0) {
5092     FinishIdleRound();
5093     return true;
5094   }
5095
5096   if (incremental_marking()->IsStopped()) {
5097     // If there are no more than two GCs left in this idle round and we are
5098     // allowed to do a full GC, then make those GCs full in order to compact
5099     // the code space.
5100     // TODO(ulan): Once we enable code compaction for incremental marking,
5101     // we can get rid of this special case and always start incremental marking.
5102     if (remaining_mark_sweeps <= 2 && hint >= kMinHintForFullGC) {
5103       CollectAllGarbage(kReduceMemoryFootprintMask,
5104                         "idle notification: finalize idle round");
5105     } else {
5106       incremental_marking()->Start();
5107     }
5108   }
5109   if (!incremental_marking()->IsStopped()) {
5110     AdvanceIdleIncrementalMarking(step_size);
5111   }
5112   return false;
5113 }
5114
5115
5116 bool Heap::IdleGlobalGC() {
5117   static const int kIdlesBeforeScavenge = 4;
5118   static const int kIdlesBeforeMarkSweep = 7;
5119   static const int kIdlesBeforeMarkCompact = 8;
5120   static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
5121   static const unsigned int kGCsBetweenCleanup = 4;
5122
5123   if (!last_idle_notification_gc_count_init_) {
5124     last_idle_notification_gc_count_ = gc_count_;
5125     last_idle_notification_gc_count_init_ = true;
5126   }
5127
5128   bool uncommit = true;
5129   bool finished = false;
5130
5131   // Reset the number of idle notifications received when a number of
5132   // GCs have taken place. This allows another round of cleanup based
5133   // on idle notifications if enough work has been carried out to
5134   // provoke a number of garbage collections.
5135   if (gc_count_ - last_idle_notification_gc_count_ < kGCsBetweenCleanup) {
5136     number_idle_notifications_ =
5137         Min(number_idle_notifications_ + 1, kMaxIdleCount);
5138   } else {
5139     number_idle_notifications_ = 0;
5140     last_idle_notification_gc_count_ = gc_count_;
5141   }
5142
5143   if (number_idle_notifications_ == kIdlesBeforeScavenge) {
5144     CollectGarbage(NEW_SPACE, "idle notification");
5145     new_space_.Shrink();
5146     last_idle_notification_gc_count_ = gc_count_;
5147   } else if (number_idle_notifications_ == kIdlesBeforeMarkSweep) {
5148     // Before doing the mark-sweep collections we clear the
5149     // compilation cache to avoid hanging on to source code and
5150     // generated code for cached functions.
5151     isolate_->compilation_cache()->Clear();
5152
5153     CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5154     new_space_.Shrink();
5155     last_idle_notification_gc_count_ = gc_count_;
5156
5157   } else if (number_idle_notifications_ == kIdlesBeforeMarkCompact) {
5158     CollectAllGarbage(kReduceMemoryFootprintMask, "idle notification");
5159     new_space_.Shrink();
5160     last_idle_notification_gc_count_ = gc_count_;
5161     number_idle_notifications_ = 0;
5162     finished = true;
5163   } else if (number_idle_notifications_ > kIdlesBeforeMarkCompact) {
5164     // If we have received more than kIdlesBeforeMarkCompact idle
5165     // notifications we do not perform any cleanup because we don't
5166     // expect to gain much by doing so.
5167     finished = true;
5168   }
5169
5170   if (uncommit) UncommitFromSpace();
5171
5172   return finished;
5173 }
5174
5175
5176 #ifdef DEBUG
5177
5178 void Heap::Print() {
5179   if (!HasBeenSetUp()) return;
5180   isolate()->PrintStack();
5181   AllSpaces spaces;
5182   for (Space* space = spaces.next(); space != NULL; space = spaces.next())
5183     space->Print();
5184 }
5185
5186
5187 void Heap::ReportCodeStatistics(const char* title) {
5188   PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
5189   PagedSpace::ResetCodeStatistics();
5190   // We do not look for code in new space, map space, or old space.  If code
5191   // somehow ends up in those spaces, we would miss it here.
5192   code_space_->CollectCodeStatistics();
5193   lo_space_->CollectCodeStatistics();
5194   PagedSpace::ReportCodeStatistics();
5195 }
5196
5197
5198 // This function expects that NewSpace's allocated objects histogram is
5199 // populated (via a call to CollectStatistics or else as a side effect of a
5200 // just-completed scavenge collection).
5201 void Heap::ReportHeapStatistics(const char* title) {
5202   USE(title);
5203   PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
5204          title, gc_count_);
5205   PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
5206          old_gen_promotion_limit_);
5207   PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
5208          old_gen_allocation_limit_);
5209   PrintF("old_gen_limit_factor_ %d\n", old_gen_limit_factor_);
5210
5211   PrintF("\n");
5212   PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
5213   isolate_->global_handles()->PrintStats();
5214   PrintF("\n");
5215
5216   PrintF("Heap statistics : ");
5217   isolate_->memory_allocator()->ReportStatistics();
5218   PrintF("To space : ");
5219   new_space_.ReportStatistics();
5220   PrintF("Old pointer space : ");
5221   old_pointer_space_->ReportStatistics();
5222   PrintF("Old data space : ");
5223   old_data_space_->ReportStatistics();
5224   PrintF("Code space : ");
5225   code_space_->ReportStatistics();
5226   PrintF("Map space : ");
5227   map_space_->ReportStatistics();
5228   PrintF("Cell space : ");
5229   cell_space_->ReportStatistics();
5230   PrintF("Large object space : ");
5231   lo_space_->ReportStatistics();
5232   PrintF(">>>>>> ========================================= >>>>>>\n");
5233 }
5234
5235 #endif  // DEBUG
5236
5237 bool Heap::Contains(HeapObject* value) {
5238   return Contains(value->address());
5239 }
5240
5241
5242 bool Heap::Contains(Address addr) {
5243   if (OS::IsOutsideAllocatedSpace(addr)) return false;
5244   return HasBeenSetUp() &&
5245     (new_space_.ToSpaceContains(addr) ||
5246      old_pointer_space_->Contains(addr) ||
5247      old_data_space_->Contains(addr) ||
5248      code_space_->Contains(addr) ||
5249      map_space_->Contains(addr) ||
5250      cell_space_->Contains(addr) ||
5251      lo_space_->SlowContains(addr));
5252 }
5253
5254
5255 bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
5256   return InSpace(value->address(), space);
5257 }
5258
5259
5260 bool Heap::InSpace(Address addr, AllocationSpace space) {
5261   if (OS::IsOutsideAllocatedSpace(addr)) return false;
5262   if (!HasBeenSetUp()) return false;
5263
5264   switch (space) {
5265     case NEW_SPACE:
5266       return new_space_.ToSpaceContains(addr);
5267     case OLD_POINTER_SPACE:
5268       return old_pointer_space_->Contains(addr);
5269     case OLD_DATA_SPACE:
5270       return old_data_space_->Contains(addr);
5271     case CODE_SPACE:
5272       return code_space_->Contains(addr);
5273     case MAP_SPACE:
5274       return map_space_->Contains(addr);
5275     case CELL_SPACE:
5276       return cell_space_->Contains(addr);
5277     case LO_SPACE:
5278       return lo_space_->SlowContains(addr);
5279   }
5280
5281   return false;
5282 }
5283
5284
5285 #ifdef DEBUG
5286 void Heap::Verify() {
5287   ASSERT(HasBeenSetUp());
5288
5289   store_buffer()->Verify();
5290
5291   VerifyPointersVisitor visitor;
5292   IterateRoots(&visitor, VISIT_ONLY_STRONG);
5293
5294   new_space_.Verify();
5295
5296   old_pointer_space_->Verify(&visitor);
5297   map_space_->Verify(&visitor);
5298
5299   VerifyPointersVisitor no_dirty_regions_visitor;
5300   old_data_space_->Verify(&no_dirty_regions_visitor);
5301   code_space_->Verify(&no_dirty_regions_visitor);
5302   cell_space_->Verify(&no_dirty_regions_visitor);
5303
5304   lo_space_->Verify();
5305
5306   VerifyNoAccessorPairSharing();
5307 }
5308
5309
5310 void Heap::VerifyNoAccessorPairSharing() {
5311   // Verification is done in 2 phases: First we mark all AccessorPairs, checking
5312   // that we mark only unmarked pairs, then we clear all marks, restoring the
5313   // initial state. We use the Smi tag of the AccessorPair's getter as the
5314   // marking bit, because we can never see a Smi as the getter.
5315   for (int phase = 0; phase < 2; phase++) {
5316     HeapObjectIterator iter(map_space());
5317     for (HeapObject* obj = iter.Next(); obj != NULL; obj = iter.Next()) {
5318       if (obj->IsMap()) {
5319         DescriptorArray* descs = Map::cast(obj)->instance_descriptors();
5320         for (int i = 0; i < descs->number_of_descriptors(); i++) {
5321           if (descs->GetType(i) == CALLBACKS &&
5322               descs->GetValue(i)->IsAccessorPair()) {
5323             AccessorPair* accessors = AccessorPair::cast(descs->GetValue(i));
5324             uintptr_t before = reinterpret_cast<intptr_t>(accessors->getter());
5325             uintptr_t after = (phase == 0) ?
5326                 ((before & ~kSmiTagMask) | kSmiTag) :
5327                 ((before & ~kHeapObjectTag) | kHeapObjectTag);
5328             CHECK(before != after);
5329             accessors->set_getter(reinterpret_cast<Object*>(after));
5330           }
5331         }
5332       }
5333     }
5334   }
5335 }
5336 #endif  // DEBUG
5337
5338
5339 MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
5340   Object* symbol = NULL;
5341   Object* new_table;
5342   { MaybeObject* maybe_new_table =
5343         symbol_table()->LookupSymbol(string, &symbol);
5344     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5345   }
5346   // Can't use set_symbol_table because SymbolTable::cast knows that
5347   // SymbolTable is a singleton and checks for identity.
5348   roots_[kSymbolTableRootIndex] = new_table;
5349   ASSERT(symbol != NULL);
5350   return symbol;
5351 }
5352
5353
5354 MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
5355   Object* symbol = NULL;
5356   Object* new_table;
5357   { MaybeObject* maybe_new_table =
5358         symbol_table()->LookupAsciiSymbol(string, &symbol);
5359     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5360   }
5361   // Can't use set_symbol_table because SymbolTable::cast knows that
5362   // SymbolTable is a singleton and checks for identity.
5363   roots_[kSymbolTableRootIndex] = new_table;
5364   ASSERT(symbol != NULL);
5365   return symbol;
5366 }
5367
5368
5369 MaybeObject* Heap::LookupAsciiSymbol(Handle<SeqAsciiString> string,
5370                                      int from,
5371                                      int length) {
5372   Object* symbol = NULL;
5373   Object* new_table;
5374   { MaybeObject* maybe_new_table =
5375         symbol_table()->LookupSubStringAsciiSymbol(string,
5376                                                    from,
5377                                                    length,
5378                                                    &symbol);
5379     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5380   }
5381   // Can't use set_symbol_table because SymbolTable::cast knows that
5382   // SymbolTable is a singleton and checks for identity.
5383   roots_[kSymbolTableRootIndex] = new_table;
5384   ASSERT(symbol != NULL);
5385   return symbol;
5386 }
5387
5388
5389 MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
5390   Object* symbol = NULL;
5391   Object* new_table;
5392   { MaybeObject* maybe_new_table =
5393         symbol_table()->LookupTwoByteSymbol(string, &symbol);
5394     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5395   }
5396   // Can't use set_symbol_table because SymbolTable::cast knows that
5397   // SymbolTable is a singleton and checks for identity.
5398   roots_[kSymbolTableRootIndex] = new_table;
5399   ASSERT(symbol != NULL);
5400   return symbol;
5401 }
5402
5403
5404 MaybeObject* Heap::LookupSymbol(String* string) {
5405   if (string->IsSymbol()) return string;
5406   Object* symbol = NULL;
5407   Object* new_table;
5408   { MaybeObject* maybe_new_table =
5409         symbol_table()->LookupString(string, &symbol);
5410     if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
5411   }
5412   // Can't use set_symbol_table because SymbolTable::cast knows that
5413   // SymbolTable is a singleton and checks for identity.
5414   roots_[kSymbolTableRootIndex] = new_table;
5415   ASSERT(symbol != NULL);
5416   return symbol;
5417 }
5418
5419
5420 bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
5421   if (string->IsSymbol()) {
5422     *symbol = string;
5423     return true;
5424   }
5425   return symbol_table()->LookupSymbolIfExists(string, symbol);
5426 }
5427
5428
5429 #ifdef DEBUG
5430 void Heap::ZapFromSpace() {
5431   NewSpacePageIterator it(new_space_.FromSpaceStart(),
5432                           new_space_.FromSpaceEnd());
5433   while (it.has_next()) {
5434     NewSpacePage* page = it.next();
5435     for (Address cursor = page->area_start(), limit = page->area_end();
5436          cursor < limit;
5437          cursor += kPointerSize) {
5438       Memory::Address_at(cursor) = kFromSpaceZapValue;
5439     }
5440   }
5441 }
5442 #endif  // DEBUG
5443
5444
5445 void Heap::IterateAndMarkPointersToFromSpace(Address start,
5446                                              Address end,
5447                                              ObjectSlotCallback callback) {
5448   Address slot_address = start;
5449
5450   // We are not collecting slots on new space objects during mutation
5451   // thus we have to scan for pointers to evacuation candidates when we
5452   // promote objects. But we should not record any slots in non-black
5453   // objects. Grey object's slots would be rescanned.
5454   // White object might not survive until the end of collection
5455   // it would be a violation of the invariant to record it's slots.
5456   bool record_slots = false;
5457   if (incremental_marking()->IsCompacting()) {
5458     MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::FromAddress(start));
5459     record_slots = Marking::IsBlack(mark_bit);
5460   }
5461
5462   while (slot_address < end) {
5463     Object** slot = reinterpret_cast<Object**>(slot_address);
5464     Object* object = *slot;
5465     // If the store buffer becomes overfull we mark pages as being exempt from
5466     // the store buffer.  These pages are scanned to find pointers that point
5467     // to the new space.  In that case we may hit newly promoted objects and
5468     // fix the pointers before the promotion queue gets to them.  Thus the 'if'.
5469     if (object->IsHeapObject()) {
5470       if (Heap::InFromSpace(object)) {
5471         callback(reinterpret_cast<HeapObject**>(slot),
5472                  HeapObject::cast(object));
5473         Object* new_object = *slot;
5474         if (InNewSpace(new_object)) {
5475           SLOW_ASSERT(Heap::InToSpace(new_object));
5476           SLOW_ASSERT(new_object->IsHeapObject());
5477           store_buffer_.EnterDirectlyIntoStoreBuffer(
5478               reinterpret_cast<Address>(slot));
5479         }
5480         SLOW_ASSERT(!MarkCompactCollector::IsOnEvacuationCandidate(new_object));
5481       } else if (record_slots &&
5482                  MarkCompactCollector::IsOnEvacuationCandidate(object)) {
5483         mark_compact_collector()->RecordSlot(slot, slot, object);
5484       }
5485     }
5486     slot_address += kPointerSize;
5487   }
5488 }
5489
5490
5491 #ifdef DEBUG
5492 typedef bool (*CheckStoreBufferFilter)(Object** addr);
5493
5494
5495 bool IsAMapPointerAddress(Object** addr) {
5496   uintptr_t a = reinterpret_cast<uintptr_t>(addr);
5497   int mod = a % Map::kSize;
5498   return mod >= Map::kPointerFieldsBeginOffset &&
5499          mod < Map::kPointerFieldsEndOffset;
5500 }
5501
5502
5503 bool EverythingsAPointer(Object** addr) {
5504   return true;
5505 }
5506
5507
5508 static void CheckStoreBuffer(Heap* heap,
5509                              Object** current,
5510                              Object** limit,
5511                              Object**** store_buffer_position,
5512                              Object*** store_buffer_top,
5513                              CheckStoreBufferFilter filter,
5514                              Address special_garbage_start,
5515                              Address special_garbage_end) {
5516   Map* free_space_map = heap->free_space_map();
5517   for ( ; current < limit; current++) {
5518     Object* o = *current;
5519     Address current_address = reinterpret_cast<Address>(current);
5520     // Skip free space.
5521     if (o == free_space_map) {
5522       Address current_address = reinterpret_cast<Address>(current);
5523       FreeSpace* free_space =
5524           FreeSpace::cast(HeapObject::FromAddress(current_address));
5525       int skip = free_space->Size();
5526       ASSERT(current_address + skip <= reinterpret_cast<Address>(limit));
5527       ASSERT(skip > 0);
5528       current_address += skip - kPointerSize;
5529       current = reinterpret_cast<Object**>(current_address);
5530       continue;
5531     }
5532     // Skip the current linear allocation space between top and limit which is
5533     // unmarked with the free space map, but can contain junk.
5534     if (current_address == special_garbage_start &&
5535         special_garbage_end != special_garbage_start) {
5536       current_address = special_garbage_end - kPointerSize;
5537       current = reinterpret_cast<Object**>(current_address);
5538       continue;
5539     }
5540     if (!(*filter)(current)) continue;
5541     ASSERT(current_address < special_garbage_start ||
5542            current_address >= special_garbage_end);
5543     ASSERT(reinterpret_cast<uintptr_t>(o) != kFreeListZapValue);
5544     // We have to check that the pointer does not point into new space
5545     // without trying to cast it to a heap object since the hash field of
5546     // a string can contain values like 1 and 3 which are tagged null
5547     // pointers.
5548     if (!heap->InNewSpace(o)) continue;
5549     while (**store_buffer_position < current &&
5550            *store_buffer_position < store_buffer_top) {
5551       (*store_buffer_position)++;
5552     }
5553     if (**store_buffer_position != current ||
5554         *store_buffer_position == store_buffer_top) {
5555       Object** obj_start = current;
5556       while (!(*obj_start)->IsMap()) obj_start--;
5557       UNREACHABLE();
5558     }
5559   }
5560 }
5561
5562
5563 // Check that the store buffer contains all intergenerational pointers by
5564 // scanning a page and ensuring that all pointers to young space are in the
5565 // store buffer.
5566 void Heap::OldPointerSpaceCheckStoreBuffer() {
5567   OldSpace* space = old_pointer_space();
5568   PageIterator pages(space);
5569
5570   store_buffer()->SortUniq();
5571
5572   while (pages.has_next()) {
5573     Page* page = pages.next();
5574     Object** current = reinterpret_cast<Object**>(page->area_start());
5575
5576     Address end = page->area_end();
5577
5578     Object*** store_buffer_position = store_buffer()->Start();
5579     Object*** store_buffer_top = store_buffer()->Top();
5580
5581     Object** limit = reinterpret_cast<Object**>(end);
5582     CheckStoreBuffer(this,
5583                      current,
5584                      limit,
5585                      &store_buffer_position,
5586                      store_buffer_top,
5587                      &EverythingsAPointer,
5588                      space->top(),
5589                      space->limit());
5590   }
5591 }
5592
5593
5594 void Heap::MapSpaceCheckStoreBuffer() {
5595   MapSpace* space = map_space();
5596   PageIterator pages(space);
5597
5598   store_buffer()->SortUniq();
5599
5600   while (pages.has_next()) {
5601     Page* page = pages.next();
5602     Object** current = reinterpret_cast<Object**>(page->area_start());
5603
5604     Address end = page->area_end();
5605
5606     Object*** store_buffer_position = store_buffer()->Start();
5607     Object*** store_buffer_top = store_buffer()->Top();
5608
5609     Object** limit = reinterpret_cast<Object**>(end);
5610     CheckStoreBuffer(this,
5611                      current,
5612                      limit,
5613                      &store_buffer_position,
5614                      store_buffer_top,
5615                      &IsAMapPointerAddress,
5616                      space->top(),
5617                      space->limit());
5618   }
5619 }
5620
5621
5622 void Heap::LargeObjectSpaceCheckStoreBuffer() {
5623   LargeObjectIterator it(lo_space());
5624   for (HeapObject* object = it.Next(); object != NULL; object = it.Next()) {
5625     // We only have code, sequential strings, or fixed arrays in large
5626     // object space, and only fixed arrays can possibly contain pointers to
5627     // the young generation.
5628     if (object->IsFixedArray()) {
5629       Object*** store_buffer_position = store_buffer()->Start();
5630       Object*** store_buffer_top = store_buffer()->Top();
5631       Object** current = reinterpret_cast<Object**>(object->address());
5632       Object** limit =
5633           reinterpret_cast<Object**>(object->address() + object->Size());
5634       CheckStoreBuffer(this,
5635                        current,
5636                        limit,
5637                        &store_buffer_position,
5638                        store_buffer_top,
5639                        &EverythingsAPointer,
5640                        NULL,
5641                        NULL);
5642     }
5643   }
5644 }
5645 #endif
5646
5647
5648 void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
5649   IterateStrongRoots(v, mode);
5650   IterateWeakRoots(v, mode);
5651 }
5652
5653
5654 void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
5655   v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
5656   v->Synchronize(VisitorSynchronization::kSymbolTable);
5657   if (mode != VISIT_ALL_IN_SCAVENGE &&
5658       mode != VISIT_ALL_IN_SWEEP_NEWSPACE) {
5659     // Scavenge collections have special processing for this.
5660     external_string_table_.Iterate(v);
5661   }
5662   v->Synchronize(VisitorSynchronization::kExternalStringsTable);
5663 }
5664
5665
5666 void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
5667   v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
5668   v->Synchronize(VisitorSynchronization::kStrongRootList);
5669
5670   v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
5671   v->Synchronize(VisitorSynchronization::kSymbol);
5672
5673   isolate_->bootstrapper()->Iterate(v);
5674   v->Synchronize(VisitorSynchronization::kBootstrapper);
5675   isolate_->Iterate(v);
5676   v->Synchronize(VisitorSynchronization::kTop);
5677   Relocatable::Iterate(v);
5678   v->Synchronize(VisitorSynchronization::kRelocatable);
5679
5680 #ifdef ENABLE_DEBUGGER_SUPPORT
5681   isolate_->debug()->Iterate(v);
5682   if (isolate_->deoptimizer_data() != NULL) {
5683     isolate_->deoptimizer_data()->Iterate(v);
5684   }
5685 #endif
5686   v->Synchronize(VisitorSynchronization::kDebug);
5687   isolate_->compilation_cache()->Iterate(v);
5688   v->Synchronize(VisitorSynchronization::kCompilationCache);
5689
5690   // Iterate over local handles in handle scopes.
5691   isolate_->handle_scope_implementer()->Iterate(v);
5692   v->Synchronize(VisitorSynchronization::kHandleScope);
5693
5694   // Iterate over the builtin code objects and code stubs in the
5695   // heap. Note that it is not necessary to iterate over code objects
5696   // on scavenge collections.
5697   if (mode != VISIT_ALL_IN_SCAVENGE) {
5698     isolate_->builtins()->IterateBuiltins(v);
5699   }
5700   v->Synchronize(VisitorSynchronization::kBuiltins);
5701
5702   // Iterate over global handles.
5703   switch (mode) {
5704     case VISIT_ONLY_STRONG:
5705       isolate_->global_handles()->IterateStrongRoots(v);
5706       break;
5707     case VISIT_ALL_IN_SCAVENGE:
5708       isolate_->global_handles()->IterateNewSpaceStrongAndDependentRoots(v);
5709       break;
5710     case VISIT_ALL_IN_SWEEP_NEWSPACE:
5711     case VISIT_ALL:
5712       isolate_->global_handles()->IterateAllRoots(v);
5713       break;
5714   }
5715   v->Synchronize(VisitorSynchronization::kGlobalHandles);
5716
5717   // Iterate over pointers being held by inactive threads.
5718   isolate_->thread_manager()->Iterate(v);
5719   v->Synchronize(VisitorSynchronization::kThreadManager);
5720
5721   // Iterate over the pointers the Serialization/Deserialization code is
5722   // holding.
5723   // During garbage collection this keeps the partial snapshot cache alive.
5724   // During deserialization of the startup snapshot this creates the partial
5725   // snapshot cache and deserializes the objects it refers to.  During
5726   // serialization this does nothing, since the partial snapshot cache is
5727   // empty.  However the next thing we do is create the partial snapshot,
5728   // filling up the partial snapshot cache with objects it needs as we go.
5729   SerializerDeserializer::Iterate(v);
5730   // We don't do a v->Synchronize call here, because in debug mode that will
5731   // output a flag to the snapshot.  However at this point the serializer and
5732   // deserializer are deliberately a little unsynchronized (see above) so the
5733   // checking of the sync flag in the snapshot would fail.
5734 }
5735
5736
5737 // TODO(1236194): Since the heap size is configurable on the command line
5738 // and through the API, we should gracefully handle the case that the heap
5739 // size is not big enough to fit all the initial objects.
5740 bool Heap::ConfigureHeap(int max_semispace_size,
5741                          intptr_t max_old_gen_size,
5742                          intptr_t max_executable_size) {
5743   if (HasBeenSetUp()) return false;
5744
5745   if (FLAG_stress_compaction) {
5746     // This will cause more frequent GCs when stressing.
5747     max_semispace_size_ = Page::kPageSize;
5748   }
5749
5750   if (max_semispace_size > 0) {
5751     if (max_semispace_size < Page::kPageSize) {
5752       max_semispace_size = Page::kPageSize;
5753       if (FLAG_trace_gc) {
5754         PrintF("Max semispace size cannot be less than %dkbytes\n",
5755                Page::kPageSize >> 10);
5756       }
5757     }
5758     max_semispace_size_ = max_semispace_size;
5759   }
5760
5761   if (Snapshot::IsEnabled()) {
5762     // If we are using a snapshot we always reserve the default amount
5763     // of memory for each semispace because code in the snapshot has
5764     // write-barrier code that relies on the size and alignment of new
5765     // space.  We therefore cannot use a larger max semispace size
5766     // than the default reserved semispace size.
5767     if (max_semispace_size_ > reserved_semispace_size_) {
5768       max_semispace_size_ = reserved_semispace_size_;
5769       if (FLAG_trace_gc) {
5770         PrintF("Max semispace size cannot be more than %dkbytes\n",
5771                reserved_semispace_size_ >> 10);
5772       }
5773     }
5774   } else {
5775     // If we are not using snapshots we reserve space for the actual
5776     // max semispace size.
5777     reserved_semispace_size_ = max_semispace_size_;
5778   }
5779
5780   if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
5781   if (max_executable_size > 0) {
5782     max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
5783   }
5784
5785   // The max executable size must be less than or equal to the max old
5786   // generation size.
5787   if (max_executable_size_ > max_old_generation_size_) {
5788     max_executable_size_ = max_old_generation_size_;
5789   }
5790
5791   // The new space size must be a power of two to support single-bit testing
5792   // for containment.
5793   max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
5794   reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
5795   initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
5796   external_allocation_limit_ = 10 * max_semispace_size_;
5797
5798   // The old generation is paged and needs at least one page for each space.
5799   int paged_space_count = LAST_PAGED_SPACE - FIRST_PAGED_SPACE + 1;
5800   max_old_generation_size_ = Max(static_cast<intptr_t>(paged_space_count *
5801                                                        Page::kPageSize),
5802                                  RoundUp(max_old_generation_size_,
5803                                          Page::kPageSize));
5804
5805   configured_ = true;
5806   return true;
5807 }
5808
5809
5810 bool Heap::ConfigureHeapDefault() {
5811   return ConfigureHeap(static_cast<intptr_t>(FLAG_max_new_space_size / 2) * KB,
5812                        static_cast<intptr_t>(FLAG_max_old_space_size) * MB,
5813                        static_cast<intptr_t>(FLAG_max_executable_size) * MB);
5814 }
5815
5816
5817 void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
5818   *stats->start_marker = HeapStats::kStartMarker;
5819   *stats->end_marker = HeapStats::kEndMarker;
5820   *stats->new_space_size = new_space_.SizeAsInt();
5821   *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
5822   *stats->old_pointer_space_size = old_pointer_space_->SizeOfObjects();
5823   *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
5824   *stats->old_data_space_size = old_data_space_->SizeOfObjects();
5825   *stats->old_data_space_capacity = old_data_space_->Capacity();
5826   *stats->code_space_size = code_space_->SizeOfObjects();
5827   *stats->code_space_capacity = code_space_->Capacity();
5828   *stats->map_space_size = map_space_->SizeOfObjects();
5829   *stats->map_space_capacity = map_space_->Capacity();
5830   *stats->cell_space_size = cell_space_->SizeOfObjects();
5831   *stats->cell_space_capacity = cell_space_->Capacity();
5832   *stats->lo_space_size = lo_space_->Size();
5833   isolate_->global_handles()->RecordStats(stats);
5834   *stats->memory_allocator_size = isolate()->memory_allocator()->Size();
5835   *stats->memory_allocator_capacity =
5836       isolate()->memory_allocator()->Size() +
5837       isolate()->memory_allocator()->Available();
5838   *stats->os_error = OS::GetLastError();
5839       isolate()->memory_allocator()->Available();
5840   if (take_snapshot) {
5841     HeapIterator iterator;
5842     for (HeapObject* obj = iterator.next();
5843          obj != NULL;
5844          obj = iterator.next()) {
5845       InstanceType type = obj->map()->instance_type();
5846       ASSERT(0 <= type && type <= LAST_TYPE);
5847       stats->objects_per_type[type]++;
5848       stats->size_per_type[type] += obj->Size();
5849     }
5850   }
5851 }
5852
5853
5854 intptr_t Heap::PromotedSpaceSizeOfObjects() {
5855   return old_pointer_space_->SizeOfObjects()
5856       + old_data_space_->SizeOfObjects()
5857       + code_space_->SizeOfObjects()
5858       + map_space_->SizeOfObjects()
5859       + cell_space_->SizeOfObjects()
5860       + lo_space_->SizeOfObjects();
5861 }
5862
5863
5864 intptr_t Heap::PromotedExternalMemorySize() {
5865   if (amount_of_external_allocated_memory_
5866       <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
5867   return amount_of_external_allocated_memory_
5868       - amount_of_external_allocated_memory_at_last_global_gc_;
5869 }
5870
5871 #ifdef DEBUG
5872
5873 // Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
5874 static const int kMarkTag = 2;
5875
5876
5877 class HeapDebugUtils {
5878  public:
5879   explicit HeapDebugUtils(Heap* heap)
5880     : search_for_any_global_(false),
5881       search_target_(NULL),
5882       found_target_(false),
5883       object_stack_(20),
5884       heap_(heap) {
5885   }
5886
5887   class MarkObjectVisitor : public ObjectVisitor {
5888    public:
5889     explicit MarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5890
5891     void VisitPointers(Object** start, Object** end) {
5892       // Copy all HeapObject pointers in [start, end)
5893       for (Object** p = start; p < end; p++) {
5894         if ((*p)->IsHeapObject())
5895           utils_->MarkObjectRecursively(p);
5896       }
5897     }
5898
5899     HeapDebugUtils* utils_;
5900   };
5901
5902   void MarkObjectRecursively(Object** p) {
5903     if (!(*p)->IsHeapObject()) return;
5904
5905     HeapObject* obj = HeapObject::cast(*p);
5906
5907     Object* map = obj->map();
5908
5909     if (!map->IsHeapObject()) return;  // visited before
5910
5911     if (found_target_) return;  // stop if target found
5912     object_stack_.Add(obj);
5913     if ((search_for_any_global_ && obj->IsJSGlobalObject()) ||
5914         (!search_for_any_global_ && (obj == search_target_))) {
5915       found_target_ = true;
5916       return;
5917     }
5918
5919     // not visited yet
5920     Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5921
5922     Address map_addr = map_p->address();
5923
5924     obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
5925
5926     MarkObjectRecursively(&map);
5927
5928     MarkObjectVisitor mark_visitor(this);
5929
5930     obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
5931                      &mark_visitor);
5932
5933     if (!found_target_)  // don't pop if found the target
5934       object_stack_.RemoveLast();
5935   }
5936
5937
5938   class UnmarkObjectVisitor : public ObjectVisitor {
5939    public:
5940     explicit UnmarkObjectVisitor(HeapDebugUtils* utils) : utils_(utils) { }
5941
5942     void VisitPointers(Object** start, Object** end) {
5943       // Copy all HeapObject pointers in [start, end)
5944       for (Object** p = start; p < end; p++) {
5945         if ((*p)->IsHeapObject())
5946           utils_->UnmarkObjectRecursively(p);
5947       }
5948     }
5949
5950     HeapDebugUtils* utils_;
5951   };
5952
5953
5954   void UnmarkObjectRecursively(Object** p) {
5955     if (!(*p)->IsHeapObject()) return;
5956
5957     HeapObject* obj = HeapObject::cast(*p);
5958
5959     Object* map = obj->map();
5960
5961     if (map->IsHeapObject()) return;  // unmarked already
5962
5963     Address map_addr = reinterpret_cast<Address>(map);
5964
5965     map_addr -= kMarkTag;
5966
5967     ASSERT_TAG_ALIGNED(map_addr);
5968
5969     HeapObject* map_p = HeapObject::FromAddress(map_addr);
5970
5971     obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
5972
5973     UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
5974
5975     UnmarkObjectVisitor unmark_visitor(this);
5976
5977     obj->IterateBody(Map::cast(map_p)->instance_type(),
5978                      obj->SizeFromMap(Map::cast(map_p)),
5979                      &unmark_visitor);
5980   }
5981
5982
5983   void MarkRootObjectRecursively(Object** root) {
5984     if (search_for_any_global_) {
5985       ASSERT(search_target_ == NULL);
5986     } else {
5987       ASSERT(search_target_->IsHeapObject());
5988     }
5989     found_target_ = false;
5990     object_stack_.Clear();
5991
5992     MarkObjectRecursively(root);
5993     UnmarkObjectRecursively(root);
5994
5995     if (found_target_) {
5996       PrintF("=====================================\n");
5997       PrintF("====        Path to object       ====\n");
5998       PrintF("=====================================\n\n");
5999
6000       ASSERT(!object_stack_.is_empty());
6001       for (int i = 0; i < object_stack_.length(); i++) {
6002         if (i > 0) PrintF("\n     |\n     |\n     V\n\n");
6003         Object* obj = object_stack_[i];
6004         obj->Print();
6005       }
6006       PrintF("=====================================\n");
6007     }
6008   }
6009
6010   // Helper class for visiting HeapObjects recursively.
6011   class MarkRootVisitor: public ObjectVisitor {
6012    public:
6013     explicit MarkRootVisitor(HeapDebugUtils* utils) : utils_(utils) { }
6014
6015     void VisitPointers(Object** start, Object** end) {
6016       // Visit all HeapObject pointers in [start, end)
6017       for (Object** p = start; p < end; p++) {
6018         if ((*p)->IsHeapObject())
6019           utils_->MarkRootObjectRecursively(p);
6020       }
6021     }
6022
6023     HeapDebugUtils* utils_;
6024   };
6025
6026   bool search_for_any_global_;
6027   Object* search_target_;
6028   bool found_target_;
6029   List<Object*> object_stack_;
6030   Heap* heap_;
6031
6032   friend class Heap;
6033 };
6034
6035 #endif
6036
6037
6038 V8_DECLARE_ONCE(initialize_gc_once);
6039
6040 static void InitializeGCOnce() {
6041   InitializeScavengingVisitorsTables();
6042   NewSpaceScavenger::Initialize();
6043   MarkCompactCollector::Initialize();
6044 }
6045
6046 bool Heap::SetUp(bool create_heap_objects) {
6047 #ifdef DEBUG
6048   allocation_timeout_ = FLAG_gc_interval;
6049   debug_utils_ = new HeapDebugUtils(this);
6050 #endif
6051
6052   // Initialize heap spaces and initial maps and objects. Whenever something
6053   // goes wrong, just return false. The caller should check the results and
6054   // call Heap::TearDown() to release allocated memory.
6055   //
6056   // If the heap is not yet configured (e.g. through the API), configure it.
6057   // Configuration is based on the flags new-space-size (really the semispace
6058   // size) and old-space-size if set or the initial values of semispace_size_
6059   // and old_generation_size_ otherwise.
6060   if (!configured_) {
6061     if (!ConfigureHeapDefault()) return false;
6062   }
6063
6064   CallOnce(&initialize_gc_once, &InitializeGCOnce);
6065
6066   MarkMapPointersAsEncoded(false);
6067
6068   // Set up memory allocator.
6069   if (!isolate_->memory_allocator()->SetUp(MaxReserved(), MaxExecutableSize()))
6070       return false;
6071
6072   // Set up new space.
6073   if (!new_space_.SetUp(reserved_semispace_size_, max_semispace_size_)) {
6074     return false;
6075   }
6076
6077   // Initialize old pointer space.
6078   old_pointer_space_ =
6079       new OldSpace(this,
6080                    max_old_generation_size_,
6081                    OLD_POINTER_SPACE,
6082                    NOT_EXECUTABLE);
6083   if (old_pointer_space_ == NULL) return false;
6084   if (!old_pointer_space_->SetUp()) return false;
6085
6086   // Initialize old data space.
6087   old_data_space_ =
6088       new OldSpace(this,
6089                    max_old_generation_size_,
6090                    OLD_DATA_SPACE,
6091                    NOT_EXECUTABLE);
6092   if (old_data_space_ == NULL) return false;
6093   if (!old_data_space_->SetUp()) return false;
6094
6095   // Initialize the code space, set its maximum capacity to the old
6096   // generation size. It needs executable memory.
6097   // On 64-bit platform(s), we put all code objects in a 2 GB range of
6098   // virtual address space, so that they can call each other with near calls.
6099   if (code_range_size_ > 0) {
6100     if (!isolate_->code_range()->SetUp(code_range_size_)) {
6101       return false;
6102     }
6103   }
6104
6105   code_space_ =
6106       new OldSpace(this, max_old_generation_size_, CODE_SPACE, EXECUTABLE);
6107   if (code_space_ == NULL) return false;
6108   if (!code_space_->SetUp()) return false;
6109
6110   // Initialize map space.
6111   map_space_ = new MapSpace(this, max_old_generation_size_, MAP_SPACE);
6112   if (map_space_ == NULL) return false;
6113   if (!map_space_->SetUp()) return false;
6114
6115   // Initialize global property cell space.
6116   cell_space_ = new CellSpace(this, max_old_generation_size_, CELL_SPACE);
6117   if (cell_space_ == NULL) return false;
6118   if (!cell_space_->SetUp()) return false;
6119
6120   // The large object code space may contain code or data.  We set the memory
6121   // to be non-executable here for safety, but this means we need to enable it
6122   // explicitly when allocating large code objects.
6123   lo_space_ = new LargeObjectSpace(this, max_old_generation_size_, LO_SPACE);
6124   if (lo_space_ == NULL) return false;
6125   if (!lo_space_->SetUp()) return false;
6126
6127   // Set up the seed that is used to randomize the string hash function.
6128   ASSERT(hash_seed() == 0);
6129   if (FLAG_randomize_hashes) {
6130     if (FLAG_hash_seed == 0) {
6131       set_hash_seed(
6132           Smi::FromInt(V8::RandomPrivate(isolate()) & 0x3fffffff));
6133     } else {
6134       set_hash_seed(Smi::FromInt(FLAG_hash_seed));
6135     }
6136   }
6137
6138   if (create_heap_objects) {
6139     // Create initial maps.
6140     if (!CreateInitialMaps()) return false;
6141     if (!CreateApiObjects()) return false;
6142
6143     // Create initial objects
6144     if (!CreateInitialObjects()) return false;
6145
6146     global_contexts_list_ = undefined_value();
6147   }
6148
6149   LOG(isolate_, IntPtrTEvent("heap-capacity", Capacity()));
6150   LOG(isolate_, IntPtrTEvent("heap-available", Available()));
6151
6152   store_buffer()->SetUp();
6153
6154   return true;
6155 }
6156
6157
6158 void Heap::SetStackLimits() {
6159   ASSERT(isolate_ != NULL);
6160   ASSERT(isolate_ == isolate());
6161   // On 64 bit machines, pointers are generally out of range of Smis.  We write
6162   // something that looks like an out of range Smi to the GC.
6163
6164   // Set up the special root array entries containing the stack limits.
6165   // These are actually addresses, but the tag makes the GC ignore it.
6166   roots_[kStackLimitRootIndex] =
6167       reinterpret_cast<Object*>(
6168           (isolate_->stack_guard()->jslimit() & ~kSmiTagMask) | kSmiTag);
6169   roots_[kRealStackLimitRootIndex] =
6170       reinterpret_cast<Object*>(
6171           (isolate_->stack_guard()->real_jslimit() & ~kSmiTagMask) | kSmiTag);
6172 }
6173
6174
6175 void Heap::TearDown() {
6176 #ifdef DEBUG
6177   if (FLAG_verify_heap) {
6178     Verify();
6179   }
6180 #endif
6181   if (FLAG_print_cumulative_gc_stat) {
6182     PrintF("\n\n");
6183     PrintF("gc_count=%d ", gc_count_);
6184     PrintF("mark_sweep_count=%d ", ms_count_);
6185     PrintF("max_gc_pause=%d ", get_max_gc_pause());
6186     PrintF("min_in_mutator=%d ", get_min_in_mutator());
6187     PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
6188            get_max_alive_after_gc());
6189     PrintF("\n\n");
6190   }
6191
6192   isolate_->global_handles()->TearDown();
6193
6194   external_string_table_.TearDown();
6195
6196   new_space_.TearDown();
6197
6198   if (old_pointer_space_ != NULL) {
6199     old_pointer_space_->TearDown();
6200     delete old_pointer_space_;
6201     old_pointer_space_ = NULL;
6202   }
6203
6204   if (old_data_space_ != NULL) {
6205     old_data_space_->TearDown();
6206     delete old_data_space_;
6207     old_data_space_ = NULL;
6208   }
6209
6210   if (code_space_ != NULL) {
6211     code_space_->TearDown();
6212     delete code_space_;
6213     code_space_ = NULL;
6214   }
6215
6216   if (map_space_ != NULL) {
6217     map_space_->TearDown();
6218     delete map_space_;
6219     map_space_ = NULL;
6220   }
6221
6222   if (cell_space_ != NULL) {
6223     cell_space_->TearDown();
6224     delete cell_space_;
6225     cell_space_ = NULL;
6226   }
6227
6228   if (lo_space_ != NULL) {
6229     lo_space_->TearDown();
6230     delete lo_space_;
6231     lo_space_ = NULL;
6232   }
6233
6234   store_buffer()->TearDown();
6235   incremental_marking()->TearDown();
6236
6237   isolate_->memory_allocator()->TearDown();
6238
6239 #ifdef DEBUG
6240   delete debug_utils_;
6241   debug_utils_ = NULL;
6242 #endif
6243 }
6244
6245
6246 void Heap::Shrink() {
6247   // Try to shrink all paged spaces.
6248   PagedSpaces spaces;
6249   for (PagedSpace* space = spaces.next();
6250        space != NULL;
6251        space = spaces.next()) {
6252     space->ReleaseAllUnusedPages();
6253   }
6254 }
6255
6256
6257 void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
6258   ASSERT(callback != NULL);
6259   GCPrologueCallbackPair pair(callback, gc_type);
6260   ASSERT(!gc_prologue_callbacks_.Contains(pair));
6261   return gc_prologue_callbacks_.Add(pair);
6262 }
6263
6264
6265 void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
6266   ASSERT(callback != NULL);
6267   for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
6268     if (gc_prologue_callbacks_[i].callback == callback) {
6269       gc_prologue_callbacks_.Remove(i);
6270       return;
6271     }
6272   }
6273   UNREACHABLE();
6274 }
6275
6276
6277 void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
6278   ASSERT(callback != NULL);
6279   GCEpilogueCallbackPair pair(callback, gc_type);
6280   ASSERT(!gc_epilogue_callbacks_.Contains(pair));
6281   return gc_epilogue_callbacks_.Add(pair);
6282 }
6283
6284
6285 void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
6286   ASSERT(callback != NULL);
6287   for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
6288     if (gc_epilogue_callbacks_[i].callback == callback) {
6289       gc_epilogue_callbacks_.Remove(i);
6290       return;
6291     }
6292   }
6293   UNREACHABLE();
6294 }
6295
6296
6297 #ifdef DEBUG
6298
6299 class PrintHandleVisitor: public ObjectVisitor {
6300  public:
6301   void VisitPointers(Object** start, Object** end) {
6302     for (Object** p = start; p < end; p++)
6303       PrintF("  handle %p to %p\n",
6304              reinterpret_cast<void*>(p),
6305              reinterpret_cast<void*>(*p));
6306   }
6307 };
6308
6309 void Heap::PrintHandles() {
6310   PrintF("Handles:\n");
6311   PrintHandleVisitor v;
6312   isolate_->handle_scope_implementer()->Iterate(&v);
6313 }
6314
6315 #endif
6316
6317
6318 Space* AllSpaces::next() {
6319   switch (counter_++) {
6320     case NEW_SPACE:
6321       return HEAP->new_space();
6322     case OLD_POINTER_SPACE:
6323       return HEAP->old_pointer_space();
6324     case OLD_DATA_SPACE:
6325       return HEAP->old_data_space();
6326     case CODE_SPACE:
6327       return HEAP->code_space();
6328     case MAP_SPACE:
6329       return HEAP->map_space();
6330     case CELL_SPACE:
6331       return HEAP->cell_space();
6332     case LO_SPACE:
6333       return HEAP->lo_space();
6334     default:
6335       return NULL;
6336   }
6337 }
6338
6339
6340 PagedSpace* PagedSpaces::next() {
6341   switch (counter_++) {
6342     case OLD_POINTER_SPACE:
6343       return HEAP->old_pointer_space();
6344     case OLD_DATA_SPACE:
6345       return HEAP->old_data_space();
6346     case CODE_SPACE:
6347       return HEAP->code_space();
6348     case MAP_SPACE:
6349       return HEAP->map_space();
6350     case CELL_SPACE:
6351       return HEAP->cell_space();
6352     default:
6353       return NULL;
6354   }
6355 }
6356
6357
6358
6359 OldSpace* OldSpaces::next() {
6360   switch (counter_++) {
6361     case OLD_POINTER_SPACE:
6362       return HEAP->old_pointer_space();
6363     case OLD_DATA_SPACE:
6364       return HEAP->old_data_space();
6365     case CODE_SPACE:
6366       return HEAP->code_space();
6367     default:
6368       return NULL;
6369   }
6370 }
6371
6372
6373 SpaceIterator::SpaceIterator()
6374     : current_space_(FIRST_SPACE),
6375       iterator_(NULL),
6376       size_func_(NULL) {
6377 }
6378
6379
6380 SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
6381     : current_space_(FIRST_SPACE),
6382       iterator_(NULL),
6383       size_func_(size_func) {
6384 }
6385
6386
6387 SpaceIterator::~SpaceIterator() {
6388   // Delete active iterator if any.
6389   delete iterator_;
6390 }
6391
6392
6393 bool SpaceIterator::has_next() {
6394   // Iterate until no more spaces.
6395   return current_space_ != LAST_SPACE;
6396 }
6397
6398
6399 ObjectIterator* SpaceIterator::next() {
6400   if (iterator_ != NULL) {
6401     delete iterator_;
6402     iterator_ = NULL;
6403     // Move to the next space
6404     current_space_++;
6405     if (current_space_ > LAST_SPACE) {
6406       return NULL;
6407     }
6408   }
6409
6410   // Return iterator for the new current space.
6411   return CreateIterator();
6412 }
6413
6414
6415 // Create an iterator for the space to iterate.
6416 ObjectIterator* SpaceIterator::CreateIterator() {
6417   ASSERT(iterator_ == NULL);
6418
6419   switch (current_space_) {
6420     case NEW_SPACE:
6421       iterator_ = new SemiSpaceIterator(HEAP->new_space(), size_func_);
6422       break;
6423     case OLD_POINTER_SPACE:
6424       iterator_ = new HeapObjectIterator(HEAP->old_pointer_space(), size_func_);
6425       break;
6426     case OLD_DATA_SPACE:
6427       iterator_ = new HeapObjectIterator(HEAP->old_data_space(), size_func_);
6428       break;
6429     case CODE_SPACE:
6430       iterator_ = new HeapObjectIterator(HEAP->code_space(), size_func_);
6431       break;
6432     case MAP_SPACE:
6433       iterator_ = new HeapObjectIterator(HEAP->map_space(), size_func_);
6434       break;
6435     case CELL_SPACE:
6436       iterator_ = new HeapObjectIterator(HEAP->cell_space(), size_func_);
6437       break;
6438     case LO_SPACE:
6439       iterator_ = new LargeObjectIterator(HEAP->lo_space(), size_func_);
6440       break;
6441   }
6442
6443   // Return the newly allocated iterator;
6444   ASSERT(iterator_ != NULL);
6445   return iterator_;
6446 }
6447
6448
6449 class HeapObjectsFilter {
6450  public:
6451   virtual ~HeapObjectsFilter() {}
6452   virtual bool SkipObject(HeapObject* object) = 0;
6453 };
6454
6455
6456 class UnreachableObjectsFilter : public HeapObjectsFilter {
6457  public:
6458   UnreachableObjectsFilter() {
6459     MarkReachableObjects();
6460   }
6461
6462   ~UnreachableObjectsFilter() {
6463     Isolate::Current()->heap()->mark_compact_collector()->ClearMarkbits();
6464   }
6465
6466   bool SkipObject(HeapObject* object) {
6467     MarkBit mark_bit = Marking::MarkBitFrom(object);
6468     return !mark_bit.Get();
6469   }
6470
6471  private:
6472   class MarkingVisitor : public ObjectVisitor {
6473    public:
6474     MarkingVisitor() : marking_stack_(10) {}
6475
6476     void VisitPointers(Object** start, Object** end) {
6477       for (Object** p = start; p < end; p++) {
6478         if (!(*p)->IsHeapObject()) continue;
6479         HeapObject* obj = HeapObject::cast(*p);
6480         MarkBit mark_bit = Marking::MarkBitFrom(obj);
6481         if (!mark_bit.Get()) {
6482           mark_bit.Set();
6483           marking_stack_.Add(obj);
6484         }
6485       }
6486     }
6487
6488     void TransitiveClosure() {
6489       while (!marking_stack_.is_empty()) {
6490         HeapObject* obj = marking_stack_.RemoveLast();
6491         obj->Iterate(this);
6492       }
6493     }
6494
6495    private:
6496     List<HeapObject*> marking_stack_;
6497   };
6498
6499   void MarkReachableObjects() {
6500     Heap* heap = Isolate::Current()->heap();
6501     MarkingVisitor visitor;
6502     heap->IterateRoots(&visitor, VISIT_ALL);
6503     visitor.TransitiveClosure();
6504   }
6505
6506   AssertNoAllocation no_alloc;
6507 };
6508
6509
6510 HeapIterator::HeapIterator()
6511     : filtering_(HeapIterator::kNoFiltering),
6512       filter_(NULL) {
6513   Init();
6514 }
6515
6516
6517 HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
6518     : filtering_(filtering),
6519       filter_(NULL) {
6520   Init();
6521 }
6522
6523
6524 HeapIterator::~HeapIterator() {
6525   Shutdown();
6526 }
6527
6528
6529 void HeapIterator::Init() {
6530   // Start the iteration.
6531   space_iterator_ = new SpaceIterator;
6532   switch (filtering_) {
6533     case kFilterUnreachable:
6534       filter_ = new UnreachableObjectsFilter;
6535       break;
6536     default:
6537       break;
6538   }
6539   object_iterator_ = space_iterator_->next();
6540 }
6541
6542
6543 void HeapIterator::Shutdown() {
6544 #ifdef DEBUG
6545   // Assert that in filtering mode we have iterated through all
6546   // objects. Otherwise, heap will be left in an inconsistent state.
6547   if (filtering_ != kNoFiltering) {
6548     ASSERT(object_iterator_ == NULL);
6549   }
6550 #endif
6551   // Make sure the last iterator is deallocated.
6552   delete space_iterator_;
6553   space_iterator_ = NULL;
6554   object_iterator_ = NULL;
6555   delete filter_;
6556   filter_ = NULL;
6557 }
6558
6559
6560 HeapObject* HeapIterator::next() {
6561   if (filter_ == NULL) return NextObject();
6562
6563   HeapObject* obj = NextObject();
6564   while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
6565   return obj;
6566 }
6567
6568
6569 HeapObject* HeapIterator::NextObject() {
6570   // No iterator means we are done.
6571   if (object_iterator_ == NULL) return NULL;
6572
6573   if (HeapObject* obj = object_iterator_->next_object()) {
6574     // If the current iterator has more objects we are fine.
6575     return obj;
6576   } else {
6577     // Go though the spaces looking for one that has objects.
6578     while (space_iterator_->has_next()) {
6579       object_iterator_ = space_iterator_->next();
6580       if (HeapObject* obj = object_iterator_->next_object()) {
6581         return obj;
6582       }
6583     }
6584   }
6585   // Done with the last space.
6586   object_iterator_ = NULL;
6587   return NULL;
6588 }
6589
6590
6591 void HeapIterator::reset() {
6592   // Restart the iterator.
6593   Shutdown();
6594   Init();
6595 }
6596
6597
6598 #if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
6599
6600 Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
6601
6602 class PathTracer::MarkVisitor: public ObjectVisitor {
6603  public:
6604   explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6605   void VisitPointers(Object** start, Object** end) {
6606     // Scan all HeapObject pointers in [start, end)
6607     for (Object** p = start; !tracer_->found() && (p < end); p++) {
6608       if ((*p)->IsHeapObject())
6609         tracer_->MarkRecursively(p, this);
6610     }
6611   }
6612
6613  private:
6614   PathTracer* tracer_;
6615 };
6616
6617
6618 class PathTracer::UnmarkVisitor: public ObjectVisitor {
6619  public:
6620   explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
6621   void VisitPointers(Object** start, Object** end) {
6622     // Scan all HeapObject pointers in [start, end)
6623     for (Object** p = start; p < end; p++) {
6624       if ((*p)->IsHeapObject())
6625         tracer_->UnmarkRecursively(p, this);
6626     }
6627   }
6628
6629  private:
6630   PathTracer* tracer_;
6631 };
6632
6633
6634 void PathTracer::VisitPointers(Object** start, Object** end) {
6635   bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
6636   // Visit all HeapObject pointers in [start, end)
6637   for (Object** p = start; !done && (p < end); p++) {
6638     if ((*p)->IsHeapObject()) {
6639       TracePathFrom(p);
6640       done = ((what_to_find_ == FIND_FIRST) && found_target_);
6641     }
6642   }
6643 }
6644
6645
6646 void PathTracer::Reset() {
6647   found_target_ = false;
6648   object_stack_.Clear();
6649 }
6650
6651
6652 void PathTracer::TracePathFrom(Object** root) {
6653   ASSERT((search_target_ == kAnyGlobalObject) ||
6654          search_target_->IsHeapObject());
6655   found_target_in_trace_ = false;
6656   object_stack_.Clear();
6657
6658   MarkVisitor mark_visitor(this);
6659   MarkRecursively(root, &mark_visitor);
6660
6661   UnmarkVisitor unmark_visitor(this);
6662   UnmarkRecursively(root, &unmark_visitor);
6663
6664   ProcessResults();
6665 }
6666
6667
6668 static bool SafeIsGlobalContext(HeapObject* obj) {
6669   return obj->map() == obj->GetHeap()->raw_unchecked_global_context_map();
6670 }
6671
6672
6673 void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
6674   if (!(*p)->IsHeapObject()) return;
6675
6676   HeapObject* obj = HeapObject::cast(*p);
6677
6678   Object* map = obj->map();
6679
6680   if (!map->IsHeapObject()) return;  // visited before
6681
6682   if (found_target_in_trace_) return;  // stop if target found
6683   object_stack_.Add(obj);
6684   if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
6685       (obj == search_target_)) {
6686     found_target_in_trace_ = true;
6687     found_target_ = true;
6688     return;
6689   }
6690
6691   bool is_global_context = SafeIsGlobalContext(obj);
6692
6693   // not visited yet
6694   Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
6695
6696   Address map_addr = map_p->address();
6697
6698   obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_addr + kMarkTag));
6699
6700   // Scan the object body.
6701   if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
6702     // This is specialized to scan Context's properly.
6703     Object** start = reinterpret_cast<Object**>(obj->address() +
6704                                                 Context::kHeaderSize);
6705     Object** end = reinterpret_cast<Object**>(obj->address() +
6706         Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
6707     mark_visitor->VisitPointers(start, end);
6708   } else {
6709     obj->IterateBody(map_p->instance_type(),
6710                      obj->SizeFromMap(map_p),
6711                      mark_visitor);
6712   }
6713
6714   // Scan the map after the body because the body is a lot more interesting
6715   // when doing leak detection.
6716   MarkRecursively(&map, mark_visitor);
6717
6718   if (!found_target_in_trace_)  // don't pop if found the target
6719     object_stack_.RemoveLast();
6720 }
6721
6722
6723 void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
6724   if (!(*p)->IsHeapObject()) return;
6725
6726   HeapObject* obj = HeapObject::cast(*p);
6727
6728   Object* map = obj->map();
6729
6730   if (map->IsHeapObject()) return;  // unmarked already
6731
6732   Address map_addr = reinterpret_cast<Address>(map);
6733
6734   map_addr -= kMarkTag;
6735
6736   ASSERT_TAG_ALIGNED(map_addr);
6737
6738   HeapObject* map_p = HeapObject::FromAddress(map_addr);
6739
6740   obj->set_map_no_write_barrier(reinterpret_cast<Map*>(map_p));
6741
6742   UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
6743
6744   obj->IterateBody(Map::cast(map_p)->instance_type(),
6745                    obj->SizeFromMap(Map::cast(map_p)),
6746                    unmark_visitor);
6747 }
6748
6749
6750 void PathTracer::ProcessResults() {
6751   if (found_target_) {
6752     PrintF("=====================================\n");
6753     PrintF("====        Path to object       ====\n");
6754     PrintF("=====================================\n\n");
6755
6756     ASSERT(!object_stack_.is_empty());
6757     for (int i = 0; i < object_stack_.length(); i++) {
6758       if (i > 0) PrintF("\n     |\n     |\n     V\n\n");
6759       Object* obj = object_stack_[i];
6760 #ifdef OBJECT_PRINT
6761       obj->Print();
6762 #else
6763       obj->ShortPrint();
6764 #endif
6765     }
6766     PrintF("=====================================\n");
6767   }
6768 }
6769 #endif  // DEBUG || LIVE_OBJECT_LIST
6770
6771
6772 #ifdef DEBUG
6773 // Triggers a depth-first traversal of reachable objects from roots
6774 // and finds a path to a specific heap object and prints it.
6775 void Heap::TracePathToObject(Object* target) {
6776   PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
6777   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6778 }
6779
6780
6781 // Triggers a depth-first traversal of reachable objects from roots
6782 // and finds a path to any global object and prints it. Useful for
6783 // determining the source for leaks of global objects.
6784 void Heap::TracePathToGlobal() {
6785   PathTracer tracer(PathTracer::kAnyGlobalObject,
6786                     PathTracer::FIND_ALL,
6787                     VISIT_ALL);
6788   IterateRoots(&tracer, VISIT_ONLY_STRONG);
6789 }
6790 #endif
6791
6792
6793 static intptr_t CountTotalHolesSize() {
6794   intptr_t holes_size = 0;
6795   OldSpaces spaces;
6796   for (OldSpace* space = spaces.next();
6797        space != NULL;
6798        space = spaces.next()) {
6799     holes_size += space->Waste() + space->Available();
6800   }
6801   return holes_size;
6802 }
6803
6804
6805 GCTracer::GCTracer(Heap* heap,
6806                    const char* gc_reason,
6807                    const char* collector_reason)
6808     : start_time_(0.0),
6809       start_object_size_(0),
6810       start_memory_size_(0),
6811       gc_count_(0),
6812       full_gc_count_(0),
6813       allocated_since_last_gc_(0),
6814       spent_in_mutator_(0),
6815       promoted_objects_size_(0),
6816       heap_(heap),
6817       gc_reason_(gc_reason),
6818       collector_reason_(collector_reason) {
6819   if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6820   start_time_ = OS::TimeCurrentMillis();
6821   start_object_size_ = heap_->SizeOfObjects();
6822   start_memory_size_ = heap_->isolate()->memory_allocator()->Size();
6823
6824   for (int i = 0; i < Scope::kNumberOfScopes; i++) {
6825     scopes_[i] = 0;
6826   }
6827
6828   in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
6829
6830   allocated_since_last_gc_ =
6831       heap_->SizeOfObjects() - heap_->alive_after_last_gc_;
6832
6833   if (heap_->last_gc_end_timestamp_ > 0) {
6834     spent_in_mutator_ = Max(start_time_ - heap_->last_gc_end_timestamp_, 0.0);
6835   }
6836
6837   steps_count_ = heap_->incremental_marking()->steps_count();
6838   steps_took_ = heap_->incremental_marking()->steps_took();
6839   longest_step_ = heap_->incremental_marking()->longest_step();
6840   steps_count_since_last_gc_ =
6841       heap_->incremental_marking()->steps_count_since_last_gc();
6842   steps_took_since_last_gc_ =
6843       heap_->incremental_marking()->steps_took_since_last_gc();
6844 }
6845
6846
6847 GCTracer::~GCTracer() {
6848   // Printf ONE line iff flag is set.
6849   if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
6850
6851   bool first_gc = (heap_->last_gc_end_timestamp_ == 0);
6852
6853   heap_->alive_after_last_gc_ = heap_->SizeOfObjects();
6854   heap_->last_gc_end_timestamp_ = OS::TimeCurrentMillis();
6855
6856   int time = static_cast<int>(heap_->last_gc_end_timestamp_ - start_time_);
6857
6858   // Update cumulative GC statistics if required.
6859   if (FLAG_print_cumulative_gc_stat) {
6860     heap_->max_gc_pause_ = Max(heap_->max_gc_pause_, time);
6861     heap_->max_alive_after_gc_ = Max(heap_->max_alive_after_gc_,
6862                                      heap_->alive_after_last_gc_);
6863     if (!first_gc) {
6864       heap_->min_in_mutator_ = Min(heap_->min_in_mutator_,
6865                                    static_cast<int>(spent_in_mutator_));
6866     }
6867   }
6868
6869   PrintF("%8.0f ms: ", heap_->isolate()->time_millis_since_init());
6870
6871   if (!FLAG_trace_gc_nvp) {
6872     int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
6873
6874     double end_memory_size_mb =
6875         static_cast<double>(heap_->isolate()->memory_allocator()->Size()) / MB;
6876
6877     PrintF("%s %.1f (%.1f) -> %.1f (%.1f) MB, ",
6878            CollectorString(),
6879            static_cast<double>(start_object_size_) / MB,
6880            static_cast<double>(start_memory_size_) / MB,
6881            SizeOfHeapObjects(),
6882            end_memory_size_mb);
6883
6884     if (external_time > 0) PrintF("%d / ", external_time);
6885     PrintF("%d ms", time);
6886     if (steps_count_ > 0) {
6887       if (collector_ == SCAVENGER) {
6888         PrintF(" (+ %d ms in %d steps since last GC)",
6889                static_cast<int>(steps_took_since_last_gc_),
6890                steps_count_since_last_gc_);
6891       } else {
6892         PrintF(" (+ %d ms in %d steps since start of marking, "
6893                    "biggest step %f ms)",
6894                static_cast<int>(steps_took_),
6895                steps_count_,
6896                longest_step_);
6897       }
6898     }
6899
6900     if (gc_reason_ != NULL) {
6901       PrintF(" [%s]", gc_reason_);
6902     }
6903
6904     if (collector_reason_ != NULL) {
6905       PrintF(" [%s]", collector_reason_);
6906     }
6907
6908     PrintF(".\n");
6909   } else {
6910     PrintF("pause=%d ", time);
6911     PrintF("mutator=%d ",
6912            static_cast<int>(spent_in_mutator_));
6913
6914     PrintF("gc=");
6915     switch (collector_) {
6916       case SCAVENGER:
6917         PrintF("s");
6918         break;
6919       case MARK_COMPACTOR:
6920         PrintF("ms");
6921         break;
6922       default:
6923         UNREACHABLE();
6924     }
6925     PrintF(" ");
6926
6927     PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
6928     PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
6929     PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
6930     PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
6931     PrintF("evacuate=%d ", static_cast<int>(scopes_[Scope::MC_EVACUATE_PAGES]));
6932     PrintF("new_new=%d ",
6933            static_cast<int>(scopes_[Scope::MC_UPDATE_NEW_TO_NEW_POINTERS]));
6934     PrintF("root_new=%d ",
6935            static_cast<int>(scopes_[Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS]));
6936     PrintF("old_new=%d ",
6937            static_cast<int>(scopes_[Scope::MC_UPDATE_OLD_TO_NEW_POINTERS]));
6938     PrintF("compaction_ptrs=%d ",
6939            static_cast<int>(scopes_[Scope::MC_UPDATE_POINTERS_TO_EVACUATED]));
6940     PrintF("intracompaction_ptrs=%d ", static_cast<int>(scopes_[
6941         Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED]));
6942     PrintF("misc_compaction=%d ",
6943            static_cast<int>(scopes_[Scope::MC_UPDATE_MISC_POINTERS]));
6944
6945     PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_object_size_);
6946     PrintF("total_size_after=%" V8_PTR_PREFIX "d ", heap_->SizeOfObjects());
6947     PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
6948            in_free_list_or_wasted_before_gc_);
6949     PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
6950
6951     PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
6952     PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
6953
6954     if (collector_ == SCAVENGER) {
6955       PrintF("stepscount=%d ", steps_count_since_last_gc_);
6956       PrintF("stepstook=%d ", static_cast<int>(steps_took_since_last_gc_));
6957     } else {
6958       PrintF("stepscount=%d ", steps_count_);
6959       PrintF("stepstook=%d ", static_cast<int>(steps_took_));
6960     }
6961
6962     PrintF("\n");
6963   }
6964
6965   heap_->PrintShortHeapStatistics();
6966 }
6967
6968
6969 const char* GCTracer::CollectorString() {
6970   switch (collector_) {
6971     case SCAVENGER:
6972       return "Scavenge";
6973     case MARK_COMPACTOR:
6974       return "Mark-sweep";
6975   }
6976   return "Unknown GC";
6977 }
6978
6979
6980 int KeyedLookupCache::Hash(Map* map, String* name) {
6981   // Uses only lower 32 bits if pointers are larger.
6982   uintptr_t addr_hash =
6983       static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
6984   return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
6985 }
6986
6987
6988 int KeyedLookupCache::Lookup(Map* map, String* name) {
6989   int index = (Hash(map, name) & kHashMask);
6990   for (int i = 0; i < kEntriesPerBucket; i++) {
6991     Key& key = keys_[index + i];
6992     if ((key.map == map) && key.name->Equals(name)) {
6993       return field_offsets_[index + i];
6994     }
6995   }
6996   return kNotFound;
6997 }
6998
6999
7000 void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
7001   String* symbol;
7002   if (HEAP->LookupSymbolIfExists(name, &symbol)) {
7003     int index = (Hash(map, symbol) & kHashMask);
7004     // After a GC there will be free slots, so we use them in order (this may
7005     // help to get the most frequently used one in position 0).
7006     for (int i = 0; i< kEntriesPerBucket; i++) {
7007       Key& key = keys_[index];
7008       Object* free_entry_indicator = NULL;
7009       if (key.map == free_entry_indicator) {
7010         key.map = map;
7011         key.name = symbol;
7012         field_offsets_[index + i] = field_offset;
7013         return;
7014       }
7015     }
7016     // No free entry found in this bucket, so we move them all down one and
7017     // put the new entry at position zero.
7018     for (int i = kEntriesPerBucket - 1; i > 0; i--) {
7019       Key& key = keys_[index + i];
7020       Key& key2 = keys_[index + i - 1];
7021       key = key2;
7022       field_offsets_[index + i] = field_offsets_[index + i - 1];
7023     }
7024
7025     // Write the new first entry.
7026     Key& key = keys_[index];
7027     key.map = map;
7028     key.name = symbol;
7029     field_offsets_[index] = field_offset;
7030   }
7031 }
7032
7033
7034 void KeyedLookupCache::Clear() {
7035   for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
7036 }
7037
7038
7039 void DescriptorLookupCache::Clear() {
7040   for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
7041 }
7042
7043
7044 #ifdef DEBUG
7045 void Heap::GarbageCollectionGreedyCheck() {
7046   ASSERT(FLAG_gc_greedy);
7047   if (isolate_->bootstrapper()->IsActive()) return;
7048   if (disallow_allocation_failure()) return;
7049   CollectGarbage(NEW_SPACE);
7050 }
7051 #endif
7052
7053
7054 TranscendentalCache::SubCache::SubCache(Type t)
7055   : type_(t),
7056     isolate_(Isolate::Current()) {
7057   uint32_t in0 = 0xffffffffu;  // Bit-pattern for a NaN that isn't
7058   uint32_t in1 = 0xffffffffu;  // generated by the FPU.
7059   for (int i = 0; i < kCacheSize; i++) {
7060     elements_[i].in[0] = in0;
7061     elements_[i].in[1] = in1;
7062     elements_[i].output = NULL;
7063   }
7064 }
7065
7066
7067 void TranscendentalCache::Clear() {
7068   for (int i = 0; i < kNumberOfCaches; i++) {
7069     if (caches_[i] != NULL) {
7070       delete caches_[i];
7071       caches_[i] = NULL;
7072     }
7073   }
7074 }
7075
7076
7077 void ExternalStringTable::CleanUp() {
7078   int last = 0;
7079   for (int i = 0; i < new_space_strings_.length(); ++i) {
7080     if (new_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7081       continue;
7082     }
7083     if (heap_->InNewSpace(new_space_strings_[i])) {
7084       new_space_strings_[last++] = new_space_strings_[i];
7085     } else {
7086       old_space_strings_.Add(new_space_strings_[i]);
7087     }
7088   }
7089   new_space_strings_.Rewind(last);
7090   last = 0;
7091   for (int i = 0; i < old_space_strings_.length(); ++i) {
7092     if (old_space_strings_[i] == heap_->raw_unchecked_the_hole_value()) {
7093       continue;
7094     }
7095     ASSERT(!heap_->InNewSpace(old_space_strings_[i]));
7096     old_space_strings_[last++] = old_space_strings_[i];
7097   }
7098   old_space_strings_.Rewind(last);
7099   if (FLAG_verify_heap) {
7100     Verify();
7101   }
7102 }
7103
7104
7105 void ExternalStringTable::TearDown() {
7106   new_space_strings_.Free();
7107   old_space_strings_.Free();
7108 }
7109
7110
7111 void Heap::QueueMemoryChunkForFree(MemoryChunk* chunk) {
7112   chunk->set_next_chunk(chunks_queued_for_free_);
7113   chunks_queued_for_free_ = chunk;
7114 }
7115
7116
7117 void Heap::FreeQueuedChunks() {
7118   if (chunks_queued_for_free_ == NULL) return;
7119   MemoryChunk* next;
7120   MemoryChunk* chunk;
7121   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7122     next = chunk->next_chunk();
7123     chunk->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7124
7125     if (chunk->owner()->identity() == LO_SPACE) {
7126       // StoreBuffer::Filter relies on MemoryChunk::FromAnyPointerAddress.
7127       // If FromAnyPointerAddress encounters a slot that belongs to a large
7128       // chunk queued for deletion it will fail to find the chunk because
7129       // it try to perform a search in the list of pages owned by of the large
7130       // object space and queued chunks were detached from that list.
7131       // To work around this we split large chunk into normal kPageSize aligned
7132       // pieces and initialize size, owner and flags field of every piece.
7133       // If FromAnyPointerAddress encounters a slot that belongs to one of
7134       // these smaller pieces it will treat it as a slot on a normal Page.
7135       Address chunk_end = chunk->address() + chunk->size();
7136       MemoryChunk* inner = MemoryChunk::FromAddress(
7137           chunk->address() + Page::kPageSize);
7138       MemoryChunk* inner_last = MemoryChunk::FromAddress(chunk_end - 1);
7139       while (inner <= inner_last) {
7140         // Size of a large chunk is always a multiple of
7141         // OS::AllocateAlignment() so there is always
7142         // enough space for a fake MemoryChunk header.
7143         Address area_end = Min(inner->address() + Page::kPageSize, chunk_end);
7144         // Guard against overflow.
7145         if (area_end < inner->address()) area_end = chunk_end;
7146         inner->SetArea(inner->address(), area_end);
7147         inner->set_size(Page::kPageSize);
7148         inner->set_owner(lo_space());
7149         inner->SetFlag(MemoryChunk::ABOUT_TO_BE_FREED);
7150         inner = MemoryChunk::FromAddress(
7151             inner->address() + Page::kPageSize);
7152       }
7153     }
7154   }
7155   isolate_->heap()->store_buffer()->Compact();
7156   isolate_->heap()->store_buffer()->Filter(MemoryChunk::ABOUT_TO_BE_FREED);
7157   for (chunk = chunks_queued_for_free_; chunk != NULL; chunk = next) {
7158     next = chunk->next_chunk();
7159     isolate_->memory_allocator()->Free(chunk);
7160   }
7161   chunks_queued_for_free_ = NULL;
7162 }
7163
7164
7165 void Heap::RememberUnmappedPage(Address page, bool compacted) {
7166   uintptr_t p = reinterpret_cast<uintptr_t>(page);
7167   // Tag the page pointer to make it findable in the dump file.
7168   if (compacted) {
7169     p ^= 0xc1ead & (Page::kPageSize - 1);  // Cleared.
7170   } else {
7171     p ^= 0x1d1ed & (Page::kPageSize - 1);  // I died.
7172   }
7173   remembered_unmapped_pages_[remembered_unmapped_pages_index_] =
7174       reinterpret_cast<Address>(p);
7175   remembered_unmapped_pages_index_++;
7176   remembered_unmapped_pages_index_ %= kRememberedUnmappedPages;
7177 }
7178
7179 } }  // namespace v8::internal