blob: 4e4cd1c051e570621916663aa5a88cc342b41682 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 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-inl.h"
34#include "compilation-cache.h"
35#include "debug.h"
36#include "heap-profiler.h"
37#include "global-handles.h"
38#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
Steve Block3ce2e202009-11-05 08:53:23 +000042#include "snapshot.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043#include "v8threads.h"
44#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
45#include "regexp-macro-assembler.h"
Steve Blockd0582a62009-12-15 09:54:21 +000046#include "arm/regexp-macro-assembler-arm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000047#endif
48
49namespace v8 {
50namespace internal {
51
52
53String* Heap::hidden_symbol_;
54Object* Heap::roots_[Heap::kRootListLength];
55
56
57NewSpace Heap::new_space_;
58OldSpace* Heap::old_pointer_space_ = NULL;
59OldSpace* Heap::old_data_space_ = NULL;
60OldSpace* Heap::code_space_ = NULL;
61MapSpace* Heap::map_space_ = NULL;
62CellSpace* Heap::cell_space_ = NULL;
63LargeObjectSpace* Heap::lo_space_ = NULL;
64
65static const int kMinimumPromotionLimit = 2*MB;
66static const int kMinimumAllocationLimit = 8*MB;
67
68int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
69int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
70
71int Heap::old_gen_exhausted_ = false;
72
73int Heap::amount_of_external_allocated_memory_ = 0;
74int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
75
76// semispace_size_ should be a power of 2 and old_generation_size_ should be
77// a multiple of Page::kPageSize.
78#if defined(ANDROID)
Steve Block3ce2e202009-11-05 08:53:23 +000079int Heap::max_semispace_size_ = 512*KB;
80int Heap::max_old_generation_size_ = 128*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000081int Heap::initial_semispace_size_ = 128*KB;
82size_t Heap::code_range_size_ = 0;
83#elif defined(V8_TARGET_ARCH_X64)
Steve Block3ce2e202009-11-05 08:53:23 +000084int Heap::max_semispace_size_ = 16*MB;
85int Heap::max_old_generation_size_ = 1*GB;
Steve Blocka7e24c12009-10-30 11:49:00 +000086int Heap::initial_semispace_size_ = 1*MB;
Steve Block3ce2e202009-11-05 08:53:23 +000087size_t Heap::code_range_size_ = 512*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000088#else
Steve Block3ce2e202009-11-05 08:53:23 +000089int Heap::max_semispace_size_ = 8*MB;
90int Heap::max_old_generation_size_ = 512*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000091int Heap::initial_semispace_size_ = 512*KB;
92size_t Heap::code_range_size_ = 0;
93#endif
94
Steve Block3ce2e202009-11-05 08:53:23 +000095// The snapshot semispace size will be the default semispace size if
96// snapshotting is used and will be the requested semispace size as
97// set up by ConfigureHeap otherwise.
98int Heap::reserved_semispace_size_ = Heap::max_semispace_size_;
99
Steve Blocka7e24c12009-10-30 11:49:00 +0000100GCCallback Heap::global_gc_prologue_callback_ = NULL;
101GCCallback Heap::global_gc_epilogue_callback_ = NULL;
102
103// Variables set based on semispace_size_ and old_generation_size_ in
104// ConfigureHeap.
Steve Block3ce2e202009-11-05 08:53:23 +0000105
106// Will be 4 * reserved_semispace_size_ to ensure that young
107// generation can be aligned to its size.
Steve Blocka7e24c12009-10-30 11:49:00 +0000108int Heap::survived_since_last_expansion_ = 0;
109int Heap::external_allocation_limit_ = 0;
110
111Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
112
113int Heap::mc_count_ = 0;
114int Heap::gc_count_ = 0;
115
116int Heap::always_allocate_scope_depth_ = 0;
Steve Blockd0582a62009-12-15 09:54:21 +0000117int Heap::linear_allocation_scope_depth_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000118bool Heap::context_disposed_pending_ = false;
119
120#ifdef DEBUG
121bool Heap::allocation_allowed_ = true;
122
123int Heap::allocation_timeout_ = 0;
124bool Heap::disallow_allocation_failure_ = false;
125#endif // DEBUG
126
127
128int Heap::Capacity() {
129 if (!HasBeenSetup()) return 0;
130
131 return new_space_.Capacity() +
132 old_pointer_space_->Capacity() +
133 old_data_space_->Capacity() +
134 code_space_->Capacity() +
135 map_space_->Capacity() +
136 cell_space_->Capacity();
137}
138
139
Steve Block3ce2e202009-11-05 08:53:23 +0000140int Heap::CommittedMemory() {
141 if (!HasBeenSetup()) return 0;
142
143 return new_space_.CommittedMemory() +
144 old_pointer_space_->CommittedMemory() +
145 old_data_space_->CommittedMemory() +
146 code_space_->CommittedMemory() +
147 map_space_->CommittedMemory() +
148 cell_space_->CommittedMemory() +
149 lo_space_->Size();
150}
151
152
Steve Blocka7e24c12009-10-30 11:49:00 +0000153int Heap::Available() {
154 if (!HasBeenSetup()) return 0;
155
156 return new_space_.Available() +
157 old_pointer_space_->Available() +
158 old_data_space_->Available() +
159 code_space_->Available() +
160 map_space_->Available() +
161 cell_space_->Available();
162}
163
164
165bool Heap::HasBeenSetup() {
166 return old_pointer_space_ != NULL &&
167 old_data_space_ != NULL &&
168 code_space_ != NULL &&
169 map_space_ != NULL &&
170 cell_space_ != NULL &&
171 lo_space_ != NULL;
172}
173
174
175GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
176 // Is global GC requested?
177 if (space != NEW_SPACE || FLAG_gc_global) {
178 Counters::gc_compactor_caused_by_request.Increment();
179 return MARK_COMPACTOR;
180 }
181
182 // Is enough data promoted to justify a global GC?
183 if (OldGenerationPromotionLimitReached()) {
184 Counters::gc_compactor_caused_by_promoted_data.Increment();
185 return MARK_COMPACTOR;
186 }
187
188 // Have allocation in OLD and LO failed?
189 if (old_gen_exhausted_) {
190 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
191 return MARK_COMPACTOR;
192 }
193
194 // Is there enough space left in OLD to guarantee that a scavenge can
195 // succeed?
196 //
197 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
198 // for object promotion. It counts only the bytes that the memory
199 // allocator has not yet allocated from the OS and assigned to any space,
200 // and does not count available bytes already in the old space or code
201 // space. Undercounting is safe---we may get an unrequested full GC when
202 // a scavenge would have succeeded.
203 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
204 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
205 return MARK_COMPACTOR;
206 }
207
208 // Default
209 return SCAVENGER;
210}
211
212
213// TODO(1238405): Combine the infrastructure for --heap-stats and
214// --log-gc to avoid the complicated preprocessor and flag testing.
215#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
216void Heap::ReportStatisticsBeforeGC() {
217 // Heap::ReportHeapStatistics will also log NewSpace statistics when
218 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
219 // following logic is used to avoid double logging.
220#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
221 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
222 if (FLAG_heap_stats) {
223 ReportHeapStatistics("Before GC");
224 } else if (FLAG_log_gc) {
225 new_space_.ReportStatistics();
226 }
227 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
228#elif defined(DEBUG)
229 if (FLAG_heap_stats) {
230 new_space_.CollectStatistics();
231 ReportHeapStatistics("Before GC");
232 new_space_.ClearHistograms();
233 }
234#elif defined(ENABLE_LOGGING_AND_PROFILING)
235 if (FLAG_log_gc) {
236 new_space_.CollectStatistics();
237 new_space_.ReportStatistics();
238 new_space_.ClearHistograms();
239 }
240#endif
241}
242
243
244#if defined(ENABLE_LOGGING_AND_PROFILING)
245void Heap::PrintShortHeapStatistics() {
246 if (!FLAG_trace_gc_verbose) return;
247 PrintF("Memory allocator, used: %8d, available: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000248 MemoryAllocator::Size(),
249 MemoryAllocator::Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000250 PrintF("New space, used: %8d, available: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000251 Heap::new_space_.Size(),
252 new_space_.Available());
253 PrintF("Old pointers, used: %8d, available: %8d, waste: %8d\n",
254 old_pointer_space_->Size(),
255 old_pointer_space_->Available(),
256 old_pointer_space_->Waste());
257 PrintF("Old data space, used: %8d, available: %8d, waste: %8d\n",
258 old_data_space_->Size(),
259 old_data_space_->Available(),
260 old_data_space_->Waste());
261 PrintF("Code space, used: %8d, available: %8d, waste: %8d\n",
262 code_space_->Size(),
263 code_space_->Available(),
264 code_space_->Waste());
265 PrintF("Map space, used: %8d, available: %8d, waste: %8d\n",
266 map_space_->Size(),
267 map_space_->Available(),
268 map_space_->Waste());
269 PrintF("Cell space, used: %8d, available: %8d, waste: %8d\n",
270 cell_space_->Size(),
271 cell_space_->Available(),
272 cell_space_->Waste());
Steve Blocka7e24c12009-10-30 11:49:00 +0000273 PrintF("Large object space, used: %8d, avaialble: %8d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000274 lo_space_->Size(),
275 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000276}
277#endif
278
279
280// TODO(1238405): Combine the infrastructure for --heap-stats and
281// --log-gc to avoid the complicated preprocessor and flag testing.
282void Heap::ReportStatisticsAfterGC() {
283 // Similar to the before GC, we use some complicated logic to ensure that
284 // NewSpace statistics are logged exactly once when --log-gc is turned on.
285#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
286 if (FLAG_heap_stats) {
287 new_space_.CollectStatistics();
288 ReportHeapStatistics("After GC");
289 } else if (FLAG_log_gc) {
290 new_space_.ReportStatistics();
291 }
292#elif defined(DEBUG)
293 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
294#elif defined(ENABLE_LOGGING_AND_PROFILING)
295 if (FLAG_log_gc) new_space_.ReportStatistics();
296#endif
297}
298#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
299
300
301void Heap::GarbageCollectionPrologue() {
302 TranscendentalCache::Clear();
303 gc_count_++;
304#ifdef DEBUG
305 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
306 allow_allocation(false);
307
308 if (FLAG_verify_heap) {
309 Verify();
310 }
311
312 if (FLAG_gc_verbose) Print();
313
314 if (FLAG_print_rset) {
315 // Not all spaces have remembered set bits that we care about.
316 old_pointer_space_->PrintRSet();
317 map_space_->PrintRSet();
318 lo_space_->PrintRSet();
319 }
320#endif
321
322#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
323 ReportStatisticsBeforeGC();
324#endif
325}
326
327int Heap::SizeOfObjects() {
328 int total = 0;
329 AllSpaces spaces;
330 while (Space* space = spaces.next()) {
331 total += space->Size();
332 }
333 return total;
334}
335
336void Heap::GarbageCollectionEpilogue() {
337#ifdef DEBUG
338 allow_allocation(true);
339 ZapFromSpace();
340
341 if (FLAG_verify_heap) {
342 Verify();
343 }
344
345 if (FLAG_print_global_handles) GlobalHandles::Print();
346 if (FLAG_print_handles) PrintHandles();
347 if (FLAG_gc_verbose) Print();
348 if (FLAG_code_stats) ReportCodeStatistics("After GC");
349#endif
350
351 Counters::alive_after_last_gc.Set(SizeOfObjects());
352
353 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
354 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
355#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
356 ReportStatisticsAfterGC();
357#endif
358#ifdef ENABLE_DEBUGGER_SUPPORT
359 Debug::AfterGarbageCollection();
360#endif
361}
362
363
364void Heap::CollectAllGarbage(bool force_compaction) {
365 // Since we are ignoring the return value, the exact choice of space does
366 // not matter, so long as we do not specify NEW_SPACE, which would not
367 // cause a full GC.
368 MarkCompactCollector::SetForceCompaction(force_compaction);
369 CollectGarbage(0, OLD_POINTER_SPACE);
370 MarkCompactCollector::SetForceCompaction(false);
371}
372
373
374void Heap::CollectAllGarbageIfContextDisposed() {
375 // If the garbage collector interface is exposed through the global
376 // gc() function, we avoid being clever about forcing GCs when
377 // contexts are disposed and leave it to the embedder to make
378 // informed decisions about when to force a collection.
379 if (!FLAG_expose_gc && context_disposed_pending_) {
380 HistogramTimerScope scope(&Counters::gc_context);
381 CollectAllGarbage(false);
382 }
383 context_disposed_pending_ = false;
384}
385
386
387void Heap::NotifyContextDisposed() {
388 context_disposed_pending_ = true;
389}
390
391
392bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
393 // The VM is in the GC state until exiting this function.
394 VMState state(GC);
395
396#ifdef DEBUG
397 // Reset the allocation timeout to the GC interval, but make sure to
398 // allow at least a few allocations after a collection. The reason
399 // for this is that we have a lot of allocation sequences and we
400 // assume that a garbage collection will allow the subsequent
401 // allocation attempts to go through.
402 allocation_timeout_ = Max(6, FLAG_gc_interval);
403#endif
404
405 { GCTracer tracer;
406 GarbageCollectionPrologue();
407 // The GC count was incremented in the prologue. Tell the tracer about
408 // it.
409 tracer.set_gc_count(gc_count_);
410
411 GarbageCollector collector = SelectGarbageCollector(space);
412 // Tell the tracer which collector we've selected.
413 tracer.set_collector(collector);
414
415 HistogramTimer* rate = (collector == SCAVENGER)
416 ? &Counters::gc_scavenger
417 : &Counters::gc_compactor;
418 rate->Start();
419 PerformGarbageCollection(space, collector, &tracer);
420 rate->Stop();
421
422 GarbageCollectionEpilogue();
423 }
424
425
426#ifdef ENABLE_LOGGING_AND_PROFILING
427 if (FLAG_log_gc) HeapProfiler::WriteSample();
428#endif
429
430 switch (space) {
431 case NEW_SPACE:
432 return new_space_.Available() >= requested_size;
433 case OLD_POINTER_SPACE:
434 return old_pointer_space_->Available() >= requested_size;
435 case OLD_DATA_SPACE:
436 return old_data_space_->Available() >= requested_size;
437 case CODE_SPACE:
438 return code_space_->Available() >= requested_size;
439 case MAP_SPACE:
440 return map_space_->Available() >= requested_size;
441 case CELL_SPACE:
442 return cell_space_->Available() >= requested_size;
443 case LO_SPACE:
444 return lo_space_->Available() >= requested_size;
445 }
446 return false;
447}
448
449
450void Heap::PerformScavenge() {
451 GCTracer tracer;
452 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
453}
454
455
456#ifdef DEBUG
457// Helper class for verifying the symbol table.
458class SymbolTableVerifier : public ObjectVisitor {
459 public:
460 SymbolTableVerifier() { }
461 void VisitPointers(Object** start, Object** end) {
462 // Visit all HeapObject pointers in [start, end).
463 for (Object** p = start; p < end; p++) {
464 if ((*p)->IsHeapObject()) {
465 // Check that the symbol is actually a symbol.
466 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
467 }
468 }
469 }
470};
471#endif // DEBUG
472
473
474static void VerifySymbolTable() {
475#ifdef DEBUG
476 SymbolTableVerifier verifier;
477 Heap::symbol_table()->IterateElements(&verifier);
478#endif // DEBUG
479}
480
481
482void Heap::EnsureFromSpaceIsCommitted() {
483 if (new_space_.CommitFromSpaceIfNeeded()) return;
484
485 // Committing memory to from space failed.
486 // Try shrinking and try again.
487 Shrink();
488 if (new_space_.CommitFromSpaceIfNeeded()) return;
489
490 // Committing memory to from space failed again.
491 // Memory is exhausted and we will die.
492 V8::FatalProcessOutOfMemory("Committing semi space failed.");
493}
494
495
496void Heap::PerformGarbageCollection(AllocationSpace space,
497 GarbageCollector collector,
498 GCTracer* tracer) {
499 VerifySymbolTable();
500 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
501 ASSERT(!allocation_allowed_);
502 global_gc_prologue_callback_();
503 }
504 EnsureFromSpaceIsCommitted();
505 if (collector == MARK_COMPACTOR) {
506 MarkCompact(tracer);
507
508 int old_gen_size = PromotedSpaceSize();
509 old_gen_promotion_limit_ =
510 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
511 old_gen_allocation_limit_ =
512 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
513 old_gen_exhausted_ = false;
514 }
515 Scavenge();
516
517 Counters::objs_since_last_young.Set(0);
518
Steve Block3ce2e202009-11-05 08:53:23 +0000519 if (collector == MARK_COMPACTOR) {
520 DisableAssertNoAllocation allow_allocation;
521 GlobalHandles::PostGarbageCollectionProcessing();
522 }
523
524 // Update relocatables.
525 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000526
527 if (collector == MARK_COMPACTOR) {
528 // Register the amount of external allocated memory.
529 amount_of_external_allocated_memory_at_last_global_gc_ =
530 amount_of_external_allocated_memory_;
531 }
532
533 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
534 ASSERT(!allocation_allowed_);
535 global_gc_epilogue_callback_();
536 }
537 VerifySymbolTable();
538}
539
540
Steve Blocka7e24c12009-10-30 11:49:00 +0000541void Heap::MarkCompact(GCTracer* tracer) {
542 gc_state_ = MARK_COMPACT;
543 mc_count_++;
544 tracer->set_full_gc_count(mc_count_);
545 LOG(ResourceEvent("markcompact", "begin"));
546
547 MarkCompactCollector::Prepare(tracer);
548
549 bool is_compacting = MarkCompactCollector::IsCompacting();
550
551 MarkCompactPrologue(is_compacting);
552
553 MarkCompactCollector::CollectGarbage();
554
555 MarkCompactEpilogue(is_compacting);
556
557 LOG(ResourceEvent("markcompact", "end"));
558
559 gc_state_ = NOT_IN_GC;
560
561 Shrink();
562
563 Counters::objs_since_last_full.Set(0);
564 context_disposed_pending_ = false;
565}
566
567
568void Heap::MarkCompactPrologue(bool is_compacting) {
569 // At any old GC clear the keyed lookup cache to enable collection of unused
570 // maps.
571 KeyedLookupCache::Clear();
572 ContextSlotCache::Clear();
573 DescriptorLookupCache::Clear();
574
575 CompilationCache::MarkCompactPrologue();
576
577 Top::MarkCompactPrologue(is_compacting);
578 ThreadManager::MarkCompactPrologue(is_compacting);
579}
580
581
582void Heap::MarkCompactEpilogue(bool is_compacting) {
583 Top::MarkCompactEpilogue(is_compacting);
584 ThreadManager::MarkCompactEpilogue(is_compacting);
585}
586
587
588Object* Heap::FindCodeObject(Address a) {
589 Object* obj = code_space_->FindObject(a);
590 if (obj->IsFailure()) {
591 obj = lo_space_->FindObject(a);
592 }
593 ASSERT(!obj->IsFailure());
594 return obj;
595}
596
597
598// Helper class for copying HeapObjects
599class ScavengeVisitor: public ObjectVisitor {
600 public:
601
602 void VisitPointer(Object** p) { ScavengePointer(p); }
603
604 void VisitPointers(Object** start, Object** end) {
605 // Copy all HeapObject pointers in [start, end)
606 for (Object** p = start; p < end; p++) ScavengePointer(p);
607 }
608
609 private:
610 void ScavengePointer(Object** p) {
611 Object* object = *p;
612 if (!Heap::InNewSpace(object)) return;
613 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
614 reinterpret_cast<HeapObject*>(object));
615 }
616};
617
618
619// A queue of pointers and maps of to-be-promoted objects during a
620// scavenge collection.
621class PromotionQueue {
622 public:
623 void Initialize(Address start_address) {
624 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
625 }
626
627 bool is_empty() { return front_ <= rear_; }
628
629 void insert(HeapObject* object, Map* map) {
630 *(--rear_) = object;
631 *(--rear_) = map;
632 // Assert no overflow into live objects.
633 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
634 }
635
636 void remove(HeapObject** object, Map** map) {
637 *object = *(--front_);
638 *map = Map::cast(*(--front_));
639 // Assert no underflow.
640 ASSERT(front_ >= rear_);
641 }
642
643 private:
644 // The front of the queue is higher in memory than the rear.
645 HeapObject** front_;
646 HeapObject** rear_;
647};
648
649
650// Shared state read by the scavenge collector and set by ScavengeObject.
651static PromotionQueue promotion_queue;
652
653
654#ifdef DEBUG
655// Visitor class to verify pointers in code or data space do not point into
656// new space.
657class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
658 public:
659 void VisitPointers(Object** start, Object**end) {
660 for (Object** current = start; current < end; current++) {
661 if ((*current)->IsHeapObject()) {
662 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
663 }
664 }
665 }
666};
667
668
669static void VerifyNonPointerSpacePointers() {
670 // Verify that there are no pointers to new space in spaces where we
671 // do not expect them.
672 VerifyNonPointerSpacePointersVisitor v;
673 HeapObjectIterator code_it(Heap::code_space());
674 while (code_it.has_next()) {
675 HeapObject* object = code_it.next();
676 object->Iterate(&v);
677 }
678
679 HeapObjectIterator data_it(Heap::old_data_space());
680 while (data_it.has_next()) data_it.next()->Iterate(&v);
681}
682#endif
683
684
685void Heap::Scavenge() {
686#ifdef DEBUG
687 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
688#endif
689
690 gc_state_ = SCAVENGE;
691
692 // Implements Cheney's copying algorithm
693 LOG(ResourceEvent("scavenge", "begin"));
694
695 // Clear descriptor cache.
696 DescriptorLookupCache::Clear();
697
698 // Used for updating survived_since_last_expansion_ at function end.
699 int survived_watermark = PromotedSpaceSize();
700
701 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
702 survived_since_last_expansion_ > new_space_.Capacity()) {
703 // Grow the size of new space if there is room to grow and enough
704 // data has survived scavenge since the last expansion.
705 new_space_.Grow();
706 survived_since_last_expansion_ = 0;
707 }
708
709 // Flip the semispaces. After flipping, to space is empty, from space has
710 // live objects.
711 new_space_.Flip();
712 new_space_.ResetAllocationInfo();
713
714 // We need to sweep newly copied objects which can be either in the
715 // to space or promoted to the old generation. For to-space
716 // objects, we treat the bottom of the to space as a queue. Newly
717 // copied and unswept objects lie between a 'front' mark and the
718 // allocation pointer.
719 //
720 // Promoted objects can go into various old-generation spaces, and
721 // can be allocated internally in the spaces (from the free list).
722 // We treat the top of the to space as a queue of addresses of
723 // promoted objects. The addresses of newly promoted and unswept
724 // objects lie between a 'front' mark and a 'rear' mark that is
725 // updated as a side effect of promoting an object.
726 //
727 // There is guaranteed to be enough room at the top of the to space
728 // for the addresses of promoted objects: every object promoted
729 // frees up its size in bytes from the top of the new space, and
730 // objects are at least one pointer in size.
731 Address new_space_front = new_space_.ToSpaceLow();
732 promotion_queue.Initialize(new_space_.ToSpaceHigh());
733
734 ScavengeVisitor scavenge_visitor;
735 // Copy roots.
Steve Blockd0582a62009-12-15 09:54:21 +0000736 IterateRoots(&scavenge_visitor, VISIT_ALL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000737
738 // Copy objects reachable from the old generation. By definition,
739 // there are no intergenerational pointers in code or data spaces.
740 IterateRSet(old_pointer_space_, &ScavengePointer);
741 IterateRSet(map_space_, &ScavengePointer);
742 lo_space_->IterateRSet(&ScavengePointer);
743
744 // Copy objects reachable from cells by scavenging cell values directly.
745 HeapObjectIterator cell_iterator(cell_space_);
746 while (cell_iterator.has_next()) {
747 HeapObject* cell = cell_iterator.next();
748 if (cell->IsJSGlobalPropertyCell()) {
749 Address value_address =
750 reinterpret_cast<Address>(cell) +
751 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
752 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
753 }
754 }
755
756 do {
757 ASSERT(new_space_front <= new_space_.top());
758
759 // The addresses new_space_front and new_space_.top() define a
760 // queue of unprocessed copied objects. Process them until the
761 // queue is empty.
762 while (new_space_front < new_space_.top()) {
763 HeapObject* object = HeapObject::FromAddress(new_space_front);
764 object->Iterate(&scavenge_visitor);
765 new_space_front += object->Size();
766 }
767
768 // Promote and process all the to-be-promoted objects.
769 while (!promotion_queue.is_empty()) {
770 HeapObject* source;
771 Map* map;
772 promotion_queue.remove(&source, &map);
773 // Copy the from-space object to its new location (given by the
774 // forwarding address) and fix its map.
775 HeapObject* target = source->map_word().ToForwardingAddress();
776 CopyBlock(reinterpret_cast<Object**>(target->address()),
777 reinterpret_cast<Object**>(source->address()),
778 source->SizeFromMap(map));
779 target->set_map(map);
780
781#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
782 // Update NewSpace stats if necessary.
783 RecordCopiedObject(target);
784#endif
785 // Visit the newly copied object for pointers to new space.
786 target->Iterate(&scavenge_visitor);
787 UpdateRSet(target);
788 }
789
790 // Take another spin if there are now unswept objects in new space
791 // (there are currently no more unswept promoted objects).
792 } while (new_space_front < new_space_.top());
793
794 // Set age mark.
795 new_space_.set_age_mark(new_space_.top());
796
797 // Update how much has survived scavenge.
798 survived_since_last_expansion_ +=
799 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
800
801 LOG(ResourceEvent("scavenge", "end"));
802
803 gc_state_ = NOT_IN_GC;
804}
805
806
807void Heap::ClearRSetRange(Address start, int size_in_bytes) {
808 uint32_t start_bit;
809 Address start_word_address =
810 Page::ComputeRSetBitPosition(start, 0, &start_bit);
811 uint32_t end_bit;
812 Address end_word_address =
813 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
814 0,
815 &end_bit);
816
817 // We want to clear the bits in the starting word starting with the
818 // first bit, and in the ending word up to and including the last
819 // bit. Build a pair of bitmasks to do that.
820 uint32_t start_bitmask = start_bit - 1;
821 uint32_t end_bitmask = ~((end_bit << 1) - 1);
822
823 // If the start address and end address are the same, we mask that
824 // word once, otherwise mask the starting and ending word
825 // separately and all the ones in between.
826 if (start_word_address == end_word_address) {
827 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
828 } else {
829 Memory::uint32_at(start_word_address) &= start_bitmask;
830 Memory::uint32_at(end_word_address) &= end_bitmask;
831 start_word_address += kIntSize;
832 memset(start_word_address, 0, end_word_address - start_word_address);
833 }
834}
835
836
837class UpdateRSetVisitor: public ObjectVisitor {
838 public:
839
840 void VisitPointer(Object** p) {
841 UpdateRSet(p);
842 }
843
844 void VisitPointers(Object** start, Object** end) {
845 // Update a store into slots [start, end), used (a) to update remembered
846 // set when promoting a young object to old space or (b) to rebuild
847 // remembered sets after a mark-compact collection.
848 for (Object** p = start; p < end; p++) UpdateRSet(p);
849 }
850 private:
851
852 void UpdateRSet(Object** p) {
853 // The remembered set should not be set. It should be clear for objects
854 // newly copied to old space, and it is cleared before rebuilding in the
855 // mark-compact collector.
856 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
857 if (Heap::InNewSpace(*p)) {
858 Page::SetRSet(reinterpret_cast<Address>(p), 0);
859 }
860 }
861};
862
863
864int Heap::UpdateRSet(HeapObject* obj) {
865 ASSERT(!InNewSpace(obj));
866 // Special handling of fixed arrays to iterate the body based on the start
867 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
868 // will not work because Page::SetRSet needs to have the start of the
869 // object for large object pages.
870 if (obj->IsFixedArray()) {
871 FixedArray* array = FixedArray::cast(obj);
872 int length = array->length();
873 for (int i = 0; i < length; i++) {
874 int offset = FixedArray::kHeaderSize + i * kPointerSize;
875 ASSERT(!Page::IsRSetSet(obj->address(), offset));
876 if (Heap::InNewSpace(array->get(i))) {
877 Page::SetRSet(obj->address(), offset);
878 }
879 }
880 } else if (!obj->IsCode()) {
881 // Skip code object, we know it does not contain inter-generational
882 // pointers.
883 UpdateRSetVisitor v;
884 obj->Iterate(&v);
885 }
886 return obj->Size();
887}
888
889
890void Heap::RebuildRSets() {
891 // By definition, we do not care about remembered set bits in code,
892 // data, or cell spaces.
893 map_space_->ClearRSet();
894 RebuildRSets(map_space_);
895
896 old_pointer_space_->ClearRSet();
897 RebuildRSets(old_pointer_space_);
898
899 Heap::lo_space_->ClearRSet();
900 RebuildRSets(lo_space_);
901}
902
903
904void Heap::RebuildRSets(PagedSpace* space) {
905 HeapObjectIterator it(space);
906 while (it.has_next()) Heap::UpdateRSet(it.next());
907}
908
909
910void Heap::RebuildRSets(LargeObjectSpace* space) {
911 LargeObjectIterator it(space);
912 while (it.has_next()) Heap::UpdateRSet(it.next());
913}
914
915
916#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
917void Heap::RecordCopiedObject(HeapObject* obj) {
918 bool should_record = false;
919#ifdef DEBUG
920 should_record = FLAG_heap_stats;
921#endif
922#ifdef ENABLE_LOGGING_AND_PROFILING
923 should_record = should_record || FLAG_log_gc;
924#endif
925 if (should_record) {
926 if (new_space_.Contains(obj)) {
927 new_space_.RecordAllocation(obj);
928 } else {
929 new_space_.RecordPromotion(obj);
930 }
931 }
932}
933#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
934
935
936
937HeapObject* Heap::MigrateObject(HeapObject* source,
938 HeapObject* target,
939 int size) {
940 // Copy the content of source to target.
941 CopyBlock(reinterpret_cast<Object**>(target->address()),
942 reinterpret_cast<Object**>(source->address()),
943 size);
944
945 // Set the forwarding address.
946 source->set_map_word(MapWord::FromForwardingAddress(target));
947
948#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
949 // Update NewSpace stats if necessary.
950 RecordCopiedObject(target);
951#endif
952
953 return target;
954}
955
956
957static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
958 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
959 ASSERT(object->map() == map);
960 InstanceType type = map->instance_type();
961 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
962 ASSERT(object->IsString() && !object->IsSymbol());
963 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
964}
965
966
967void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
968 ASSERT(InFromSpace(object));
969 MapWord first_word = object->map_word();
970 ASSERT(!first_word.IsForwardingAddress());
971
972 // Optimization: Bypass flattened ConsString objects.
973 if (IsShortcutCandidate(object, first_word.ToMap())) {
974 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
975 *p = object;
976 // After patching *p we have to repeat the checks that object is in the
977 // active semispace of the young generation and not already copied.
978 if (!InNewSpace(object)) return;
979 first_word = object->map_word();
980 if (first_word.IsForwardingAddress()) {
981 *p = first_word.ToForwardingAddress();
982 return;
983 }
984 }
985
986 int object_size = object->SizeFromMap(first_word.ToMap());
987 // We rely on live objects in new space to be at least two pointers,
988 // so we can store the from-space address and map pointer of promoted
989 // objects in the to space.
990 ASSERT(object_size >= 2 * kPointerSize);
991
992 // If the object should be promoted, we try to copy it to old space.
993 if (ShouldBePromoted(object->address(), object_size)) {
994 Object* result;
995 if (object_size > MaxObjectSizeInPagedSpace()) {
996 result = lo_space_->AllocateRawFixedArray(object_size);
997 if (!result->IsFailure()) {
998 // Save the from-space object pointer and its map pointer at the
999 // top of the to space to be swept and copied later. Write the
1000 // forwarding address over the map word of the from-space
1001 // object.
1002 HeapObject* target = HeapObject::cast(result);
1003 promotion_queue.insert(object, first_word.ToMap());
1004 object->set_map_word(MapWord::FromForwardingAddress(target));
1005
1006 // Give the space allocated for the result a proper map by
1007 // treating it as a free list node (not linked into the free
1008 // list).
1009 FreeListNode* node = FreeListNode::FromAddress(target->address());
1010 node->set_size(object_size);
1011
1012 *p = target;
1013 return;
1014 }
1015 } else {
1016 OldSpace* target_space = Heap::TargetSpace(object);
1017 ASSERT(target_space == Heap::old_pointer_space_ ||
1018 target_space == Heap::old_data_space_);
1019 result = target_space->AllocateRaw(object_size);
1020 if (!result->IsFailure()) {
1021 HeapObject* target = HeapObject::cast(result);
1022 if (target_space == Heap::old_pointer_space_) {
1023 // Save the from-space object pointer and its map pointer at the
1024 // top of the to space to be swept and copied later. Write the
1025 // forwarding address over the map word of the from-space
1026 // object.
1027 promotion_queue.insert(object, first_word.ToMap());
1028 object->set_map_word(MapWord::FromForwardingAddress(target));
1029
1030 // Give the space allocated for the result a proper map by
1031 // treating it as a free list node (not linked into the free
1032 // list).
1033 FreeListNode* node = FreeListNode::FromAddress(target->address());
1034 node->set_size(object_size);
1035
1036 *p = target;
1037 } else {
1038 // Objects promoted to the data space can be copied immediately
1039 // and not revisited---we will never sweep that space for
1040 // pointers and the copied objects do not contain pointers to
1041 // new space objects.
1042 *p = MigrateObject(object, target, object_size);
1043#ifdef DEBUG
1044 VerifyNonPointerSpacePointersVisitor v;
1045 (*p)->Iterate(&v);
1046#endif
1047 }
1048 return;
1049 }
1050 }
1051 }
1052 // The object should remain in new space or the old space allocation failed.
1053 Object* result = new_space_.AllocateRaw(object_size);
1054 // Failed allocation at this point is utterly unexpected.
1055 ASSERT(!result->IsFailure());
1056 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1057}
1058
1059
1060void Heap::ScavengePointer(HeapObject** p) {
1061 ScavengeObject(p, *p);
1062}
1063
1064
1065Object* Heap::AllocatePartialMap(InstanceType instance_type,
1066 int instance_size) {
1067 Object* result = AllocateRawMap();
1068 if (result->IsFailure()) return result;
1069
1070 // Map::cast cannot be used due to uninitialized map field.
1071 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1072 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1073 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
1074 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
1075 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1076 return result;
1077}
1078
1079
1080Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
1081 Object* result = AllocateRawMap();
1082 if (result->IsFailure()) return result;
1083
1084 Map* map = reinterpret_cast<Map*>(result);
1085 map->set_map(meta_map());
1086 map->set_instance_type(instance_type);
1087 map->set_prototype(null_value());
1088 map->set_constructor(null_value());
1089 map->set_instance_size(instance_size);
1090 map->set_inobject_properties(0);
1091 map->set_pre_allocated_property_fields(0);
1092 map->set_instance_descriptors(empty_descriptor_array());
1093 map->set_code_cache(empty_fixed_array());
1094 map->set_unused_property_fields(0);
1095 map->set_bit_field(0);
1096 map->set_bit_field2(0);
1097 return map;
1098}
1099
1100
1101const Heap::StringTypeTable Heap::string_type_table[] = {
1102#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1103 {type, size, k##camel_name##MapRootIndex},
1104 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1105#undef STRING_TYPE_ELEMENT
1106};
1107
1108
1109const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1110#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1111 {contents, k##name##RootIndex},
1112 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1113#undef CONSTANT_SYMBOL_ELEMENT
1114};
1115
1116
1117const Heap::StructTable Heap::struct_table[] = {
1118#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1119 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1120 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1121#undef STRUCT_TABLE_ELEMENT
1122};
1123
1124
1125bool Heap::CreateInitialMaps() {
1126 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1127 if (obj->IsFailure()) return false;
1128 // Map::cast cannot be used due to uninitialized map field.
1129 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1130 set_meta_map(new_meta_map);
1131 new_meta_map->set_map(new_meta_map);
1132
1133 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
1134 if (obj->IsFailure()) return false;
1135 set_fixed_array_map(Map::cast(obj));
1136
1137 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1138 if (obj->IsFailure()) return false;
1139 set_oddball_map(Map::cast(obj));
1140
1141 // Allocate the empty array
1142 obj = AllocateEmptyFixedArray();
1143 if (obj->IsFailure()) return false;
1144 set_empty_fixed_array(FixedArray::cast(obj));
1145
1146 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1147 if (obj->IsFailure()) return false;
1148 set_null_value(obj);
1149
1150 // Allocate the empty descriptor array.
1151 obj = AllocateEmptyFixedArray();
1152 if (obj->IsFailure()) return false;
1153 set_empty_descriptor_array(DescriptorArray::cast(obj));
1154
1155 // Fix the instance_descriptors for the existing maps.
1156 meta_map()->set_instance_descriptors(empty_descriptor_array());
1157 meta_map()->set_code_cache(empty_fixed_array());
1158
1159 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
1160 fixed_array_map()->set_code_cache(empty_fixed_array());
1161
1162 oddball_map()->set_instance_descriptors(empty_descriptor_array());
1163 oddball_map()->set_code_cache(empty_fixed_array());
1164
1165 // Fix prototype object for existing maps.
1166 meta_map()->set_prototype(null_value());
1167 meta_map()->set_constructor(null_value());
1168
1169 fixed_array_map()->set_prototype(null_value());
1170 fixed_array_map()->set_constructor(null_value());
1171
1172 oddball_map()->set_prototype(null_value());
1173 oddball_map()->set_constructor(null_value());
1174
1175 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1176 if (obj->IsFailure()) return false;
1177 set_heap_number_map(Map::cast(obj));
1178
1179 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1180 if (obj->IsFailure()) return false;
1181 set_proxy_map(Map::cast(obj));
1182
1183 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1184 const StringTypeTable& entry = string_type_table[i];
1185 obj = AllocateMap(entry.type, entry.size);
1186 if (obj->IsFailure()) return false;
1187 roots_[entry.index] = Map::cast(obj);
1188 }
1189
Steve Blockd0582a62009-12-15 09:54:21 +00001190 obj = AllocateMap(STRING_TYPE, SeqTwoByteString::kAlignedSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00001191 if (obj->IsFailure()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00001192 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001193 Map::cast(obj)->set_is_undetectable();
1194
Steve Blockd0582a62009-12-15 09:54:21 +00001195 obj = AllocateMap(ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00001196 if (obj->IsFailure()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00001197 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001198 Map::cast(obj)->set_is_undetectable();
1199
1200 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
1201 if (obj->IsFailure()) return false;
1202 set_byte_array_map(Map::cast(obj));
1203
1204 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1205 if (obj->IsFailure()) return false;
1206 set_pixel_array_map(Map::cast(obj));
1207
Steve Block3ce2e202009-11-05 08:53:23 +00001208 obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1209 ExternalArray::kAlignedSize);
1210 if (obj->IsFailure()) return false;
1211 set_external_byte_array_map(Map::cast(obj));
1212
1213 obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1214 ExternalArray::kAlignedSize);
1215 if (obj->IsFailure()) return false;
1216 set_external_unsigned_byte_array_map(Map::cast(obj));
1217
1218 obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1219 ExternalArray::kAlignedSize);
1220 if (obj->IsFailure()) return false;
1221 set_external_short_array_map(Map::cast(obj));
1222
1223 obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1224 ExternalArray::kAlignedSize);
1225 if (obj->IsFailure()) return false;
1226 set_external_unsigned_short_array_map(Map::cast(obj));
1227
1228 obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1229 ExternalArray::kAlignedSize);
1230 if (obj->IsFailure()) return false;
1231 set_external_int_array_map(Map::cast(obj));
1232
1233 obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1234 ExternalArray::kAlignedSize);
1235 if (obj->IsFailure()) return false;
1236 set_external_unsigned_int_array_map(Map::cast(obj));
1237
1238 obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1239 ExternalArray::kAlignedSize);
1240 if (obj->IsFailure()) return false;
1241 set_external_float_array_map(Map::cast(obj));
1242
Steve Blocka7e24c12009-10-30 11:49:00 +00001243 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1244 if (obj->IsFailure()) return false;
1245 set_code_map(Map::cast(obj));
1246
1247 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1248 JSGlobalPropertyCell::kSize);
1249 if (obj->IsFailure()) return false;
1250 set_global_property_cell_map(Map::cast(obj));
1251
1252 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1253 if (obj->IsFailure()) return false;
1254 set_one_pointer_filler_map(Map::cast(obj));
1255
1256 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1257 if (obj->IsFailure()) return false;
1258 set_two_pointer_filler_map(Map::cast(obj));
1259
1260 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1261 const StructTable& entry = struct_table[i];
1262 obj = AllocateMap(entry.type, entry.size);
1263 if (obj->IsFailure()) return false;
1264 roots_[entry.index] = Map::cast(obj);
1265 }
1266
1267 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1268 if (obj->IsFailure()) return false;
1269 set_hash_table_map(Map::cast(obj));
1270
1271 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1272 if (obj->IsFailure()) return false;
1273 set_context_map(Map::cast(obj));
1274
1275 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1276 if (obj->IsFailure()) return false;
1277 set_catch_context_map(Map::cast(obj));
1278
1279 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1280 if (obj->IsFailure()) return false;
1281 set_global_context_map(Map::cast(obj));
1282
1283 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1284 if (obj->IsFailure()) return false;
1285 set_boilerplate_function_map(Map::cast(obj));
1286
1287 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1288 if (obj->IsFailure()) return false;
1289 set_shared_function_info_map(Map::cast(obj));
1290
1291 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
1292 return true;
1293}
1294
1295
1296Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1297 // Statically ensure that it is safe to allocate heap numbers in paged
1298 // spaces.
1299 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1300 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1301
1302 // New space can't cope with forced allocation.
1303 if (always_allocate()) space = OLD_DATA_SPACE;
1304
1305 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
1306 if (result->IsFailure()) return result;
1307
1308 HeapObject::cast(result)->set_map(heap_number_map());
1309 HeapNumber::cast(result)->set_value(value);
1310 return result;
1311}
1312
1313
1314Object* Heap::AllocateHeapNumber(double value) {
1315 // Use general version, if we're forced to always allocate.
1316 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1317
1318 // This version of AllocateHeapNumber is optimized for
1319 // allocation in new space.
1320 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1321 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1322 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
1323 if (result->IsFailure()) return result;
1324 HeapObject::cast(result)->set_map(heap_number_map());
1325 HeapNumber::cast(result)->set_value(value);
1326 return result;
1327}
1328
1329
1330Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
1331 Object* result = AllocateRawCell();
1332 if (result->IsFailure()) return result;
1333 HeapObject::cast(result)->set_map(global_property_cell_map());
1334 JSGlobalPropertyCell::cast(result)->set_value(value);
1335 return result;
1336}
1337
1338
1339Object* Heap::CreateOddball(Map* map,
1340 const char* to_string,
1341 Object* to_number) {
1342 Object* result = Allocate(map, OLD_DATA_SPACE);
1343 if (result->IsFailure()) return result;
1344 return Oddball::cast(result)->Initialize(to_string, to_number);
1345}
1346
1347
1348bool Heap::CreateApiObjects() {
1349 Object* obj;
1350
1351 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1352 if (obj->IsFailure()) return false;
1353 set_neander_map(Map::cast(obj));
1354
1355 obj = Heap::AllocateJSObjectFromMap(neander_map());
1356 if (obj->IsFailure()) return false;
1357 Object* elements = AllocateFixedArray(2);
1358 if (elements->IsFailure()) return false;
1359 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1360 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1361 set_message_listeners(JSObject::cast(obj));
1362
1363 return true;
1364}
1365
1366
1367void Heap::CreateCEntryStub() {
1368 CEntryStub stub(1);
1369 set_c_entry_code(*stub.GetCode());
1370}
1371
1372
1373#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1374void Heap::CreateRegExpCEntryStub() {
1375 RegExpCEntryStub stub;
1376 set_re_c_entry_code(*stub.GetCode());
1377}
1378#endif
1379
1380
1381void Heap::CreateCEntryDebugBreakStub() {
1382 CEntryDebugBreakStub stub;
1383 set_c_entry_debug_break_code(*stub.GetCode());
1384}
1385
1386
1387void Heap::CreateJSEntryStub() {
1388 JSEntryStub stub;
1389 set_js_entry_code(*stub.GetCode());
1390}
1391
1392
1393void Heap::CreateJSConstructEntryStub() {
1394 JSConstructEntryStub stub;
1395 set_js_construct_entry_code(*stub.GetCode());
1396}
1397
1398
1399void Heap::CreateFixedStubs() {
1400 // Here we create roots for fixed stubs. They are needed at GC
1401 // for cooking and uncooking (check out frames.cc).
1402 // The eliminates the need for doing dictionary lookup in the
1403 // stub cache for these stubs.
1404 HandleScope scope;
1405 // gcc-4.4 has problem generating correct code of following snippet:
1406 // { CEntryStub stub;
1407 // c_entry_code_ = *stub.GetCode();
1408 // }
1409 // { CEntryDebugBreakStub stub;
1410 // c_entry_debug_break_code_ = *stub.GetCode();
1411 // }
1412 // To workaround the problem, make separate functions without inlining.
1413 Heap::CreateCEntryStub();
1414 Heap::CreateCEntryDebugBreakStub();
1415 Heap::CreateJSEntryStub();
1416 Heap::CreateJSConstructEntryStub();
1417#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1418 Heap::CreateRegExpCEntryStub();
1419#endif
1420}
1421
1422
1423bool Heap::CreateInitialObjects() {
1424 Object* obj;
1425
1426 // The -0 value must be set before NumberFromDouble works.
1427 obj = AllocateHeapNumber(-0.0, TENURED);
1428 if (obj->IsFailure()) return false;
1429 set_minus_zero_value(obj);
1430 ASSERT(signbit(minus_zero_value()->Number()) != 0);
1431
1432 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1433 if (obj->IsFailure()) return false;
1434 set_nan_value(obj);
1435
1436 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1437 if (obj->IsFailure()) return false;
1438 set_undefined_value(obj);
1439 ASSERT(!InNewSpace(undefined_value()));
1440
1441 // Allocate initial symbol table.
1442 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1443 if (obj->IsFailure()) return false;
1444 // Don't use set_symbol_table() due to asserts.
1445 roots_[kSymbolTableRootIndex] = obj;
1446
1447 // Assign the print strings for oddballs after creating symboltable.
1448 Object* symbol = LookupAsciiSymbol("undefined");
1449 if (symbol->IsFailure()) return false;
1450 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1451 Oddball::cast(undefined_value())->set_to_number(nan_value());
1452
1453 // Assign the print strings for oddballs after creating symboltable.
1454 symbol = LookupAsciiSymbol("null");
1455 if (symbol->IsFailure()) return false;
1456 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1457 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
1458
1459 // Allocate the null_value
1460 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1461 if (obj->IsFailure()) return false;
1462
1463 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1464 if (obj->IsFailure()) return false;
1465 set_true_value(obj);
1466
1467 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1468 if (obj->IsFailure()) return false;
1469 set_false_value(obj);
1470
1471 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1472 if (obj->IsFailure()) return false;
1473 set_the_hole_value(obj);
1474
1475 obj = CreateOddball(
1476 oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
1477 if (obj->IsFailure()) return false;
1478 set_no_interceptor_result_sentinel(obj);
1479
1480 obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
1481 if (obj->IsFailure()) return false;
1482 set_termination_exception(obj);
1483
1484 // Allocate the empty string.
1485 obj = AllocateRawAsciiString(0, TENURED);
1486 if (obj->IsFailure()) return false;
1487 set_empty_string(String::cast(obj));
1488
1489 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1490 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1491 if (obj->IsFailure()) return false;
1492 roots_[constant_symbol_table[i].index] = String::cast(obj);
1493 }
1494
1495 // Allocate the hidden symbol which is used to identify the hidden properties
1496 // in JSObjects. The hash code has a special value so that it will not match
1497 // the empty string when searching for the property. It cannot be part of the
1498 // loop above because it needs to be allocated manually with the special
1499 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1500 // that it will always be at the first entry in property descriptors.
1501 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1502 if (obj->IsFailure()) return false;
1503 hidden_symbol_ = String::cast(obj);
1504
1505 // Allocate the proxy for __proto__.
1506 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1507 if (obj->IsFailure()) return false;
1508 set_prototype_accessors(Proxy::cast(obj));
1509
1510 // Allocate the code_stubs dictionary. The initial size is set to avoid
1511 // expanding the dictionary during bootstrapping.
1512 obj = NumberDictionary::Allocate(128);
1513 if (obj->IsFailure()) return false;
1514 set_code_stubs(NumberDictionary::cast(obj));
1515
1516 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1517 // is set to avoid expanding the dictionary during bootstrapping.
1518 obj = NumberDictionary::Allocate(64);
1519 if (obj->IsFailure()) return false;
1520 set_non_monomorphic_cache(NumberDictionary::cast(obj));
1521
1522 CreateFixedStubs();
1523
1524 // Allocate the number->string conversion cache
1525 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1526 if (obj->IsFailure()) return false;
1527 set_number_string_cache(FixedArray::cast(obj));
1528
1529 // Allocate cache for single character strings.
1530 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1531 if (obj->IsFailure()) return false;
1532 set_single_character_string_cache(FixedArray::cast(obj));
1533
1534 // Allocate cache for external strings pointing to native source code.
1535 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1536 if (obj->IsFailure()) return false;
1537 set_natives_source_cache(FixedArray::cast(obj));
1538
1539 // Handling of script id generation is in Factory::NewScript.
1540 set_last_script_id(undefined_value());
1541
1542 // Initialize keyed lookup cache.
1543 KeyedLookupCache::Clear();
1544
1545 // Initialize context slot cache.
1546 ContextSlotCache::Clear();
1547
1548 // Initialize descriptor cache.
1549 DescriptorLookupCache::Clear();
1550
1551 // Initialize compilation cache.
1552 CompilationCache::Clear();
1553
1554 return true;
1555}
1556
1557
1558static inline int double_get_hash(double d) {
1559 DoubleRepresentation rep(d);
1560 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1561 (Heap::kNumberStringCacheSize - 1));
1562}
1563
1564
1565static inline int smi_get_hash(Smi* smi) {
1566 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1567}
1568
1569
1570
1571Object* Heap::GetNumberStringCache(Object* number) {
1572 int hash;
1573 if (number->IsSmi()) {
1574 hash = smi_get_hash(Smi::cast(number));
1575 } else {
1576 hash = double_get_hash(number->Number());
1577 }
1578 Object* key = number_string_cache()->get(hash * 2);
1579 if (key == number) {
1580 return String::cast(number_string_cache()->get(hash * 2 + 1));
1581 } else if (key->IsHeapNumber() &&
1582 number->IsHeapNumber() &&
1583 key->Number() == number->Number()) {
1584 return String::cast(number_string_cache()->get(hash * 2 + 1));
1585 }
1586 return undefined_value();
1587}
1588
1589
1590void Heap::SetNumberStringCache(Object* number, String* string) {
1591 int hash;
1592 if (number->IsSmi()) {
1593 hash = smi_get_hash(Smi::cast(number));
1594 number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
1595 } else {
1596 hash = double_get_hash(number->Number());
1597 number_string_cache()->set(hash * 2, number);
1598 }
1599 number_string_cache()->set(hash * 2 + 1, string);
1600}
1601
1602
1603Object* Heap::SmiOrNumberFromDouble(double value,
1604 bool new_object,
1605 PretenureFlag pretenure) {
1606 // We need to distinguish the minus zero value and this cannot be
1607 // done after conversion to int. Doing this by comparing bit
1608 // patterns is faster than using fpclassify() et al.
1609 static const DoubleRepresentation plus_zero(0.0);
1610 static const DoubleRepresentation minus_zero(-0.0);
1611 static const DoubleRepresentation nan(OS::nan_value());
1612 ASSERT(minus_zero_value() != NULL);
1613 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1614
1615 DoubleRepresentation rep(value);
1616 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1617 if (rep.bits == minus_zero.bits) {
1618 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1619 : minus_zero_value();
1620 }
1621 if (rep.bits == nan.bits) {
1622 return new_object
1623 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1624 : nan_value();
1625 }
1626
1627 // Try to represent the value as a tagged small integer.
1628 int int_value = FastD2I(value);
1629 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1630 return Smi::FromInt(int_value);
1631 }
1632
1633 // Materialize the value in the heap.
1634 return AllocateHeapNumber(value, pretenure);
1635}
1636
1637
1638Object* Heap::NumberToString(Object* number) {
1639 Object* cached = GetNumberStringCache(number);
1640 if (cached != undefined_value()) {
1641 return cached;
1642 }
1643
1644 char arr[100];
1645 Vector<char> buffer(arr, ARRAY_SIZE(arr));
1646 const char* str;
1647 if (number->IsSmi()) {
1648 int num = Smi::cast(number)->value();
1649 str = IntToCString(num, buffer);
1650 } else {
1651 double num = HeapNumber::cast(number)->value();
1652 str = DoubleToCString(num, buffer);
1653 }
1654 Object* result = AllocateStringFromAscii(CStrVector(str));
1655
1656 if (!result->IsFailure()) {
1657 SetNumberStringCache(number, String::cast(result));
1658 }
1659 return result;
1660}
1661
1662
Steve Block3ce2e202009-11-05 08:53:23 +00001663Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
1664 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
1665}
1666
1667
1668Heap::RootListIndex Heap::RootIndexForExternalArrayType(
1669 ExternalArrayType array_type) {
1670 switch (array_type) {
1671 case kExternalByteArray:
1672 return kExternalByteArrayMapRootIndex;
1673 case kExternalUnsignedByteArray:
1674 return kExternalUnsignedByteArrayMapRootIndex;
1675 case kExternalShortArray:
1676 return kExternalShortArrayMapRootIndex;
1677 case kExternalUnsignedShortArray:
1678 return kExternalUnsignedShortArrayMapRootIndex;
1679 case kExternalIntArray:
1680 return kExternalIntArrayMapRootIndex;
1681 case kExternalUnsignedIntArray:
1682 return kExternalUnsignedIntArrayMapRootIndex;
1683 case kExternalFloatArray:
1684 return kExternalFloatArrayMapRootIndex;
1685 default:
1686 UNREACHABLE();
1687 return kUndefinedValueRootIndex;
1688 }
1689}
1690
1691
Steve Blocka7e24c12009-10-30 11:49:00 +00001692Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1693 return SmiOrNumberFromDouble(value,
1694 true /* number object must be new */,
1695 pretenure);
1696}
1697
1698
1699Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1700 return SmiOrNumberFromDouble(value,
1701 false /* use preallocated NaN, -0.0 */,
1702 pretenure);
1703}
1704
1705
1706Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1707 // Statically ensure that it is safe to allocate proxies in paged spaces.
1708 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
1709 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
Steve Blockd0582a62009-12-15 09:54:21 +00001710 if (always_allocate()) space = OLD_DATA_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00001711 Object* result = Allocate(proxy_map(), space);
1712 if (result->IsFailure()) return result;
1713
1714 Proxy::cast(result)->set_proxy(proxy);
1715 return result;
1716}
1717
1718
1719Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1720 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
1721 if (result->IsFailure()) return result;
1722
1723 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1724 share->set_name(name);
1725 Code* illegal = Builtins::builtin(Builtins::Illegal);
1726 share->set_code(illegal);
1727 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1728 share->set_construct_stub(construct_stub);
1729 share->set_expected_nof_properties(0);
1730 share->set_length(0);
1731 share->set_formal_parameter_count(0);
1732 share->set_instance_class_name(Object_symbol());
1733 share->set_function_data(undefined_value());
1734 share->set_script(undefined_value());
1735 share->set_start_position_and_type(0);
1736 share->set_debug_info(undefined_value());
1737 share->set_inferred_name(empty_string());
1738 share->set_compiler_hints(0);
1739 share->set_this_property_assignments_count(0);
1740 share->set_this_property_assignments(undefined_value());
1741 return result;
1742}
1743
1744
Steve Blockd0582a62009-12-15 09:54:21 +00001745// Returns true for a character in a range. Both limits are inclusive.
1746static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
1747 // This makes uses of the the unsigned wraparound.
1748 return character - from <= to - from;
1749}
1750
1751
1752static inline Object* MakeOrFindTwoCharacterString(uint32_t c1, uint32_t c2) {
1753 String* symbol;
1754 // Numeric strings have a different hash algorithm not known by
1755 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
1756 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
1757 Heap::symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
1758 return symbol;
1759 // Now we know the length is 2, we might as well make use of that fact
1760 // when building the new string.
1761 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
1762 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
1763 Object* result = Heap::AllocateRawAsciiString(2);
1764 if (result->IsFailure()) return result;
1765 char* dest = SeqAsciiString::cast(result)->GetChars();
1766 dest[0] = c1;
1767 dest[1] = c2;
1768 return result;
1769 } else {
1770 Object* result = Heap::AllocateRawTwoByteString(2);
1771 if (result->IsFailure()) return result;
1772 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1773 dest[0] = c1;
1774 dest[1] = c2;
1775 return result;
1776 }
1777}
1778
1779
Steve Blocka7e24c12009-10-30 11:49:00 +00001780Object* Heap::AllocateConsString(String* first, String* second) {
1781 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00001782 if (first_length == 0) {
1783 return second;
1784 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001785
1786 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00001787 if (second_length == 0) {
1788 return first;
1789 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001790
1791 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00001792
1793 // Optimization for 2-byte strings often used as keys in a decompression
1794 // dictionary. Check whether we already have the string in the symbol
1795 // table to prevent creation of many unneccesary strings.
1796 if (length == 2) {
1797 unsigned c1 = first->Get(0);
1798 unsigned c2 = second->Get(0);
1799 return MakeOrFindTwoCharacterString(c1, c2);
1800 }
1801
Steve Blocka7e24c12009-10-30 11:49:00 +00001802 bool is_ascii = first->IsAsciiRepresentation()
1803 && second->IsAsciiRepresentation();
1804
1805 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00001806 // of the new cons string is too large.
1807 if (length > String::kMaxLength || length < 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001808 Top::context()->mark_out_of_memory();
1809 return Failure::OutOfMemoryException();
1810 }
1811
1812 // If the resulting string is small make a flat string.
1813 if (length < String::kMinNonFlatLength) {
1814 ASSERT(first->IsFlat());
1815 ASSERT(second->IsFlat());
1816 if (is_ascii) {
1817 Object* result = AllocateRawAsciiString(length);
1818 if (result->IsFailure()) return result;
1819 // Copy the characters into the new object.
1820 char* dest = SeqAsciiString::cast(result)->GetChars();
1821 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00001822 const char* src;
1823 if (first->IsExternalString()) {
1824 src = ExternalAsciiString::cast(first)->resource()->data();
1825 } else {
1826 src = SeqAsciiString::cast(first)->GetChars();
1827 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001828 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1829 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00001830 if (second->IsExternalString()) {
1831 src = ExternalAsciiString::cast(second)->resource()->data();
1832 } else {
1833 src = SeqAsciiString::cast(second)->GetChars();
1834 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001835 for (int i = 0; i < second_length; i++) *dest++ = src[i];
1836 return result;
1837 } else {
1838 Object* result = AllocateRawTwoByteString(length);
1839 if (result->IsFailure()) return result;
1840 // Copy the characters into the new object.
1841 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1842 String::WriteToFlat(first, dest, 0, first_length);
1843 String::WriteToFlat(second, dest + first_length, 0, second_length);
1844 return result;
1845 }
1846 }
1847
Steve Blockd0582a62009-12-15 09:54:21 +00001848 Map* map = is_ascii ? cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00001849
Steve Blockd0582a62009-12-15 09:54:21 +00001850 Object* result = Allocate(map,
1851 always_allocate() ? OLD_POINTER_SPACE : NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001852 if (result->IsFailure()) return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00001853 ConsString* cons_string = ConsString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00001854 WriteBarrierMode mode = cons_string->GetWriteBarrierMode();
Steve Blocka7e24c12009-10-30 11:49:00 +00001855 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00001856 cons_string->set_hash_field(String::kEmptyHashField);
1857 cons_string->set_first(first, mode);
1858 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00001859 return result;
1860}
1861
1862
1863Object* Heap::AllocateSubString(String* buffer,
1864 int start,
1865 int end) {
1866 int length = end - start;
1867
1868 if (length == 1) {
1869 return Heap::LookupSingleCharacterStringFromCode(
1870 buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00001871 } else if (length == 2) {
1872 // Optimization for 2-byte strings often used as keys in a decompression
1873 // dictionary. Check whether we already have the string in the symbol
1874 // table to prevent creation of many unneccesary strings.
1875 unsigned c1 = buffer->Get(start);
1876 unsigned c2 = buffer->Get(start + 1);
1877 return MakeOrFindTwoCharacterString(c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00001878 }
1879
1880 // Make an attempt to flatten the buffer to reduce access time.
1881 if (!buffer->IsFlat()) {
1882 buffer->TryFlatten();
1883 }
1884
1885 Object* result = buffer->IsAsciiRepresentation()
1886 ? AllocateRawAsciiString(length)
1887 : AllocateRawTwoByteString(length);
1888 if (result->IsFailure()) return result;
Steve Blockd0582a62009-12-15 09:54:21 +00001889 String* string_result = String::cast(result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001890
1891 // Copy the characters into the new object.
Steve Blockd0582a62009-12-15 09:54:21 +00001892 if (buffer->IsAsciiRepresentation()) {
1893 ASSERT(string_result->IsAsciiRepresentation());
1894 char* dest = SeqAsciiString::cast(string_result)->GetChars();
1895 String::WriteToFlat(buffer, dest, start, end);
1896 } else {
1897 ASSERT(string_result->IsTwoByteRepresentation());
1898 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
1899 String::WriteToFlat(buffer, dest, start, end);
Steve Blocka7e24c12009-10-30 11:49:00 +00001900 }
Steve Blockd0582a62009-12-15 09:54:21 +00001901
Steve Blocka7e24c12009-10-30 11:49:00 +00001902 return result;
1903}
1904
1905
1906Object* Heap::AllocateExternalStringFromAscii(
1907 ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00001908 size_t length = resource->length();
1909 if (length > static_cast<size_t>(String::kMaxLength)) {
1910 Top::context()->mark_out_of_memory();
1911 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00001912 }
1913
Steve Blockd0582a62009-12-15 09:54:21 +00001914 Map* map = external_ascii_string_map();
1915 Object* result = Allocate(map,
1916 always_allocate() ? OLD_DATA_SPACE : NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001917 if (result->IsFailure()) return result;
1918
1919 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00001920 external_string->set_length(static_cast<int>(length));
1921 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00001922 external_string->set_resource(resource);
1923
1924 return result;
1925}
1926
1927
1928Object* Heap::AllocateExternalStringFromTwoByte(
1929 ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00001930 size_t length = resource->length();
1931 if (length > static_cast<size_t>(String::kMaxLength)) {
1932 Top::context()->mark_out_of_memory();
1933 return Failure::OutOfMemoryException();
1934 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001935
Steve Blockd0582a62009-12-15 09:54:21 +00001936 Map* map = Heap::external_string_map();
1937 Object* result = Allocate(map,
1938 always_allocate() ? OLD_DATA_SPACE : NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001939 if (result->IsFailure()) return result;
1940
1941 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00001942 external_string->set_length(static_cast<int>(length));
1943 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00001944 external_string->set_resource(resource);
1945
1946 return result;
1947}
1948
1949
1950Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
1951 if (code <= String::kMaxAsciiCharCode) {
1952 Object* value = Heap::single_character_string_cache()->get(code);
1953 if (value != Heap::undefined_value()) return value;
1954
1955 char buffer[1];
1956 buffer[0] = static_cast<char>(code);
1957 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1958
1959 if (result->IsFailure()) return result;
1960 Heap::single_character_string_cache()->set(code, result);
1961 return result;
1962 }
1963
1964 Object* result = Heap::AllocateRawTwoByteString(1);
1965 if (result->IsFailure()) return result;
1966 String* answer = String::cast(result);
1967 answer->Set(0, code);
1968 return answer;
1969}
1970
1971
1972Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1973 if (pretenure == NOT_TENURED) {
1974 return AllocateByteArray(length);
1975 }
1976 int size = ByteArray::SizeFor(length);
1977 AllocationSpace space =
1978 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
1979
1980 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1981
1982 if (result->IsFailure()) return result;
1983
1984 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1985 reinterpret_cast<Array*>(result)->set_length(length);
1986 return result;
1987}
1988
1989
1990Object* Heap::AllocateByteArray(int length) {
1991 int size = ByteArray::SizeFor(length);
1992 AllocationSpace space =
1993 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
1994
1995 // New space can't cope with forced allocation.
1996 if (always_allocate()) space = LO_SPACE;
1997
1998 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1999
2000 if (result->IsFailure()) return result;
2001
2002 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2003 reinterpret_cast<Array*>(result)->set_length(length);
2004 return result;
2005}
2006
2007
2008void Heap::CreateFillerObjectAt(Address addr, int size) {
2009 if (size == 0) return;
2010 HeapObject* filler = HeapObject::FromAddress(addr);
2011 if (size == kPointerSize) {
2012 filler->set_map(Heap::one_pointer_filler_map());
2013 } else {
2014 filler->set_map(Heap::byte_array_map());
2015 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2016 }
2017}
2018
2019
2020Object* Heap::AllocatePixelArray(int length,
2021 uint8_t* external_pointer,
2022 PretenureFlag pretenure) {
2023 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2024
2025 // New space can't cope with forced allocation.
2026 if (always_allocate()) space = OLD_DATA_SPACE;
2027
2028 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
2029
2030 if (result->IsFailure()) return result;
2031
2032 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
2033 reinterpret_cast<PixelArray*>(result)->set_length(length);
2034 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
2035
2036 return result;
2037}
2038
2039
Steve Block3ce2e202009-11-05 08:53:23 +00002040Object* Heap::AllocateExternalArray(int length,
2041 ExternalArrayType array_type,
2042 void* external_pointer,
2043 PretenureFlag pretenure) {
2044 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2045
2046 // New space can't cope with forced allocation.
2047 if (always_allocate()) space = OLD_DATA_SPACE;
2048
2049 Object* result = AllocateRaw(ExternalArray::kAlignedSize,
2050 space,
2051 OLD_DATA_SPACE);
2052
2053 if (result->IsFailure()) return result;
2054
2055 reinterpret_cast<ExternalArray*>(result)->set_map(
2056 MapForExternalArrayType(array_type));
2057 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2058 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2059 external_pointer);
2060
2061 return result;
2062}
2063
2064
Steve Blocka7e24c12009-10-30 11:49:00 +00002065Object* Heap::CreateCode(const CodeDesc& desc,
2066 ZoneScopeInfo* sinfo,
2067 Code::Flags flags,
2068 Handle<Object> self_reference) {
2069 // Compute size
2070 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
2071 int sinfo_size = 0;
2072 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
2073 int obj_size = Code::SizeFor(body_size, sinfo_size);
2074 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
2075 Object* result;
2076 if (obj_size > MaxObjectSizeInPagedSpace()) {
2077 result = lo_space_->AllocateRawCode(obj_size);
2078 } else {
2079 result = code_space_->AllocateRaw(obj_size);
2080 }
2081
2082 if (result->IsFailure()) return result;
2083
2084 // Initialize the object
2085 HeapObject::cast(result)->set_map(code_map());
2086 Code* code = Code::cast(result);
2087 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2088 code->set_instruction_size(desc.instr_size);
2089 code->set_relocation_size(desc.reloc_size);
2090 code->set_sinfo_size(sinfo_size);
2091 code->set_flags(flags);
2092 // Allow self references to created code object by patching the handle to
2093 // point to the newly allocated Code object.
2094 if (!self_reference.is_null()) {
2095 *(self_reference.location()) = code;
2096 }
2097 // Migrate generated code.
2098 // The generated code can contain Object** values (typically from handles)
2099 // that are dereferenced during the copy to point directly to the actual heap
2100 // objects. These pointers can include references to the code object itself,
2101 // through the self_reference parameter.
2102 code->CopyFrom(desc);
2103 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
2104
2105#ifdef DEBUG
2106 code->Verify();
2107#endif
2108 return code;
2109}
2110
2111
2112Object* Heap::CopyCode(Code* code) {
2113 // Allocate an object the same size as the code object.
2114 int obj_size = code->Size();
2115 Object* result;
2116 if (obj_size > MaxObjectSizeInPagedSpace()) {
2117 result = lo_space_->AllocateRawCode(obj_size);
2118 } else {
2119 result = code_space_->AllocateRaw(obj_size);
2120 }
2121
2122 if (result->IsFailure()) return result;
2123
2124 // Copy code object.
2125 Address old_addr = code->address();
2126 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
2127 CopyBlock(reinterpret_cast<Object**>(new_addr),
2128 reinterpret_cast<Object**>(old_addr),
2129 obj_size);
2130 // Relocate the copy.
2131 Code* new_code = Code::cast(result);
2132 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2133 new_code->Relocate(new_addr - old_addr);
2134 return new_code;
2135}
2136
2137
2138Object* Heap::Allocate(Map* map, AllocationSpace space) {
2139 ASSERT(gc_state_ == NOT_IN_GC);
2140 ASSERT(map->instance_type() != MAP_TYPE);
2141 Object* result = AllocateRaw(map->instance_size(),
2142 space,
2143 TargetSpaceId(map->instance_type()));
2144 if (result->IsFailure()) return result;
2145 HeapObject::cast(result)->set_map(map);
Steve Block3ce2e202009-11-05 08:53:23 +00002146#ifdef ENABLE_LOGGING_AND_PROFILING
2147 ProducerHeapProfile::RecordJSObjectAllocation(result);
2148#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00002149 return result;
2150}
2151
2152
2153Object* Heap::InitializeFunction(JSFunction* function,
2154 SharedFunctionInfo* shared,
2155 Object* prototype) {
2156 ASSERT(!prototype->IsMap());
2157 function->initialize_properties();
2158 function->initialize_elements();
2159 function->set_shared(shared);
2160 function->set_prototype_or_initial_map(prototype);
2161 function->set_context(undefined_value());
2162 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
2163 return function;
2164}
2165
2166
2167Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
2168 // Allocate the prototype. Make sure to use the object function
2169 // from the function's context, since the function can be from a
2170 // different context.
2171 JSFunction* object_function =
2172 function->context()->global_context()->object_function();
2173 Object* prototype = AllocateJSObject(object_function);
2174 if (prototype->IsFailure()) return prototype;
2175 // When creating the prototype for the function we must set its
2176 // constructor to the function.
2177 Object* result =
2178 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2179 function,
2180 DONT_ENUM);
2181 if (result->IsFailure()) return result;
2182 return prototype;
2183}
2184
2185
2186Object* Heap::AllocateFunction(Map* function_map,
2187 SharedFunctionInfo* shared,
2188 Object* prototype) {
2189 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
2190 if (result->IsFailure()) return result;
2191 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2192}
2193
2194
2195Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
2196 // To get fast allocation and map sharing for arguments objects we
2197 // allocate them based on an arguments boilerplate.
2198
2199 // This calls Copy directly rather than using Heap::AllocateRaw so we
2200 // duplicate the check here.
2201 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2202
2203 JSObject* boilerplate =
2204 Top::context()->global_context()->arguments_boilerplate();
2205
2206 // Make the clone.
2207 Map* map = boilerplate->map();
2208 int object_size = map->instance_size();
2209 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2210 if (result->IsFailure()) return result;
2211
2212 // Copy the content. The arguments boilerplate doesn't have any
2213 // fields that point to new space so it's safe to skip the write
2214 // barrier here.
2215 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2216 reinterpret_cast<Object**>(boilerplate->address()),
2217 object_size);
2218
2219 // Set the two properties.
2220 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
2221 callee);
2222 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2223 Smi::FromInt(length),
2224 SKIP_WRITE_BARRIER);
2225
2226 // Check the state of the object
2227 ASSERT(JSObject::cast(result)->HasFastProperties());
2228 ASSERT(JSObject::cast(result)->HasFastElements());
2229
2230 return result;
2231}
2232
2233
2234Object* Heap::AllocateInitialMap(JSFunction* fun) {
2235 ASSERT(!fun->has_initial_map());
2236
2237 // First create a new map with the size and number of in-object properties
2238 // suggested by the function.
2239 int instance_size = fun->shared()->CalculateInstanceSize();
2240 int in_object_properties = fun->shared()->CalculateInObjectProperties();
2241 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
2242 if (map_obj->IsFailure()) return map_obj;
2243
2244 // Fetch or allocate prototype.
2245 Object* prototype;
2246 if (fun->has_instance_prototype()) {
2247 prototype = fun->instance_prototype();
2248 } else {
2249 prototype = AllocateFunctionPrototype(fun);
2250 if (prototype->IsFailure()) return prototype;
2251 }
2252 Map* map = Map::cast(map_obj);
2253 map->set_inobject_properties(in_object_properties);
2254 map->set_unused_property_fields(in_object_properties);
2255 map->set_prototype(prototype);
2256
2257 // If the function has only simple this property assignments add field
2258 // descriptors for these to the initial map as the object cannot be
2259 // constructed without having these properties.
2260 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Steve Blockd0582a62009-12-15 09:54:21 +00002261 if (fun->shared()->has_only_simple_this_property_assignments() &&
2262 fun->shared()->this_property_assignments_count() > 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002263 int count = fun->shared()->this_property_assignments_count();
2264 if (count > in_object_properties) {
2265 count = in_object_properties;
2266 }
2267 Object* descriptors_obj = DescriptorArray::Allocate(count);
2268 if (descriptors_obj->IsFailure()) return descriptors_obj;
2269 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
2270 for (int i = 0; i < count; i++) {
2271 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2272 ASSERT(name->IsSymbol());
2273 FieldDescriptor field(name, i, NONE);
2274 descriptors->Set(i, &field);
2275 }
2276 descriptors->Sort();
2277 map->set_instance_descriptors(descriptors);
2278 map->set_pre_allocated_property_fields(count);
2279 map->set_unused_property_fields(in_object_properties - count);
2280 }
2281 return map;
2282}
2283
2284
2285void Heap::InitializeJSObjectFromMap(JSObject* obj,
2286 FixedArray* properties,
2287 Map* map) {
2288 obj->set_properties(properties);
2289 obj->initialize_elements();
2290 // TODO(1240798): Initialize the object's body using valid initial values
2291 // according to the object's initial map. For example, if the map's
2292 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2293 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2294 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2295 // verification code has to cope with (temporarily) invalid objects. See
2296 // for example, JSArray::JSArrayVerify).
2297 obj->InitializeBody(map->instance_size());
2298}
2299
2300
2301Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2302 // JSFunctions should be allocated using AllocateFunction to be
2303 // properly initialized.
2304 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2305
2306 // Both types of globla objects should be allocated using
2307 // AllocateGloblaObject to be properly initialized.
2308 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2309 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2310
2311 // Allocate the backing storage for the properties.
2312 int prop_size =
2313 map->pre_allocated_property_fields() +
2314 map->unused_property_fields() -
2315 map->inobject_properties();
2316 ASSERT(prop_size >= 0);
2317 Object* properties = AllocateFixedArray(prop_size, pretenure);
2318 if (properties->IsFailure()) return properties;
2319
2320 // Allocate the JSObject.
2321 AllocationSpace space =
2322 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2323 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
Steve Blockd0582a62009-12-15 09:54:21 +00002324 if (always_allocate()) space = OLD_POINTER_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00002325 Object* obj = Allocate(map, space);
2326 if (obj->IsFailure()) return obj;
2327
2328 // Initialize the JSObject.
2329 InitializeJSObjectFromMap(JSObject::cast(obj),
2330 FixedArray::cast(properties),
2331 map);
2332 return obj;
2333}
2334
2335
2336Object* Heap::AllocateJSObject(JSFunction* constructor,
2337 PretenureFlag pretenure) {
2338 // Allocate the initial map if absent.
2339 if (!constructor->has_initial_map()) {
2340 Object* initial_map = AllocateInitialMap(constructor);
2341 if (initial_map->IsFailure()) return initial_map;
2342 constructor->set_initial_map(Map::cast(initial_map));
2343 Map::cast(initial_map)->set_constructor(constructor);
2344 }
2345 // Allocate the object based on the constructors initial map.
2346 Object* result =
2347 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2348 // Make sure result is NOT a global object if valid.
2349 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2350 return result;
2351}
2352
2353
2354Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2355 ASSERT(constructor->has_initial_map());
2356 Map* map = constructor->initial_map();
2357
2358 // Make sure no field properties are described in the initial map.
2359 // This guarantees us that normalizing the properties does not
2360 // require us to change property values to JSGlobalPropertyCells.
2361 ASSERT(map->NextFreePropertyIndex() == 0);
2362
2363 // Make sure we don't have a ton of pre-allocated slots in the
2364 // global objects. They will be unused once we normalize the object.
2365 ASSERT(map->unused_property_fields() == 0);
2366 ASSERT(map->inobject_properties() == 0);
2367
2368 // Initial size of the backing store to avoid resize of the storage during
2369 // bootstrapping. The size differs between the JS global object ad the
2370 // builtins object.
2371 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
2372
2373 // Allocate a dictionary object for backing storage.
2374 Object* obj =
2375 StringDictionary::Allocate(
2376 map->NumberOfDescribedProperties() * 2 + initial_size);
2377 if (obj->IsFailure()) return obj;
2378 StringDictionary* dictionary = StringDictionary::cast(obj);
2379
2380 // The global object might be created from an object template with accessors.
2381 // Fill these accessors into the dictionary.
2382 DescriptorArray* descs = map->instance_descriptors();
2383 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2384 PropertyDetails details = descs->GetDetails(i);
2385 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2386 PropertyDetails d =
2387 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2388 Object* value = descs->GetCallbacksObject(i);
2389 value = Heap::AllocateJSGlobalPropertyCell(value);
2390 if (value->IsFailure()) return value;
2391
2392 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2393 if (result->IsFailure()) return result;
2394 dictionary = StringDictionary::cast(result);
2395 }
2396
2397 // Allocate the global object and initialize it with the backing store.
2398 obj = Allocate(map, OLD_POINTER_SPACE);
2399 if (obj->IsFailure()) return obj;
2400 JSObject* global = JSObject::cast(obj);
2401 InitializeJSObjectFromMap(global, dictionary, map);
2402
2403 // Create a new map for the global object.
2404 obj = map->CopyDropDescriptors();
2405 if (obj->IsFailure()) return obj;
2406 Map* new_map = Map::cast(obj);
2407
2408 // Setup the global object as a normalized object.
2409 global->set_map(new_map);
2410 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2411 global->set_properties(dictionary);
2412
2413 // Make sure result is a global object with properties in dictionary.
2414 ASSERT(global->IsGlobalObject());
2415 ASSERT(!global->HasFastProperties());
2416 return global;
2417}
2418
2419
2420Object* Heap::CopyJSObject(JSObject* source) {
2421 // Never used to copy functions. If functions need to be copied we
2422 // have to be careful to clear the literals array.
2423 ASSERT(!source->IsJSFunction());
2424
2425 // Make the clone.
2426 Map* map = source->map();
2427 int object_size = map->instance_size();
2428 Object* clone;
2429
2430 // If we're forced to always allocate, we use the general allocation
2431 // functions which may leave us with an object in old space.
2432 if (always_allocate()) {
2433 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2434 if (clone->IsFailure()) return clone;
2435 Address clone_address = HeapObject::cast(clone)->address();
2436 CopyBlock(reinterpret_cast<Object**>(clone_address),
2437 reinterpret_cast<Object**>(source->address()),
2438 object_size);
2439 // Update write barrier for all fields that lie beyond the header.
2440 for (int offset = JSObject::kHeaderSize;
2441 offset < object_size;
2442 offset += kPointerSize) {
2443 RecordWrite(clone_address, offset);
2444 }
2445 } else {
2446 clone = new_space_.AllocateRaw(object_size);
2447 if (clone->IsFailure()) return clone;
2448 ASSERT(Heap::InNewSpace(clone));
2449 // Since we know the clone is allocated in new space, we can copy
2450 // the contents without worrying about updating the write barrier.
2451 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2452 reinterpret_cast<Object**>(source->address()),
2453 object_size);
2454 }
2455
2456 FixedArray* elements = FixedArray::cast(source->elements());
2457 FixedArray* properties = FixedArray::cast(source->properties());
2458 // Update elements if necessary.
2459 if (elements->length()> 0) {
2460 Object* elem = CopyFixedArray(elements);
2461 if (elem->IsFailure()) return elem;
2462 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2463 }
2464 // Update properties if necessary.
2465 if (properties->length() > 0) {
2466 Object* prop = CopyFixedArray(properties);
2467 if (prop->IsFailure()) return prop;
2468 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2469 }
2470 // Return the new clone.
Steve Block3ce2e202009-11-05 08:53:23 +00002471#ifdef ENABLE_LOGGING_AND_PROFILING
2472 ProducerHeapProfile::RecordJSObjectAllocation(clone);
2473#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00002474 return clone;
2475}
2476
2477
2478Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2479 JSGlobalProxy* object) {
2480 // Allocate initial map if absent.
2481 if (!constructor->has_initial_map()) {
2482 Object* initial_map = AllocateInitialMap(constructor);
2483 if (initial_map->IsFailure()) return initial_map;
2484 constructor->set_initial_map(Map::cast(initial_map));
2485 Map::cast(initial_map)->set_constructor(constructor);
2486 }
2487
2488 Map* map = constructor->initial_map();
2489
2490 // Check that the already allocated object has the same size as
2491 // objects allocated using the constructor.
2492 ASSERT(map->instance_size() == object->map()->instance_size());
2493
2494 // Allocate the backing storage for the properties.
2495 int prop_size = map->unused_property_fields() - map->inobject_properties();
2496 Object* properties = AllocateFixedArray(prop_size, TENURED);
2497 if (properties->IsFailure()) return properties;
2498
2499 // Reset the map for the object.
2500 object->set_map(constructor->initial_map());
2501
2502 // Reinitialize the object from the constructor map.
2503 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2504 return object;
2505}
2506
2507
2508Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2509 PretenureFlag pretenure) {
2510 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2511 if (result->IsFailure()) return result;
2512
2513 // Copy the characters into the new object.
2514 SeqAsciiString* string_result = SeqAsciiString::cast(result);
2515 for (int i = 0; i < string.length(); i++) {
2516 string_result->SeqAsciiStringSet(i, string[i]);
2517 }
2518 return result;
2519}
2520
2521
2522Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2523 PretenureFlag pretenure) {
2524 // Count the number of characters in the UTF-8 string and check if
2525 // it is an ASCII string.
2526 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2527 decoder->Reset(string.start(), string.length());
2528 int chars = 0;
2529 bool is_ascii = true;
2530 while (decoder->has_more()) {
2531 uc32 r = decoder->GetNext();
2532 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2533 chars++;
2534 }
2535
2536 // If the string is ascii, we do not need to convert the characters
2537 // since UTF8 is backwards compatible with ascii.
2538 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2539
2540 Object* result = AllocateRawTwoByteString(chars, pretenure);
2541 if (result->IsFailure()) return result;
2542
2543 // Convert and copy the characters into the new object.
2544 String* string_result = String::cast(result);
2545 decoder->Reset(string.start(), string.length());
2546 for (int i = 0; i < chars; i++) {
2547 uc32 r = decoder->GetNext();
2548 string_result->Set(i, r);
2549 }
2550 return result;
2551}
2552
2553
2554Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2555 PretenureFlag pretenure) {
2556 // Check if the string is an ASCII string.
2557 int i = 0;
2558 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2559
2560 Object* result;
2561 if (i == string.length()) { // It's an ASCII string.
2562 result = AllocateRawAsciiString(string.length(), pretenure);
2563 } else { // It's not an ASCII string.
2564 result = AllocateRawTwoByteString(string.length(), pretenure);
2565 }
2566 if (result->IsFailure()) return result;
2567
2568 // Copy the characters into the new object, which may be either ASCII or
2569 // UTF-16.
2570 String* string_result = String::cast(result);
2571 for (int i = 0; i < string.length(); i++) {
2572 string_result->Set(i, string[i]);
2573 }
2574 return result;
2575}
2576
2577
2578Map* Heap::SymbolMapForString(String* string) {
2579 // If the string is in new space it cannot be used as a symbol.
2580 if (InNewSpace(string)) return NULL;
2581
2582 // Find the corresponding symbol map for strings.
2583 Map* map = string->map();
Steve Blockd0582a62009-12-15 09:54:21 +00002584 if (map == ascii_string_map()) return ascii_symbol_map();
2585 if (map == string_map()) return symbol_map();
2586 if (map == cons_string_map()) return cons_symbol_map();
2587 if (map == cons_ascii_string_map()) return cons_ascii_symbol_map();
2588 if (map == external_string_map()) return external_symbol_map();
2589 if (map == external_ascii_string_map()) return external_ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002590
2591 // No match found.
2592 return NULL;
2593}
2594
2595
2596Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2597 int chars,
Steve Blockd0582a62009-12-15 09:54:21 +00002598 uint32_t hash_field) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002599 // Ensure the chars matches the number of characters in the buffer.
2600 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2601 // Determine whether the string is ascii.
2602 bool is_ascii = true;
2603 while (buffer->has_more() && is_ascii) {
2604 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2605 }
2606 buffer->Rewind();
2607
2608 // Compute map and object size.
2609 int size;
2610 Map* map;
2611
2612 if (is_ascii) {
Steve Blockd0582a62009-12-15 09:54:21 +00002613 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002614 size = SeqAsciiString::SizeFor(chars);
2615 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00002616 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002617 size = SeqTwoByteString::SizeFor(chars);
2618 }
2619
2620 // Allocate string.
2621 AllocationSpace space =
2622 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
2623 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
2624 if (result->IsFailure()) return result;
2625
2626 reinterpret_cast<HeapObject*>(result)->set_map(map);
Steve Blockd0582a62009-12-15 09:54:21 +00002627 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00002628 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002629 answer->set_length(chars);
2630 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00002631
2632 ASSERT_EQ(size, answer->Size());
2633
2634 // Fill in the characters.
2635 for (int i = 0; i < chars; i++) {
2636 answer->Set(i, buffer->GetNext());
2637 }
2638 return answer;
2639}
2640
2641
2642Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
2643 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2644
2645 // New space can't cope with forced allocation.
2646 if (always_allocate()) space = OLD_DATA_SPACE;
2647
2648 int size = SeqAsciiString::SizeFor(length);
2649
2650 Object* result = Failure::OutOfMemoryException();
2651 if (space == NEW_SPACE) {
2652 result = size <= kMaxObjectSizeInNewSpace
2653 ? new_space_.AllocateRaw(size)
2654 : lo_space_->AllocateRaw(size);
2655 } else {
2656 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2657 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2658 }
2659 if (result->IsFailure()) return result;
2660
Steve Blocka7e24c12009-10-30 11:49:00 +00002661 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00002662 HeapObject::cast(result)->set_map(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002663 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002664 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002665 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2666 return result;
2667}
2668
2669
2670Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
2671 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2672
2673 // New space can't cope with forced allocation.
2674 if (always_allocate()) space = OLD_DATA_SPACE;
2675
2676 int size = SeqTwoByteString::SizeFor(length);
2677
2678 Object* result = Failure::OutOfMemoryException();
2679 if (space == NEW_SPACE) {
2680 result = size <= kMaxObjectSizeInNewSpace
2681 ? new_space_.AllocateRaw(size)
2682 : lo_space_->AllocateRaw(size);
2683 } else {
2684 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2685 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2686 }
2687 if (result->IsFailure()) return result;
2688
Steve Blocka7e24c12009-10-30 11:49:00 +00002689 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00002690 HeapObject::cast(result)->set_map(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002691 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002692 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002693 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2694 return result;
2695}
2696
2697
2698Object* Heap::AllocateEmptyFixedArray() {
2699 int size = FixedArray::SizeFor(0);
2700 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
2701 if (result->IsFailure()) return result;
2702 // Initialize the object.
2703 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2704 reinterpret_cast<Array*>(result)->set_length(0);
2705 return result;
2706}
2707
2708
2709Object* Heap::AllocateRawFixedArray(int length) {
2710 // Use the general function if we're forced to always allocate.
2711 if (always_allocate()) return AllocateFixedArray(length, TENURED);
2712 // Allocate the raw data for a fixed array.
2713 int size = FixedArray::SizeFor(length);
2714 return size <= kMaxObjectSizeInNewSpace
2715 ? new_space_.AllocateRaw(size)
2716 : lo_space_->AllocateRawFixedArray(size);
2717}
2718
2719
2720Object* Heap::CopyFixedArray(FixedArray* src) {
2721 int len = src->length();
2722 Object* obj = AllocateRawFixedArray(len);
2723 if (obj->IsFailure()) return obj;
2724 if (Heap::InNewSpace(obj)) {
2725 HeapObject* dst = HeapObject::cast(obj);
2726 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2727 reinterpret_cast<Object**>(src->address()),
2728 FixedArray::SizeFor(len));
2729 return obj;
2730 }
2731 HeapObject::cast(obj)->set_map(src->map());
2732 FixedArray* result = FixedArray::cast(obj);
2733 result->set_length(len);
2734 // Copy the content
2735 WriteBarrierMode mode = result->GetWriteBarrierMode();
2736 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2737 return result;
2738}
2739
2740
2741Object* Heap::AllocateFixedArray(int length) {
2742 ASSERT(length >= 0);
2743 if (length == 0) return empty_fixed_array();
2744 Object* result = AllocateRawFixedArray(length);
2745 if (!result->IsFailure()) {
2746 // Initialize header.
2747 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2748 FixedArray* array = FixedArray::cast(result);
2749 array->set_length(length);
2750 Object* value = undefined_value();
2751 // Initialize body.
2752 for (int index = 0; index < length; index++) {
2753 array->set(index, value, SKIP_WRITE_BARRIER);
2754 }
2755 }
2756 return result;
2757}
2758
2759
2760Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2761 ASSERT(empty_fixed_array()->IsFixedArray());
2762 if (length == 0) return empty_fixed_array();
2763
2764 // New space can't cope with forced allocation.
2765 if (always_allocate()) pretenure = TENURED;
2766
2767 int size = FixedArray::SizeFor(length);
2768 Object* result = Failure::OutOfMemoryException();
2769 if (pretenure != TENURED) {
2770 result = size <= kMaxObjectSizeInNewSpace
2771 ? new_space_.AllocateRaw(size)
2772 : lo_space_->AllocateRawFixedArray(size);
2773 }
2774 if (result->IsFailure()) {
2775 if (size > MaxObjectSizeInPagedSpace()) {
2776 result = lo_space_->AllocateRawFixedArray(size);
2777 } else {
2778 AllocationSpace space =
2779 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2780 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
2781 }
2782 if (result->IsFailure()) return result;
2783 }
2784 // Initialize the object.
2785 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2786 FixedArray* array = FixedArray::cast(result);
2787 array->set_length(length);
2788 Object* value = undefined_value();
2789 for (int index = 0; index < length; index++) {
2790 array->set(index, value, SKIP_WRITE_BARRIER);
2791 }
2792 return array;
2793}
2794
2795
2796Object* Heap::AllocateFixedArrayWithHoles(int length) {
2797 if (length == 0) return empty_fixed_array();
2798 Object* result = AllocateRawFixedArray(length);
2799 if (!result->IsFailure()) {
2800 // Initialize header.
2801 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2802 FixedArray* array = FixedArray::cast(result);
2803 array->set_length(length);
2804 // Initialize body.
2805 Object* value = the_hole_value();
2806 for (int index = 0; index < length; index++) {
2807 array->set(index, value, SKIP_WRITE_BARRIER);
2808 }
2809 }
2810 return result;
2811}
2812
2813
2814Object* Heap::AllocateHashTable(int length) {
2815 Object* result = Heap::AllocateFixedArray(length);
2816 if (result->IsFailure()) return result;
2817 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2818 ASSERT(result->IsHashTable());
2819 return result;
2820}
2821
2822
2823Object* Heap::AllocateGlobalContext() {
2824 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2825 if (result->IsFailure()) return result;
2826 Context* context = reinterpret_cast<Context*>(result);
2827 context->set_map(global_context_map());
2828 ASSERT(context->IsGlobalContext());
2829 ASSERT(result->IsContext());
2830 return result;
2831}
2832
2833
2834Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2835 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2836 Object* result = Heap::AllocateFixedArray(length);
2837 if (result->IsFailure()) return result;
2838 Context* context = reinterpret_cast<Context*>(result);
2839 context->set_map(context_map());
2840 context->set_closure(function);
2841 context->set_fcontext(context);
2842 context->set_previous(NULL);
2843 context->set_extension(NULL);
2844 context->set_global(function->context()->global());
2845 ASSERT(!context->IsGlobalContext());
2846 ASSERT(context->is_function_context());
2847 ASSERT(result->IsContext());
2848 return result;
2849}
2850
2851
2852Object* Heap::AllocateWithContext(Context* previous,
2853 JSObject* extension,
2854 bool is_catch_context) {
2855 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2856 if (result->IsFailure()) return result;
2857 Context* context = reinterpret_cast<Context*>(result);
2858 context->set_map(is_catch_context ? catch_context_map() : context_map());
2859 context->set_closure(previous->closure());
2860 context->set_fcontext(previous->fcontext());
2861 context->set_previous(previous);
2862 context->set_extension(extension);
2863 context->set_global(previous->global());
2864 ASSERT(!context->IsGlobalContext());
2865 ASSERT(!context->is_function_context());
2866 ASSERT(result->IsContext());
2867 return result;
2868}
2869
2870
2871Object* Heap::AllocateStruct(InstanceType type) {
2872 Map* map;
2873 switch (type) {
2874#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2875STRUCT_LIST(MAKE_CASE)
2876#undef MAKE_CASE
2877 default:
2878 UNREACHABLE();
2879 return Failure::InternalError();
2880 }
2881 int size = map->instance_size();
2882 AllocationSpace space =
2883 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
2884 Object* result = Heap::Allocate(map, space);
2885 if (result->IsFailure()) return result;
2886 Struct::cast(result)->InitializeBody(size);
2887 return result;
2888}
2889
2890
2891bool Heap::IdleNotification() {
2892 static const int kIdlesBeforeScavenge = 4;
2893 static const int kIdlesBeforeMarkSweep = 7;
2894 static const int kIdlesBeforeMarkCompact = 8;
2895 static int number_idle_notifications = 0;
2896 static int last_gc_count = gc_count_;
2897
2898 bool finished = false;
2899
2900 if (last_gc_count == gc_count_) {
2901 number_idle_notifications++;
2902 } else {
2903 number_idle_notifications = 0;
2904 last_gc_count = gc_count_;
2905 }
2906
2907 if (number_idle_notifications == kIdlesBeforeScavenge) {
2908 CollectGarbage(0, NEW_SPACE);
2909 new_space_.Shrink();
2910 last_gc_count = gc_count_;
2911
2912 } else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00002913 // Before doing the mark-sweep collections we clear the
2914 // compilation cache to avoid hanging on to source code and
2915 // generated code for cached functions.
2916 CompilationCache::Clear();
2917
Steve Blocka7e24c12009-10-30 11:49:00 +00002918 CollectAllGarbage(false);
2919 new_space_.Shrink();
2920 last_gc_count = gc_count_;
2921
2922 } else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
2923 CollectAllGarbage(true);
2924 new_space_.Shrink();
2925 last_gc_count = gc_count_;
2926 number_idle_notifications = 0;
2927 finished = true;
2928 }
2929
2930 // Uncommit unused memory in new space.
2931 Heap::UncommitFromSpace();
2932 return finished;
2933}
2934
2935
2936#ifdef DEBUG
2937
2938void Heap::Print() {
2939 if (!HasBeenSetup()) return;
2940 Top::PrintStack();
2941 AllSpaces spaces;
2942 while (Space* space = spaces.next()) space->Print();
2943}
2944
2945
2946void Heap::ReportCodeStatistics(const char* title) {
2947 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2948 PagedSpace::ResetCodeStatistics();
2949 // We do not look for code in new space, map space, or old space. If code
2950 // somehow ends up in those spaces, we would miss it here.
2951 code_space_->CollectCodeStatistics();
2952 lo_space_->CollectCodeStatistics();
2953 PagedSpace::ReportCodeStatistics();
2954}
2955
2956
2957// This function expects that NewSpace's allocated objects histogram is
2958// populated (via a call to CollectStatistics or else as a side effect of a
2959// just-completed scavenge collection).
2960void Heap::ReportHeapStatistics(const char* title) {
2961 USE(title);
2962 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2963 title, gc_count_);
2964 PrintF("mark-compact GC : %d\n", mc_count_);
2965 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2966 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
2967
2968 PrintF("\n");
2969 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2970 GlobalHandles::PrintStats();
2971 PrintF("\n");
2972
2973 PrintF("Heap statistics : ");
2974 MemoryAllocator::ReportStatistics();
2975 PrintF("To space : ");
2976 new_space_.ReportStatistics();
2977 PrintF("Old pointer space : ");
2978 old_pointer_space_->ReportStatistics();
2979 PrintF("Old data space : ");
2980 old_data_space_->ReportStatistics();
2981 PrintF("Code space : ");
2982 code_space_->ReportStatistics();
2983 PrintF("Map space : ");
2984 map_space_->ReportStatistics();
2985 PrintF("Cell space : ");
2986 cell_space_->ReportStatistics();
2987 PrintF("Large object space : ");
2988 lo_space_->ReportStatistics();
2989 PrintF(">>>>>> ========================================= >>>>>>\n");
2990}
2991
2992#endif // DEBUG
2993
2994bool Heap::Contains(HeapObject* value) {
2995 return Contains(value->address());
2996}
2997
2998
2999bool Heap::Contains(Address addr) {
3000 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3001 return HasBeenSetup() &&
3002 (new_space_.ToSpaceContains(addr) ||
3003 old_pointer_space_->Contains(addr) ||
3004 old_data_space_->Contains(addr) ||
3005 code_space_->Contains(addr) ||
3006 map_space_->Contains(addr) ||
3007 cell_space_->Contains(addr) ||
3008 lo_space_->SlowContains(addr));
3009}
3010
3011
3012bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
3013 return InSpace(value->address(), space);
3014}
3015
3016
3017bool Heap::InSpace(Address addr, AllocationSpace space) {
3018 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3019 if (!HasBeenSetup()) return false;
3020
3021 switch (space) {
3022 case NEW_SPACE:
3023 return new_space_.ToSpaceContains(addr);
3024 case OLD_POINTER_SPACE:
3025 return old_pointer_space_->Contains(addr);
3026 case OLD_DATA_SPACE:
3027 return old_data_space_->Contains(addr);
3028 case CODE_SPACE:
3029 return code_space_->Contains(addr);
3030 case MAP_SPACE:
3031 return map_space_->Contains(addr);
3032 case CELL_SPACE:
3033 return cell_space_->Contains(addr);
3034 case LO_SPACE:
3035 return lo_space_->SlowContains(addr);
3036 }
3037
3038 return false;
3039}
3040
3041
3042#ifdef DEBUG
3043void Heap::Verify() {
3044 ASSERT(HasBeenSetup());
3045
3046 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00003047 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00003048
3049 new_space_.Verify();
3050
3051 VerifyPointersAndRSetVisitor rset_visitor;
3052 old_pointer_space_->Verify(&rset_visitor);
3053 map_space_->Verify(&rset_visitor);
3054
3055 VerifyPointersVisitor no_rset_visitor;
3056 old_data_space_->Verify(&no_rset_visitor);
3057 code_space_->Verify(&no_rset_visitor);
3058 cell_space_->Verify(&no_rset_visitor);
3059
3060 lo_space_->Verify();
3061}
3062#endif // DEBUG
3063
3064
3065Object* Heap::LookupSymbol(Vector<const char> string) {
3066 Object* symbol = NULL;
3067 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
3068 if (new_table->IsFailure()) return new_table;
3069 // Can't use set_symbol_table because SymbolTable::cast knows that
3070 // SymbolTable is a singleton and checks for identity.
3071 roots_[kSymbolTableRootIndex] = new_table;
3072 ASSERT(symbol != NULL);
3073 return symbol;
3074}
3075
3076
3077Object* Heap::LookupSymbol(String* string) {
3078 if (string->IsSymbol()) return string;
3079 Object* symbol = NULL;
3080 Object* new_table = symbol_table()->LookupString(string, &symbol);
3081 if (new_table->IsFailure()) return new_table;
3082 // Can't use set_symbol_table because SymbolTable::cast knows that
3083 // SymbolTable is a singleton and checks for identity.
3084 roots_[kSymbolTableRootIndex] = new_table;
3085 ASSERT(symbol != NULL);
3086 return symbol;
3087}
3088
3089
3090bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
3091 if (string->IsSymbol()) {
3092 *symbol = string;
3093 return true;
3094 }
3095 return symbol_table()->LookupSymbolIfExists(string, symbol);
3096}
3097
3098
3099#ifdef DEBUG
3100void Heap::ZapFromSpace() {
3101 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
3102 for (Address a = new_space_.FromSpaceLow();
3103 a < new_space_.FromSpaceHigh();
3104 a += kPointerSize) {
3105 Memory::Address_at(a) = kFromSpaceZapValue;
3106 }
3107}
3108#endif // DEBUG
3109
3110
3111int Heap::IterateRSetRange(Address object_start,
3112 Address object_end,
3113 Address rset_start,
3114 ObjectSlotCallback copy_object_func) {
3115 Address object_address = object_start;
3116 Address rset_address = rset_start;
3117 int set_bits_count = 0;
3118
3119 // Loop over all the pointers in [object_start, object_end).
3120 while (object_address < object_end) {
3121 uint32_t rset_word = Memory::uint32_at(rset_address);
3122 if (rset_word != 0) {
3123 uint32_t result_rset = rset_word;
3124 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
3125 // Do not dereference pointers at or past object_end.
3126 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3127 Object** object_p = reinterpret_cast<Object**>(object_address);
3128 if (Heap::InNewSpace(*object_p)) {
3129 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3130 }
3131 // If this pointer does not need to be remembered anymore, clear
3132 // the remembered set bit.
3133 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
3134 set_bits_count++;
3135 }
3136 object_address += kPointerSize;
3137 }
3138 // Update the remembered set if it has changed.
3139 if (result_rset != rset_word) {
3140 Memory::uint32_at(rset_address) = result_rset;
3141 }
3142 } else {
3143 // No bits in the word were set. This is the common case.
3144 object_address += kPointerSize * kBitsPerInt;
3145 }
3146 rset_address += kIntSize;
3147 }
3148 return set_bits_count;
3149}
3150
3151
3152void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3153 ASSERT(Page::is_rset_in_use());
3154 ASSERT(space == old_pointer_space_ || space == map_space_);
3155
3156 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3157 "V8.RSetPaged",
3158 0,
3159 Page::kObjectAreaSize / kPointerSize,
3160 30);
3161
3162 PageIterator it(space, PageIterator::PAGES_IN_USE);
3163 while (it.has_next()) {
3164 Page* page = it.next();
3165 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3166 page->RSetStart(), copy_object_func);
3167 if (paged_rset_histogram != NULL) {
3168 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3169 }
3170 }
3171}
3172
3173
Steve Blockd0582a62009-12-15 09:54:21 +00003174void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
3175 IterateStrongRoots(v, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003176 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Steve Blockd0582a62009-12-15 09:54:21 +00003177 v->Synchronize("symbol_table");
Steve Blocka7e24c12009-10-30 11:49:00 +00003178}
3179
3180
Steve Blockd0582a62009-12-15 09:54:21 +00003181void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003182 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Steve Blockd0582a62009-12-15 09:54:21 +00003183 v->Synchronize("strong_root_list");
Steve Blocka7e24c12009-10-30 11:49:00 +00003184
3185 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
Steve Blockd0582a62009-12-15 09:54:21 +00003186 v->Synchronize("symbol");
Steve Blocka7e24c12009-10-30 11:49:00 +00003187
3188 Bootstrapper::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003189 v->Synchronize("bootstrapper");
Steve Blocka7e24c12009-10-30 11:49:00 +00003190 Top::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003191 v->Synchronize("top");
Steve Blocka7e24c12009-10-30 11:49:00 +00003192 Relocatable::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003193 v->Synchronize("relocatable");
Steve Blocka7e24c12009-10-30 11:49:00 +00003194
3195#ifdef ENABLE_DEBUGGER_SUPPORT
3196 Debug::Iterate(v);
3197#endif
Steve Blockd0582a62009-12-15 09:54:21 +00003198 v->Synchronize("debug");
Steve Blocka7e24c12009-10-30 11:49:00 +00003199 CompilationCache::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003200 v->Synchronize("compilationcache");
Steve Blocka7e24c12009-10-30 11:49:00 +00003201
3202 // Iterate over local handles in handle scopes.
3203 HandleScopeImplementer::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003204 v->Synchronize("handlescope");
Steve Blocka7e24c12009-10-30 11:49:00 +00003205
3206 // Iterate over the builtin code objects and code stubs in the heap. Note
3207 // that it is not strictly necessary to iterate over code objects on
3208 // scavenge collections. We still do it here because this same function
3209 // is used by the mark-sweep collector and the deserializer.
3210 Builtins::IterateBuiltins(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003211 v->Synchronize("builtins");
Steve Blocka7e24c12009-10-30 11:49:00 +00003212
3213 // Iterate over global handles.
Steve Blockd0582a62009-12-15 09:54:21 +00003214 if (mode == VISIT_ONLY_STRONG) {
3215 GlobalHandles::IterateStrongRoots(v);
3216 } else {
3217 GlobalHandles::IterateAllRoots(v);
3218 }
3219 v->Synchronize("globalhandles");
Steve Blocka7e24c12009-10-30 11:49:00 +00003220
3221 // Iterate over pointers being held by inactive threads.
3222 ThreadManager::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00003223 v->Synchronize("threadmanager");
Steve Blocka7e24c12009-10-30 11:49:00 +00003224}
Steve Blocka7e24c12009-10-30 11:49:00 +00003225
3226
3227// Flag is set when the heap has been configured. The heap can be repeatedly
3228// configured through the API until it is setup.
3229static bool heap_configured = false;
3230
3231// TODO(1236194): Since the heap size is configurable on the command line
3232// and through the API, we should gracefully handle the case that the heap
3233// size is not big enough to fit all the initial objects.
Steve Block3ce2e202009-11-05 08:53:23 +00003234bool Heap::ConfigureHeap(int max_semispace_size, int max_old_gen_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003235 if (HasBeenSetup()) return false;
3236
Steve Block3ce2e202009-11-05 08:53:23 +00003237 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
3238
3239 if (Snapshot::IsEnabled()) {
3240 // If we are using a snapshot we always reserve the default amount
3241 // of memory for each semispace because code in the snapshot has
3242 // write-barrier code that relies on the size and alignment of new
3243 // space. We therefore cannot use a larger max semispace size
3244 // than the default reserved semispace size.
3245 if (max_semispace_size_ > reserved_semispace_size_) {
3246 max_semispace_size_ = reserved_semispace_size_;
3247 }
3248 } else {
3249 // If we are not using snapshots we reserve space for the actual
3250 // max semispace size.
3251 reserved_semispace_size_ = max_semispace_size_;
3252 }
3253
3254 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00003255
3256 // The new space size must be a power of two to support single-bit testing
3257 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00003258 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
3259 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
3260 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
3261 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003262
3263 // The old generation is paged.
Steve Block3ce2e202009-11-05 08:53:23 +00003264 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003265
3266 heap_configured = true;
3267 return true;
3268}
3269
3270
3271bool Heap::ConfigureHeapDefault() {
Steve Block3ce2e202009-11-05 08:53:23 +00003272 return ConfigureHeap(FLAG_max_new_space_size / 2, FLAG_max_old_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00003273}
3274
3275
Steve Blockd0582a62009-12-15 09:54:21 +00003276void Heap::RecordStats(HeapStats* stats) {
3277 *stats->start_marker = 0xDECADE00;
3278 *stats->end_marker = 0xDECADE01;
3279 *stats->new_space_size = new_space_.Size();
3280 *stats->new_space_capacity = new_space_.Capacity();
3281 *stats->old_pointer_space_size = old_pointer_space_->Size();
3282 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
3283 *stats->old_data_space_size = old_data_space_->Size();
3284 *stats->old_data_space_capacity = old_data_space_->Capacity();
3285 *stats->code_space_size = code_space_->Size();
3286 *stats->code_space_capacity = code_space_->Capacity();
3287 *stats->map_space_size = map_space_->Size();
3288 *stats->map_space_capacity = map_space_->Capacity();
3289 *stats->cell_space_size = cell_space_->Size();
3290 *stats->cell_space_capacity = cell_space_->Capacity();
3291 *stats->lo_space_size = lo_space_->Size();
3292 GlobalHandles::RecordStats(stats);
3293}
3294
3295
Steve Blocka7e24c12009-10-30 11:49:00 +00003296int Heap::PromotedSpaceSize() {
3297 return old_pointer_space_->Size()
3298 + old_data_space_->Size()
3299 + code_space_->Size()
3300 + map_space_->Size()
3301 + cell_space_->Size()
3302 + lo_space_->Size();
3303}
3304
3305
3306int Heap::PromotedExternalMemorySize() {
3307 if (amount_of_external_allocated_memory_
3308 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3309 return amount_of_external_allocated_memory_
3310 - amount_of_external_allocated_memory_at_last_global_gc_;
3311}
3312
3313
3314bool Heap::Setup(bool create_heap_objects) {
3315 // Initialize heap spaces and initial maps and objects. Whenever something
3316 // goes wrong, just return false. The caller should check the results and
3317 // call Heap::TearDown() to release allocated memory.
3318 //
3319 // If the heap is not yet configured (eg, through the API), configure it.
3320 // Configuration is based on the flags new-space-size (really the semispace
3321 // size) and old-space-size if set or the initial values of semispace_size_
3322 // and old_generation_size_ otherwise.
3323 if (!heap_configured) {
3324 if (!ConfigureHeapDefault()) return false;
3325 }
3326
3327 // Setup memory allocator and reserve a chunk of memory for new
Steve Block3ce2e202009-11-05 08:53:23 +00003328 // space. The chunk is double the size of the requested reserved
3329 // new space size to ensure that we can find a pair of semispaces that
3330 // are contiguous and aligned to their size.
3331 if (!MemoryAllocator::Setup(MaxReserved())) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00003332 void* chunk =
Steve Block3ce2e202009-11-05 08:53:23 +00003333 MemoryAllocator::ReserveInitialChunk(4 * reserved_semispace_size_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003334 if (chunk == NULL) return false;
3335
3336 // Align the pair of semispaces to their size, which must be a power
3337 // of 2.
Steve Blocka7e24c12009-10-30 11:49:00 +00003338 Address new_space_start =
Steve Block3ce2e202009-11-05 08:53:23 +00003339 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
3340 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
3341 return false;
3342 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003343
3344 // Initialize old pointer space.
3345 old_pointer_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003346 new OldSpace(max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003347 if (old_pointer_space_ == NULL) return false;
3348 if (!old_pointer_space_->Setup(NULL, 0)) return false;
3349
3350 // Initialize old data space.
3351 old_data_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003352 new OldSpace(max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003353 if (old_data_space_ == NULL) return false;
3354 if (!old_data_space_->Setup(NULL, 0)) return false;
3355
3356 // Initialize the code space, set its maximum capacity to the old
3357 // generation size. It needs executable memory.
3358 // On 64-bit platform(s), we put all code objects in a 2 GB range of
3359 // virtual address space, so that they can call each other with near calls.
3360 if (code_range_size_ > 0) {
3361 if (!CodeRange::Setup(code_range_size_)) {
3362 return false;
3363 }
3364 }
3365
3366 code_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00003367 new OldSpace(max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003368 if (code_space_ == NULL) return false;
3369 if (!code_space_->Setup(NULL, 0)) return false;
3370
3371 // Initialize map space.
3372 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
3373 if (map_space_ == NULL) return false;
3374 if (!map_space_->Setup(NULL, 0)) return false;
3375
3376 // Initialize global property cell space.
Steve Block3ce2e202009-11-05 08:53:23 +00003377 cell_space_ = new CellSpace(max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003378 if (cell_space_ == NULL) return false;
3379 if (!cell_space_->Setup(NULL, 0)) return false;
3380
3381 // The large object code space may contain code or data. We set the memory
3382 // to be non-executable here for safety, but this means we need to enable it
3383 // explicitly when allocating large code objects.
3384 lo_space_ = new LargeObjectSpace(LO_SPACE);
3385 if (lo_space_ == NULL) return false;
3386 if (!lo_space_->Setup()) return false;
3387
3388 if (create_heap_objects) {
3389 // Create initial maps.
3390 if (!CreateInitialMaps()) return false;
3391 if (!CreateApiObjects()) return false;
3392
3393 // Create initial objects
3394 if (!CreateInitialObjects()) return false;
3395 }
3396
3397 LOG(IntEvent("heap-capacity", Capacity()));
3398 LOG(IntEvent("heap-available", Available()));
3399
Steve Block3ce2e202009-11-05 08:53:23 +00003400#ifdef ENABLE_LOGGING_AND_PROFILING
3401 // This should be called only after initial objects have been created.
3402 ProducerHeapProfile::Setup();
3403#endif
3404
Steve Blocka7e24c12009-10-30 11:49:00 +00003405 return true;
3406}
3407
3408
Steve Blockd0582a62009-12-15 09:54:21 +00003409void Heap::SetStackLimits() {
Steve Blocka7e24c12009-10-30 11:49:00 +00003410 // On 64 bit machines, pointers are generally out of range of Smis. We write
3411 // something that looks like an out of range Smi to the GC.
3412
Steve Blockd0582a62009-12-15 09:54:21 +00003413 // Set up the special root array entries containing the stack limits.
3414 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00003415 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00003416 reinterpret_cast<Object*>(
3417 (StackGuard::jslimit() & ~kSmiTagMask) | kSmiTag);
3418 roots_[kRealStackLimitRootIndex] =
3419 reinterpret_cast<Object*>(
3420 (StackGuard::real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00003421}
3422
3423
3424void Heap::TearDown() {
3425 GlobalHandles::TearDown();
3426
3427 new_space_.TearDown();
3428
3429 if (old_pointer_space_ != NULL) {
3430 old_pointer_space_->TearDown();
3431 delete old_pointer_space_;
3432 old_pointer_space_ = NULL;
3433 }
3434
3435 if (old_data_space_ != NULL) {
3436 old_data_space_->TearDown();
3437 delete old_data_space_;
3438 old_data_space_ = NULL;
3439 }
3440
3441 if (code_space_ != NULL) {
3442 code_space_->TearDown();
3443 delete code_space_;
3444 code_space_ = NULL;
3445 }
3446
3447 if (map_space_ != NULL) {
3448 map_space_->TearDown();
3449 delete map_space_;
3450 map_space_ = NULL;
3451 }
3452
3453 if (cell_space_ != NULL) {
3454 cell_space_->TearDown();
3455 delete cell_space_;
3456 cell_space_ = NULL;
3457 }
3458
3459 if (lo_space_ != NULL) {
3460 lo_space_->TearDown();
3461 delete lo_space_;
3462 lo_space_ = NULL;
3463 }
3464
3465 MemoryAllocator::TearDown();
3466}
3467
3468
3469void Heap::Shrink() {
3470 // Try to shrink all paged spaces.
3471 PagedSpaces spaces;
3472 while (PagedSpace* space = spaces.next()) space->Shrink();
3473}
3474
3475
3476#ifdef ENABLE_HEAP_PROTECTION
3477
3478void Heap::Protect() {
3479 if (HasBeenSetup()) {
3480 AllSpaces spaces;
3481 while (Space* space = spaces.next()) space->Protect();
3482 }
3483}
3484
3485
3486void Heap::Unprotect() {
3487 if (HasBeenSetup()) {
3488 AllSpaces spaces;
3489 while (Space* space = spaces.next()) space->Unprotect();
3490 }
3491}
3492
3493#endif
3494
3495
3496#ifdef DEBUG
3497
3498class PrintHandleVisitor: public ObjectVisitor {
3499 public:
3500 void VisitPointers(Object** start, Object** end) {
3501 for (Object** p = start; p < end; p++)
3502 PrintF(" handle %p to %p\n", p, *p);
3503 }
3504};
3505
3506void Heap::PrintHandles() {
3507 PrintF("Handles:\n");
3508 PrintHandleVisitor v;
3509 HandleScopeImplementer::Iterate(&v);
3510}
3511
3512#endif
3513
3514
3515Space* AllSpaces::next() {
3516 switch (counter_++) {
3517 case NEW_SPACE:
3518 return Heap::new_space();
3519 case OLD_POINTER_SPACE:
3520 return Heap::old_pointer_space();
3521 case OLD_DATA_SPACE:
3522 return Heap::old_data_space();
3523 case CODE_SPACE:
3524 return Heap::code_space();
3525 case MAP_SPACE:
3526 return Heap::map_space();
3527 case CELL_SPACE:
3528 return Heap::cell_space();
3529 case LO_SPACE:
3530 return Heap::lo_space();
3531 default:
3532 return NULL;
3533 }
3534}
3535
3536
3537PagedSpace* PagedSpaces::next() {
3538 switch (counter_++) {
3539 case OLD_POINTER_SPACE:
3540 return Heap::old_pointer_space();
3541 case OLD_DATA_SPACE:
3542 return Heap::old_data_space();
3543 case CODE_SPACE:
3544 return Heap::code_space();
3545 case MAP_SPACE:
3546 return Heap::map_space();
3547 case CELL_SPACE:
3548 return Heap::cell_space();
3549 default:
3550 return NULL;
3551 }
3552}
3553
3554
3555
3556OldSpace* OldSpaces::next() {
3557 switch (counter_++) {
3558 case OLD_POINTER_SPACE:
3559 return Heap::old_pointer_space();
3560 case OLD_DATA_SPACE:
3561 return Heap::old_data_space();
3562 case CODE_SPACE:
3563 return Heap::code_space();
3564 default:
3565 return NULL;
3566 }
3567}
3568
3569
3570SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3571}
3572
3573
3574SpaceIterator::~SpaceIterator() {
3575 // Delete active iterator if any.
3576 delete iterator_;
3577}
3578
3579
3580bool SpaceIterator::has_next() {
3581 // Iterate until no more spaces.
3582 return current_space_ != LAST_SPACE;
3583}
3584
3585
3586ObjectIterator* SpaceIterator::next() {
3587 if (iterator_ != NULL) {
3588 delete iterator_;
3589 iterator_ = NULL;
3590 // Move to the next space
3591 current_space_++;
3592 if (current_space_ > LAST_SPACE) {
3593 return NULL;
3594 }
3595 }
3596
3597 // Return iterator for the new current space.
3598 return CreateIterator();
3599}
3600
3601
3602// Create an iterator for the space to iterate.
3603ObjectIterator* SpaceIterator::CreateIterator() {
3604 ASSERT(iterator_ == NULL);
3605
3606 switch (current_space_) {
3607 case NEW_SPACE:
3608 iterator_ = new SemiSpaceIterator(Heap::new_space());
3609 break;
3610 case OLD_POINTER_SPACE:
3611 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3612 break;
3613 case OLD_DATA_SPACE:
3614 iterator_ = new HeapObjectIterator(Heap::old_data_space());
3615 break;
3616 case CODE_SPACE:
3617 iterator_ = new HeapObjectIterator(Heap::code_space());
3618 break;
3619 case MAP_SPACE:
3620 iterator_ = new HeapObjectIterator(Heap::map_space());
3621 break;
3622 case CELL_SPACE:
3623 iterator_ = new HeapObjectIterator(Heap::cell_space());
3624 break;
3625 case LO_SPACE:
3626 iterator_ = new LargeObjectIterator(Heap::lo_space());
3627 break;
3628 }
3629
3630 // Return the newly allocated iterator;
3631 ASSERT(iterator_ != NULL);
3632 return iterator_;
3633}
3634
3635
3636HeapIterator::HeapIterator() {
3637 Init();
3638}
3639
3640
3641HeapIterator::~HeapIterator() {
3642 Shutdown();
3643}
3644
3645
3646void HeapIterator::Init() {
3647 // Start the iteration.
3648 space_iterator_ = new SpaceIterator();
3649 object_iterator_ = space_iterator_->next();
3650}
3651
3652
3653void HeapIterator::Shutdown() {
3654 // Make sure the last iterator is deallocated.
3655 delete space_iterator_;
3656 space_iterator_ = NULL;
3657 object_iterator_ = NULL;
3658}
3659
3660
3661bool HeapIterator::has_next() {
3662 // No iterator means we are done.
3663 if (object_iterator_ == NULL) return false;
3664
3665 if (object_iterator_->has_next_object()) {
3666 // If the current iterator has more objects we are fine.
3667 return true;
3668 } else {
3669 // Go though the spaces looking for one that has objects.
3670 while (space_iterator_->has_next()) {
3671 object_iterator_ = space_iterator_->next();
3672 if (object_iterator_->has_next_object()) {
3673 return true;
3674 }
3675 }
3676 }
3677 // Done with the last space.
3678 object_iterator_ = NULL;
3679 return false;
3680}
3681
3682
3683HeapObject* HeapIterator::next() {
3684 if (has_next()) {
3685 return object_iterator_->next_object();
3686 } else {
3687 return NULL;
3688 }
3689}
3690
3691
3692void HeapIterator::reset() {
3693 // Restart the iterator.
3694 Shutdown();
3695 Init();
3696}
3697
3698
3699#ifdef DEBUG
3700
3701static bool search_for_any_global;
3702static Object* search_target;
3703static bool found_target;
3704static List<Object*> object_stack(20);
3705
3706
3707// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3708static const int kMarkTag = 2;
3709
3710static void MarkObjectRecursively(Object** p);
3711class MarkObjectVisitor : public ObjectVisitor {
3712 public:
3713 void VisitPointers(Object** start, Object** end) {
3714 // Copy all HeapObject pointers in [start, end)
3715 for (Object** p = start; p < end; p++) {
3716 if ((*p)->IsHeapObject())
3717 MarkObjectRecursively(p);
3718 }
3719 }
3720};
3721
3722static MarkObjectVisitor mark_visitor;
3723
3724static void MarkObjectRecursively(Object** p) {
3725 if (!(*p)->IsHeapObject()) return;
3726
3727 HeapObject* obj = HeapObject::cast(*p);
3728
3729 Object* map = obj->map();
3730
3731 if (!map->IsHeapObject()) return; // visited before
3732
3733 if (found_target) return; // stop if target found
3734 object_stack.Add(obj);
3735 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3736 (!search_for_any_global && (obj == search_target))) {
3737 found_target = true;
3738 return;
3739 }
3740
3741 // not visited yet
3742 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3743
3744 Address map_addr = map_p->address();
3745
3746 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3747
3748 MarkObjectRecursively(&map);
3749
3750 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3751 &mark_visitor);
3752
3753 if (!found_target) // don't pop if found the target
3754 object_stack.RemoveLast();
3755}
3756
3757
3758static void UnmarkObjectRecursively(Object** p);
3759class UnmarkObjectVisitor : public ObjectVisitor {
3760 public:
3761 void VisitPointers(Object** start, Object** end) {
3762 // Copy all HeapObject pointers in [start, end)
3763 for (Object** p = start; p < end; p++) {
3764 if ((*p)->IsHeapObject())
3765 UnmarkObjectRecursively(p);
3766 }
3767 }
3768};
3769
3770static UnmarkObjectVisitor unmark_visitor;
3771
3772static void UnmarkObjectRecursively(Object** p) {
3773 if (!(*p)->IsHeapObject()) return;
3774
3775 HeapObject* obj = HeapObject::cast(*p);
3776
3777 Object* map = obj->map();
3778
3779 if (map->IsHeapObject()) return; // unmarked already
3780
3781 Address map_addr = reinterpret_cast<Address>(map);
3782
3783 map_addr -= kMarkTag;
3784
3785 ASSERT_TAG_ALIGNED(map_addr);
3786
3787 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3788
3789 obj->set_map(reinterpret_cast<Map*>(map_p));
3790
3791 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3792
3793 obj->IterateBody(Map::cast(map_p)->instance_type(),
3794 obj->SizeFromMap(Map::cast(map_p)),
3795 &unmark_visitor);
3796}
3797
3798
3799static void MarkRootObjectRecursively(Object** root) {
3800 if (search_for_any_global) {
3801 ASSERT(search_target == NULL);
3802 } else {
3803 ASSERT(search_target->IsHeapObject());
3804 }
3805 found_target = false;
3806 object_stack.Clear();
3807
3808 MarkObjectRecursively(root);
3809 UnmarkObjectRecursively(root);
3810
3811 if (found_target) {
3812 PrintF("=====================================\n");
3813 PrintF("==== Path to object ====\n");
3814 PrintF("=====================================\n\n");
3815
3816 ASSERT(!object_stack.is_empty());
3817 for (int i = 0; i < object_stack.length(); i++) {
3818 if (i > 0) PrintF("\n |\n |\n V\n\n");
3819 Object* obj = object_stack[i];
3820 obj->Print();
3821 }
3822 PrintF("=====================================\n");
3823 }
3824}
3825
3826
3827// Helper class for visiting HeapObjects recursively.
3828class MarkRootVisitor: public ObjectVisitor {
3829 public:
3830 void VisitPointers(Object** start, Object** end) {
3831 // Visit all HeapObject pointers in [start, end)
3832 for (Object** p = start; p < end; p++) {
3833 if ((*p)->IsHeapObject())
3834 MarkRootObjectRecursively(p);
3835 }
3836 }
3837};
3838
3839
3840// Triggers a depth-first traversal of reachable objects from roots
3841// and finds a path to a specific heap object and prints it.
3842void Heap::TracePathToObject() {
3843 search_target = NULL;
3844 search_for_any_global = false;
3845
3846 MarkRootVisitor root_visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00003847 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00003848}
3849
3850
3851// Triggers a depth-first traversal of reachable objects from roots
3852// and finds a path to any global object and prints it. Useful for
3853// determining the source for leaks of global objects.
3854void Heap::TracePathToGlobal() {
3855 search_target = NULL;
3856 search_for_any_global = true;
3857
3858 MarkRootVisitor root_visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00003859 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00003860}
3861#endif
3862
3863
3864GCTracer::GCTracer()
3865 : start_time_(0.0),
3866 start_size_(0.0),
3867 gc_count_(0),
3868 full_gc_count_(0),
3869 is_compacting_(false),
3870 marked_count_(0) {
3871 // These two fields reflect the state of the previous full collection.
3872 // Set them before they are changed by the collector.
3873 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3874 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3875 if (!FLAG_trace_gc) return;
3876 start_time_ = OS::TimeCurrentMillis();
3877 start_size_ = SizeOfHeapObjects();
3878}
3879
3880
3881GCTracer::~GCTracer() {
3882 if (!FLAG_trace_gc) return;
3883 // Printf ONE line iff flag is set.
3884 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3885 CollectorString(),
3886 start_size_, SizeOfHeapObjects(),
3887 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3888
3889#if defined(ENABLE_LOGGING_AND_PROFILING)
3890 Heap::PrintShortHeapStatistics();
3891#endif
3892}
3893
3894
3895const char* GCTracer::CollectorString() {
3896 switch (collector_) {
3897 case SCAVENGER:
3898 return "Scavenge";
3899 case MARK_COMPACTOR:
3900 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3901 : "Mark-sweep";
3902 }
3903 return "Unknown GC";
3904}
3905
3906
3907int KeyedLookupCache::Hash(Map* map, String* name) {
3908 // Uses only lower 32 bits if pointers are larger.
3909 uintptr_t addr_hash =
3910 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
3911 return (addr_hash ^ name->Hash()) % kLength;
3912}
3913
3914
3915int KeyedLookupCache::Lookup(Map* map, String* name) {
3916 int index = Hash(map, name);
3917 Key& key = keys_[index];
3918 if ((key.map == map) && key.name->Equals(name)) {
3919 return field_offsets_[index];
3920 }
3921 return -1;
3922}
3923
3924
3925void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
3926 String* symbol;
3927 if (Heap::LookupSymbolIfExists(name, &symbol)) {
3928 int index = Hash(map, symbol);
3929 Key& key = keys_[index];
3930 key.map = map;
3931 key.name = symbol;
3932 field_offsets_[index] = field_offset;
3933 }
3934}
3935
3936
3937void KeyedLookupCache::Clear() {
3938 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
3939}
3940
3941
3942KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
3943
3944
3945int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
3946
3947
3948void DescriptorLookupCache::Clear() {
3949 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
3950}
3951
3952
3953DescriptorLookupCache::Key
3954DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
3955
3956int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
3957
3958
3959#ifdef DEBUG
3960bool Heap::GarbageCollectionGreedyCheck() {
3961 ASSERT(FLAG_gc_greedy);
3962 if (Bootstrapper::IsActive()) return true;
3963 if (disallow_allocation_failure()) return true;
3964 return CollectGarbage(0, NEW_SPACE);
3965}
3966#endif
3967
3968
3969TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
3970 : type_(t) {
3971 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
3972 uint32_t in1 = 0xffffffffu; // generated by the FPU.
3973 for (int i = 0; i < kCacheSize; i++) {
3974 elements_[i].in[0] = in0;
3975 elements_[i].in[1] = in1;
3976 elements_[i].output = NULL;
3977 }
3978}
3979
3980
3981TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
3982
3983
3984void TranscendentalCache::Clear() {
3985 for (int i = 0; i < kNumberOfCaches; i++) {
3986 if (caches_[i] != NULL) {
3987 delete caches_[i];
3988 caches_[i] = NULL;
3989 }
3990 }
3991}
3992
3993
3994} } // namespace v8::internal