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