blob: 00cf78be58d909127668ce74e635b215bf2ab58f [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// 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"
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "debug.h"
36#include "global-handles.h"
37#include "jsregexp.h"
38#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
42#include "v8threads.h"
43
44namespace v8 { namespace internal {
45
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
47 ROOT_LIST(ROOT_ALLOCATION)
48#undef ROOT_ALLOCATION
49
50
51#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
52 STRUCT_LIST(STRUCT_ALLOCATION)
53#undef STRUCT_ALLOCATION
54
55
56#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
57 SYMBOL_LIST(SYMBOL_ALLOCATION)
58#undef SYMBOL_ALLOCATION
59
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000060NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000061OldSpace* Heap::old_pointer_space_ = NULL;
62OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000063OldSpace* Heap::code_space_ = NULL;
64MapSpace* Heap::map_space_ = NULL;
65LargeObjectSpace* Heap::lo_space_ = NULL;
66
67int Heap::promoted_space_limit_ = 0;
68int Heap::old_gen_exhausted_ = false;
69
kasper.lund7276f142008-07-30 08:49:36 +000070int Heap::amount_of_external_allocated_memory_ = 0;
71int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
72
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073// semispace_size_ should be a power of 2 and old_generation_size_ should be
74// a multiple of Page::kPageSize.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000075int Heap::semispace_size_ = 2*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000076int Heap::old_generation_size_ = 512*MB;
77int Heap::initial_semispace_size_ = 256*KB;
78
79GCCallback Heap::global_gc_prologue_callback_ = NULL;
80GCCallback Heap::global_gc_epilogue_callback_ = NULL;
81
82// Variables set based on semispace_size_ and old_generation_size_ in
83// ConfigureHeap.
84int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
85
86// Double the new space after this many scavenge collections.
87int Heap::new_space_growth_limit_ = 8;
88int Heap::scavenge_count_ = 0;
89Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
90
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000091int Heap::mc_count_ = 0;
92int Heap::gc_count_ = 0;
93
kasper.lund7276f142008-07-30 08:49:36 +000094#ifdef DEBUG
95bool Heap::allocation_allowed_ = true;
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097int Heap::allocation_timeout_ = 0;
98bool Heap::disallow_allocation_failure_ = false;
99#endif // DEBUG
100
101
102int Heap::Capacity() {
103 if (!HasBeenSetup()) return 0;
104
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000105 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000106 old_pointer_space_->Capacity() +
107 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000108 code_space_->Capacity() +
109 map_space_->Capacity();
110}
111
112
113int Heap::Available() {
114 if (!HasBeenSetup()) return 0;
115
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000116 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000117 old_pointer_space_->Available() +
118 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000119 code_space_->Available() +
120 map_space_->Available();
121}
122
123
124bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000125 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000126 old_data_space_ != NULL &&
127 code_space_ != NULL &&
128 map_space_ != NULL &&
129 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000130}
131
132
133GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
134 // Is global GC requested?
135 if (space != NEW_SPACE || FLAG_gc_global) {
136 Counters::gc_compactor_caused_by_request.Increment();
137 return MARK_COMPACTOR;
138 }
139
140 // Is enough data promoted to justify a global GC?
kasper.lund7276f142008-07-30 08:49:36 +0000141 if (PromotedSpaceSize() + PromotedExternalMemorySize()
142 > promoted_space_limit_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000143 Counters::gc_compactor_caused_by_promoted_data.Increment();
144 return MARK_COMPACTOR;
145 }
146
147 // Have allocation in OLD and LO failed?
148 if (old_gen_exhausted_) {
149 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
150 return MARK_COMPACTOR;
151 }
152
153 // Is there enough space left in OLD to guarantee that a scavenge can
154 // succeed?
155 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000156 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000157 // for object promotion. It counts only the bytes that the memory
158 // allocator has not yet allocated from the OS and assigned to any space,
159 // and does not count available bytes already in the old space or code
160 // space. Undercounting is safe---we may get an unrequested full GC when
161 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000162 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000163 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
164 return MARK_COMPACTOR;
165 }
166
167 // Default
168 return SCAVENGER;
169}
170
171
172// TODO(1238405): Combine the infrastructure for --heap-stats and
173// --log-gc to avoid the complicated preprocessor and flag testing.
174#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
175void Heap::ReportStatisticsBeforeGC() {
176 // Heap::ReportHeapStatistics will also log NewSpace statistics when
177 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
178 // following logic is used to avoid double logging.
179#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000180 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000181 if (FLAG_heap_stats) {
182 ReportHeapStatistics("Before GC");
183 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000184 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000185 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000186 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187#elif defined(DEBUG)
188 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000189 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000190 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000191 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000192 }
193#elif defined(ENABLE_LOGGING_AND_PROFILING)
194 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000195 new_space_.CollectStatistics();
196 new_space_.ReportStatistics();
197 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 }
199#endif
200}
201
202
203// TODO(1238405): Combine the infrastructure for --heap-stats and
204// --log-gc to avoid the complicated preprocessor and flag testing.
205void Heap::ReportStatisticsAfterGC() {
206 // Similar to the before GC, we use some complicated logic to ensure that
207 // NewSpace statistics are logged exactly once when --log-gc is turned on.
208#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
209 if (FLAG_heap_stats) {
210 ReportHeapStatistics("After GC");
211 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000212 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000213 }
214#elif defined(DEBUG)
215 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
216#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000217 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000218#endif
219}
220#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
221
222
223void Heap::GarbageCollectionPrologue() {
224 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000225 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226#ifdef DEBUG
227 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
228 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000229
230 if (FLAG_verify_heap) {
231 Verify();
232 }
233
234 if (FLAG_gc_verbose) Print();
235
236 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000237 // Not all spaces have remembered set bits that we care about.
238 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239 map_space_->PrintRSet();
240 lo_space_->PrintRSet();
241 }
242#endif
243
244#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
245 ReportStatisticsBeforeGC();
246#endif
247}
248
249int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000250 int total = 0;
251 AllSpaces spaces;
252 while (Space* space = spaces.next()) total += space->Size();
253 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000254}
255
256void Heap::GarbageCollectionEpilogue() {
257#ifdef DEBUG
258 allow_allocation(true);
259 ZapFromSpace();
260
261 if (FLAG_verify_heap) {
262 Verify();
263 }
264
265 if (FLAG_print_global_handles) GlobalHandles::Print();
266 if (FLAG_print_handles) PrintHandles();
267 if (FLAG_gc_verbose) Print();
268 if (FLAG_code_stats) ReportCodeStatistics("After GC");
269#endif
270
271 Counters::alive_after_last_gc.Set(SizeOfObjects());
272
273 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
274 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
275 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
276#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
277 ReportStatisticsAfterGC();
278#endif
279}
280
281
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000282void Heap::CollectAllGarbage() {
283 // Since we are ignoring the return value, the exact choice of space does
284 // not matter, so long as we do not specify NEW_SPACE, which would not
285 // cause a full GC.
286 CollectGarbage(0, OLD_POINTER_SPACE);
287}
288
289
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
291 // The VM is in the GC state until exiting this function.
292 VMState state(GC);
293
294#ifdef DEBUG
295 // Reset the allocation timeout to the GC interval, but make sure to
296 // allow at least a few allocations after a collection. The reason
297 // for this is that we have a lot of allocation sequences and we
298 // assume that a garbage collection will allow the subsequent
299 // allocation attempts to go through.
300 allocation_timeout_ = Max(6, FLAG_gc_interval);
301#endif
302
303 { GCTracer tracer;
304 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000305 // The GC count was incremented in the prologue. Tell the tracer about
306 // it.
307 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308
309 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000310 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000311 tracer.set_collector(collector);
312
313 StatsRate* rate = (collector == SCAVENGER)
314 ? &Counters::gc_scavenger
315 : &Counters::gc_compactor;
316 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000317 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318 rate->Stop();
319
320 GarbageCollectionEpilogue();
321 }
322
323
324#ifdef ENABLE_LOGGING_AND_PROFILING
325 if (FLAG_log_gc) HeapProfiler::WriteSample();
326#endif
327
328 switch (space) {
329 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000330 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000331 case OLD_POINTER_SPACE:
332 return old_pointer_space_->Available() >= requested_size;
333 case OLD_DATA_SPACE:
334 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335 case CODE_SPACE:
336 return code_space_->Available() >= requested_size;
337 case MAP_SPACE:
338 return map_space_->Available() >= requested_size;
339 case LO_SPACE:
340 return lo_space_->Available() >= requested_size;
341 }
342 return false;
343}
344
345
kasper.lund7276f142008-07-30 08:49:36 +0000346void Heap::PerformScavenge() {
347 GCTracer tracer;
348 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
349}
350
351
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000352void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000353 GarbageCollector collector,
354 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
356 ASSERT(!allocation_allowed_);
357 global_gc_prologue_callback_();
358 }
359
360 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000361 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000362
363 int promoted_space_size = PromotedSpaceSize();
364 promoted_space_limit_ =
365 promoted_space_size + Max(2 * MB, (promoted_space_size/100) * 35);
366 old_gen_exhausted_ = false;
367
368 // If we have used the mark-compact collector to collect the new
369 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000370 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000371 // case where (1) a new space collection was requested, (2) the
372 // collector selection policy selected the mark-compact collector,
373 // and (3) the mark-compact collector policy selected not to
374 // compact the new space. In that case, there is no more (usable)
375 // free space in the new space after the collection compared to
376 // before.
377 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
378 Scavenge();
379 }
380 } else {
381 Scavenge();
382 }
383 Counters::objs_since_last_young.Set(0);
384
385 // Process weak handles post gc.
386 GlobalHandles::PostGarbageCollectionProcessing();
387
kasper.lund7276f142008-07-30 08:49:36 +0000388 if (collector == MARK_COMPACTOR) {
389 // Register the amount of external allocated memory.
390 amount_of_external_allocated_memory_at_last_global_gc_ =
391 amount_of_external_allocated_memory_;
392 }
393
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
395 ASSERT(!allocation_allowed_);
396 global_gc_epilogue_callback_();
397 }
398}
399
400
kasper.lund7276f142008-07-30 08:49:36 +0000401void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000403 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000404 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000405 LOG(ResourceEvent("markcompact", "begin"));
406
407 MarkCompactPrologue();
408
kasper.lund7276f142008-07-30 08:49:36 +0000409 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410
411 MarkCompactEpilogue();
412
413 LOG(ResourceEvent("markcompact", "end"));
414
415 gc_state_ = NOT_IN_GC;
416
417 Shrink();
418
419 Counters::objs_since_last_full.Set(0);
420}
421
422
423void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000424 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000425 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000426 RegExpImpl::OldSpaceCollectionPrologue();
427 Top::MarkCompactPrologue();
428 ThreadManager::MarkCompactPrologue();
429}
430
431
432void Heap::MarkCompactEpilogue() {
433 Top::MarkCompactEpilogue();
434 ThreadManager::MarkCompactEpilogue();
435}
436
437
438Object* Heap::FindCodeObject(Address a) {
439 Object* obj = code_space_->FindObject(a);
440 if (obj->IsFailure()) {
441 obj = lo_space_->FindObject(a);
442 }
kasper.lund7276f142008-07-30 08:49:36 +0000443 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444 return obj;
445}
446
447
448// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000449class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450 public:
451
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000452 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000453
454 void VisitPointers(Object** start, Object** end) {
455 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000456 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000457 }
458
459 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000460 void ScavengePointer(Object** p) {
461 Object* object = *p;
462 if (!Heap::InNewSpace(object)) return;
463 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
464 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 }
466};
467
468
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000469// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470static Address promoted_top = NULL;
471
472
473#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000474// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000476class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477 public:
478 void VisitPointers(Object** start, Object**end) {
479 for (Object** current = start; current < end; current++) {
480 if ((*current)->IsHeapObject()) {
481 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
482 }
483 }
484 }
485};
486#endif
487
488void Heap::Scavenge() {
489#ifdef DEBUG
490 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000491 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492 HeapObjectIterator it(code_space_);
493 while (it.has_next()) {
494 HeapObject* object = it.next();
495 if (object->IsCode()) {
496 Code::cast(object)->ConvertICTargetsFromAddressToObject();
497 }
498 object->Iterate(&v);
499 if (object->IsCode()) {
500 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
501 }
502 }
503 }
504#endif
505
506 gc_state_ = SCAVENGE;
507
508 // Implements Cheney's copying algorithm
509 LOG(ResourceEvent("scavenge", "begin"));
510
511 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000512 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000513 scavenge_count_ > new_space_growth_limit_) {
514 // Double the size of the new space, and double the limit. The next
515 // doubling attempt will occur after the current new_space_growth_limit_
516 // more collections.
517 // TODO(1240712): NewSpace::Double has a return value which is
518 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000519 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 new_space_growth_limit_ *= 2;
521 }
522
523 // Flip the semispaces. After flipping, to space is empty, from space has
524 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000525 new_space_.Flip();
526 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000527
528 // We need to sweep newly copied objects which can be in either the to space
529 // or the old space. For to space objects, we use a mark. Newly copied
530 // objects lie between the mark and the allocation top. For objects
531 // promoted to old space, we write their addresses downward from the top of
532 // the new space. Sweeping newly promoted objects requires an allocation
533 // pointer and a mark. Note that the allocation pointer 'top' actually
534 // moves downward from the high address in the to space.
535 //
536 // There is guaranteed to be enough room at the top of the to space for the
537 // addresses of promoted objects: every object promoted frees up its size in
538 // bytes from the top of the new space, and objects are at least one pointer
539 // in size. Using the new space to record promoted addresses makes the
540 // scavenge collector agnostic to the allocation strategy (eg, linear or
541 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000542 Address new_mark = new_space_.ToSpaceLow();
543 Address promoted_mark = new_space_.ToSpaceHigh();
544 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000545
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000546 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000547 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000548 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000549
550 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000551 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000552 IterateRSet(old_pointer_space_, &ScavengePointer);
553 IterateRSet(map_space_, &ScavengePointer);
554 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555
556 bool has_processed_weak_pointers = false;
557
558 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000559 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000560 ASSERT(promoted_mark >= promoted_top);
561
562 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000563 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564 // Sweep newly copied objects in the to space. The allocation pointer
565 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000566 Address previous_top = new_space_.top();
567 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000569 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570 }
571 new_mark = previous_top;
572
573 // Sweep newly copied objects in the old space. The promotion 'top'
574 // pointer could change during sweeping.
575 previous_top = promoted_top;
576 for (Address current = promoted_mark - kPointerSize;
577 current >= previous_top;
578 current -= kPointerSize) {
579 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000580 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581 UpdateRSet(object);
582 }
583 promoted_mark = previous_top;
584 }
585
586 if (has_processed_weak_pointers) break; // We are done.
587 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000588 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 has_processed_weak_pointers = true;
590 }
591
592 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000593 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594
595 LOG(ResourceEvent("scavenge", "end"));
596
597 gc_state_ = NOT_IN_GC;
598}
599
600
601void Heap::ClearRSetRange(Address start, int size_in_bytes) {
602 uint32_t start_bit;
603 Address start_word_address =
604 Page::ComputeRSetBitPosition(start, 0, &start_bit);
605 uint32_t end_bit;
606 Address end_word_address =
607 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
608 0,
609 &end_bit);
610
611 // We want to clear the bits in the starting word starting with the
612 // first bit, and in the ending word up to and including the last
613 // bit. Build a pair of bitmasks to do that.
614 uint32_t start_bitmask = start_bit - 1;
615 uint32_t end_bitmask = ~((end_bit << 1) - 1);
616
617 // If the start address and end address are the same, we mask that
618 // word once, otherwise mask the starting and ending word
619 // separately and all the ones in between.
620 if (start_word_address == end_word_address) {
621 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
622 } else {
623 Memory::uint32_at(start_word_address) &= start_bitmask;
624 Memory::uint32_at(end_word_address) &= end_bitmask;
625 start_word_address += kIntSize;
626 memset(start_word_address, 0, end_word_address - start_word_address);
627 }
628}
629
630
631class UpdateRSetVisitor: public ObjectVisitor {
632 public:
633
634 void VisitPointer(Object** p) {
635 UpdateRSet(p);
636 }
637
638 void VisitPointers(Object** start, Object** end) {
639 // Update a store into slots [start, end), used (a) to update remembered
640 // set when promoting a young object to old space or (b) to rebuild
641 // remembered sets after a mark-compact collection.
642 for (Object** p = start; p < end; p++) UpdateRSet(p);
643 }
644 private:
645
646 void UpdateRSet(Object** p) {
647 // The remembered set should not be set. It should be clear for objects
648 // newly copied to old space, and it is cleared before rebuilding in the
649 // mark-compact collector.
650 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
651 if (Heap::InNewSpace(*p)) {
652 Page::SetRSet(reinterpret_cast<Address>(p), 0);
653 }
654 }
655};
656
657
658int Heap::UpdateRSet(HeapObject* obj) {
659 ASSERT(!InNewSpace(obj));
660 // Special handling of fixed arrays to iterate the body based on the start
661 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
662 // will not work because Page::SetRSet needs to have the start of the
663 // object.
664 if (obj->IsFixedArray()) {
665 FixedArray* array = FixedArray::cast(obj);
666 int length = array->length();
667 for (int i = 0; i < length; i++) {
668 int offset = FixedArray::kHeaderSize + i * kPointerSize;
669 ASSERT(!Page::IsRSetSet(obj->address(), offset));
670 if (Heap::InNewSpace(array->get(i))) {
671 Page::SetRSet(obj->address(), offset);
672 }
673 }
674 } else if (!obj->IsCode()) {
675 // Skip code object, we know it does not contain inter-generational
676 // pointers.
677 UpdateRSetVisitor v;
678 obj->Iterate(&v);
679 }
680 return obj->Size();
681}
682
683
684void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000685 // By definition, we do not care about remembered set bits in code or data
686 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000687 map_space_->ClearRSet();
688 RebuildRSets(map_space_);
689
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000690 old_pointer_space_->ClearRSet();
691 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000692
693 Heap::lo_space_->ClearRSet();
694 RebuildRSets(lo_space_);
695}
696
697
698void Heap::RebuildRSets(PagedSpace* space) {
699 HeapObjectIterator it(space);
700 while (it.has_next()) Heap::UpdateRSet(it.next());
701}
702
703
704void Heap::RebuildRSets(LargeObjectSpace* space) {
705 LargeObjectIterator it(space);
706 while (it.has_next()) Heap::UpdateRSet(it.next());
707}
708
709
710#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
711void Heap::RecordCopiedObject(HeapObject* obj) {
712 bool should_record = false;
713#ifdef DEBUG
714 should_record = FLAG_heap_stats;
715#endif
716#ifdef ENABLE_LOGGING_AND_PROFILING
717 should_record = should_record || FLAG_log_gc;
718#endif
719 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000720 if (new_space_.Contains(obj)) {
721 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000723 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000724 }
725 }
726}
727#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
728
729
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000730
731HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000732 HeapObject* target,
733 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000734 // Copy the content of source to target.
735 CopyBlock(reinterpret_cast<Object**>(target->address()),
736 reinterpret_cast<Object**>(source->address()),
737 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000738
kasper.lund7276f142008-07-30 08:49:36 +0000739 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000740 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000741
742 // Update NewSpace stats if necessary.
743#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
744 RecordCopiedObject(target);
745#endif
746
747 return target;
748}
749
750
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000751// Inlined function.
752void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
753 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000754
kasper.lund7276f142008-07-30 08:49:36 +0000755 // We use the first word (where the map pointer usually is) of a heap
756 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000757 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000759 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000760
kasper.lund7276f142008-07-30 08:49:36 +0000761 // If the first word is a forwarding address, the object has already been
762 // copied.
763 if (first_word.IsForwardingAddress()) {
764 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000765 return;
766 }
767
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000768 // Call the slow part of scavenge object.
769 return ScavengeObjectSlow(p, object);
770}
771
772static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
773 // A ConString object with Heap::empty_string() as the right side
774 // is a candidate for being shortcut by the scavenger.
775 ASSERT(object->map() == map);
776 return (map->instance_type() < FIRST_NONSTRING_TYPE) &&
777 (String::cast(object)->map_representation_tag(map) == kConsStringTag) &&
778 (ConsString::cast(object)->second() == Heap::empty_string());
779}
780
781
782void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
783 ASSERT(InFromSpace(object));
784 MapWord first_word = object->map_word();
785 ASSERT(!first_word.IsForwardingAddress());
786
787 // Optimization: Bypass flattened ConsString objects.
788 if (IsShortcutCandidate(object, first_word.ToMap())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000789 object = HeapObject::cast(ConsString::cast(object)->first());
790 *p = object;
791 // After patching *p we have to repeat the checks that object is in the
792 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000793 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000794 first_word = object->map_word();
795 if (first_word.IsForwardingAddress()) {
796 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 return;
798 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000799 }
800
kasper.lund7276f142008-07-30 08:49:36 +0000801 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000802 // If the object should be promoted, we try to copy it to old space.
803 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000804 OldSpace* target_space = Heap::TargetSpace(object);
805 ASSERT(target_space == Heap::old_pointer_space_ ||
806 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000807 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000809 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000810 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811 // Record the object's address at the top of the to space, to allow
812 // it to be swept by the scavenger.
813 promoted_top -= kPointerSize;
814 Memory::Object_at(promoted_top) = *p;
815 } else {
816#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000817 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000818 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000819 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820 (*p)->Iterate(&v);
821#endif
822 }
823 return;
824 }
825 }
826
827 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000828 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000829 // Failed allocation at this point is utterly unexpected.
830 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000831 *p = MigrateObject(object, HeapObject::cast(result), object_size);
832}
833
834
835void Heap::ScavengePointer(HeapObject** p) {
836 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837}
838
839
840Object* Heap::AllocatePartialMap(InstanceType instance_type,
841 int instance_size) {
842 Object* result = AllocateRawMap(Map::kSize);
843 if (result->IsFailure()) return result;
844
845 // Map::cast cannot be used due to uninitialized map field.
846 reinterpret_cast<Map*>(result)->set_map(meta_map());
847 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
848 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000849 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000850 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
851 return result;
852}
853
854
855Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
856 Object* result = AllocateRawMap(Map::kSize);
857 if (result->IsFailure()) return result;
858
859 Map* map = reinterpret_cast<Map*>(result);
860 map->set_map(meta_map());
861 map->set_instance_type(instance_type);
862 map->set_prototype(null_value());
863 map->set_constructor(null_value());
864 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000865 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000866 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000867 map->set_code_cache(empty_fixed_array());
868 map->set_unused_property_fields(0);
869 map->set_bit_field(0);
870 return map;
871}
872
873
874bool Heap::CreateInitialMaps() {
875 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
876 if (obj->IsFailure()) return false;
877
878 // Map::cast cannot be used due to uninitialized map field.
879 meta_map_ = reinterpret_cast<Map*>(obj);
880 meta_map()->set_map(meta_map());
881
882 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
883 if (obj->IsFailure()) return false;
884 fixed_array_map_ = Map::cast(obj);
885
886 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
887 if (obj->IsFailure()) return false;
888 oddball_map_ = Map::cast(obj);
889
890 // Allocate the empty array
891 obj = AllocateEmptyFixedArray();
892 if (obj->IsFailure()) return false;
893 empty_fixed_array_ = FixedArray::cast(obj);
894
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000895 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896 if (obj->IsFailure()) return false;
897 null_value_ = obj;
898
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000899 // Allocate the empty descriptor array. AllocateMap can now be used.
900 obj = AllocateEmptyFixedArray();
901 if (obj->IsFailure()) return false;
902 // There is a check against empty_descriptor_array() in cast().
903 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000904
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000905 // Fix the instance_descriptors for the existing maps.
906 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000907 meta_map()->set_code_cache(empty_fixed_array());
908
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000909 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910 fixed_array_map()->set_code_cache(empty_fixed_array());
911
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000912 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913 oddball_map()->set_code_cache(empty_fixed_array());
914
915 // Fix prototype object for existing maps.
916 meta_map()->set_prototype(null_value());
917 meta_map()->set_constructor(null_value());
918
919 fixed_array_map()->set_prototype(null_value());
920 fixed_array_map()->set_constructor(null_value());
921 oddball_map()->set_prototype(null_value());
922 oddball_map()->set_constructor(null_value());
923
924 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
925 if (obj->IsFailure()) return false;
926 heap_number_map_ = Map::cast(obj);
927
928 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
929 if (obj->IsFailure()) return false;
930 proxy_map_ = Map::cast(obj);
931
932#define ALLOCATE_STRING_MAP(type, size, name) \
933 obj = AllocateMap(type, size); \
934 if (obj->IsFailure()) return false; \
935 name##_map_ = Map::cast(obj);
936 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
937#undef ALLOCATE_STRING_MAP
938
ager@chromium.org7c537e22008-10-16 08:43:32 +0000939 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000940 if (obj->IsFailure()) return false;
941 undetectable_short_string_map_ = Map::cast(obj);
942 undetectable_short_string_map_->set_is_undetectable();
943
ager@chromium.org7c537e22008-10-16 08:43:32 +0000944 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000945 if (obj->IsFailure()) return false;
946 undetectable_medium_string_map_ = Map::cast(obj);
947 undetectable_medium_string_map_->set_is_undetectable();
948
ager@chromium.org7c537e22008-10-16 08:43:32 +0000949 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 if (obj->IsFailure()) return false;
951 undetectable_long_string_map_ = Map::cast(obj);
952 undetectable_long_string_map_->set_is_undetectable();
953
ager@chromium.org7c537e22008-10-16 08:43:32 +0000954 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000955 if (obj->IsFailure()) return false;
956 undetectable_short_ascii_string_map_ = Map::cast(obj);
957 undetectable_short_ascii_string_map_->set_is_undetectable();
958
ager@chromium.org7c537e22008-10-16 08:43:32 +0000959 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000960 if (obj->IsFailure()) return false;
961 undetectable_medium_ascii_string_map_ = Map::cast(obj);
962 undetectable_medium_ascii_string_map_->set_is_undetectable();
963
ager@chromium.org7c537e22008-10-16 08:43:32 +0000964 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000965 if (obj->IsFailure()) return false;
966 undetectable_long_ascii_string_map_ = Map::cast(obj);
967 undetectable_long_ascii_string_map_->set_is_undetectable();
968
969 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
970 if (obj->IsFailure()) return false;
971 byte_array_map_ = Map::cast(obj);
972
973 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
974 if (obj->IsFailure()) return false;
975 code_map_ = Map::cast(obj);
976
977 obj = AllocateMap(FILLER_TYPE, kPointerSize);
978 if (obj->IsFailure()) return false;
979 one_word_filler_map_ = Map::cast(obj);
980
981 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
982 if (obj->IsFailure()) return false;
983 two_word_filler_map_ = Map::cast(obj);
984
985#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
986 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
987 if (obj->IsFailure()) return false; \
988 name##_map_ = Map::cast(obj);
989 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
990#undef ALLOCATE_STRUCT_MAP
991
ager@chromium.org236ad962008-09-25 09:45:57 +0000992 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000993 if (obj->IsFailure()) return false;
994 hash_table_map_ = Map::cast(obj);
995
ager@chromium.org236ad962008-09-25 09:45:57 +0000996 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000997 if (obj->IsFailure()) return false;
998 context_map_ = Map::cast(obj);
999
ager@chromium.org236ad962008-09-25 09:45:57 +00001000 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001001 if (obj->IsFailure()) return false;
1002 global_context_map_ = Map::cast(obj);
1003
1004 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1005 if (obj->IsFailure()) return false;
1006 boilerplate_function_map_ = Map::cast(obj);
1007
1008 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1009 if (obj->IsFailure()) return false;
1010 shared_function_info_map_ = Map::cast(obj);
1011
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001012 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 return true;
1014}
1015
1016
1017Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1018 // Statically ensure that it is safe to allocate heap numbers in paged
1019 // spaces.
1020 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001021 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 Object* result = AllocateRaw(HeapNumber::kSize, space);
1023 if (result->IsFailure()) return result;
1024
1025 HeapObject::cast(result)->set_map(heap_number_map());
1026 HeapNumber::cast(result)->set_value(value);
1027 return result;
1028}
1029
1030
1031Object* Heap::AllocateHeapNumber(double value) {
1032 // This version of AllocateHeapNumber is optimized for
1033 // allocation in new space.
1034 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1035 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001036 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001037 if (result->IsFailure()) return result;
1038 HeapObject::cast(result)->set_map(heap_number_map());
1039 HeapNumber::cast(result)->set_value(value);
1040 return result;
1041}
1042
1043
1044Object* Heap::CreateOddball(Map* map,
1045 const char* to_string,
1046 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001047 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001048 if (result->IsFailure()) return result;
1049 return Oddball::cast(result)->Initialize(to_string, to_number);
1050}
1051
1052
1053bool Heap::CreateApiObjects() {
1054 Object* obj;
1055
1056 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1057 if (obj->IsFailure()) return false;
1058 neander_map_ = Map::cast(obj);
1059
1060 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1061 if (obj->IsFailure()) return false;
1062 Object* elements = AllocateFixedArray(2);
1063 if (elements->IsFailure()) return false;
1064 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1065 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1066 message_listeners_ = JSObject::cast(obj);
1067
1068 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1069 if (obj->IsFailure()) return false;
1070 elements = AllocateFixedArray(2);
1071 if (elements->IsFailure()) return false;
1072 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1073 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1074 debug_event_listeners_ = JSObject::cast(obj);
1075
1076 return true;
1077}
1078
1079void Heap::CreateFixedStubs() {
1080 // Here we create roots for fixed stubs. They are needed at GC
1081 // for cooking and uncooking (check out frames.cc).
1082 // The eliminates the need for doing dictionary lookup in the
1083 // stub cache for these stubs.
1084 HandleScope scope;
1085 {
1086 CEntryStub stub;
1087 c_entry_code_ = *stub.GetCode();
1088 }
1089 {
1090 CEntryDebugBreakStub stub;
1091 c_entry_debug_break_code_ = *stub.GetCode();
1092 }
1093 {
1094 JSEntryStub stub;
1095 js_entry_code_ = *stub.GetCode();
1096 }
1097 {
1098 JSConstructEntryStub stub;
1099 js_construct_entry_code_ = *stub.GetCode();
1100 }
1101}
1102
1103
1104bool Heap::CreateInitialObjects() {
1105 Object* obj;
1106
1107 // The -0 value must be set before NumberFromDouble works.
1108 obj = AllocateHeapNumber(-0.0, TENURED);
1109 if (obj->IsFailure()) return false;
1110 minus_zero_value_ = obj;
1111 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1112
1113 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1114 if (obj->IsFailure()) return false;
1115 nan_value_ = obj;
1116
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001117 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001118 if (obj->IsFailure()) return false;
1119 undefined_value_ = obj;
1120 ASSERT(!InNewSpace(undefined_value()));
1121
1122 // Allocate initial symbol table.
1123 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1124 if (obj->IsFailure()) return false;
1125 symbol_table_ = obj;
1126
1127 // Assign the print strings for oddballs after creating symboltable.
1128 Object* symbol = LookupAsciiSymbol("undefined");
1129 if (symbol->IsFailure()) return false;
1130 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1131 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1132
1133 // Assign the print strings for oddballs after creating symboltable.
1134 symbol = LookupAsciiSymbol("null");
1135 if (symbol->IsFailure()) return false;
1136 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1137 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1138
1139 // Allocate the null_value
1140 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1141 if (obj->IsFailure()) return false;
1142
1143 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1144 if (obj->IsFailure()) return false;
1145 true_value_ = obj;
1146
1147 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1148 if (obj->IsFailure()) return false;
1149 false_value_ = obj;
1150
1151 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1152 if (obj->IsFailure()) return false;
1153 the_hole_value_ = obj;
1154
1155 // Allocate the empty string.
1156 obj = AllocateRawAsciiString(0, TENURED);
1157 if (obj->IsFailure()) return false;
1158 empty_string_ = String::cast(obj);
1159
1160#define SYMBOL_INITIALIZE(name, string) \
1161 obj = LookupAsciiSymbol(string); \
1162 if (obj->IsFailure()) return false; \
1163 (name##_) = String::cast(obj);
1164 SYMBOL_LIST(SYMBOL_INITIALIZE)
1165#undef SYMBOL_INITIALIZE
1166
1167 // Allocate the proxy for __proto__.
1168 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1169 if (obj->IsFailure()) return false;
1170 prototype_accessors_ = Proxy::cast(obj);
1171
1172 // Allocate the code_stubs dictionary.
1173 obj = Dictionary::Allocate(4);
1174 if (obj->IsFailure()) return false;
1175 code_stubs_ = Dictionary::cast(obj);
1176
1177 // Allocate the non_monomorphic_cache used in stub-cache.cc
1178 obj = Dictionary::Allocate(4);
1179 if (obj->IsFailure()) return false;
1180 non_monomorphic_cache_ = Dictionary::cast(obj);
1181
1182 CreateFixedStubs();
1183
1184 // Allocate the number->string conversion cache
1185 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1186 if (obj->IsFailure()) return false;
1187 number_string_cache_ = FixedArray::cast(obj);
1188
1189 // Allocate cache for single character strings.
1190 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1191 if (obj->IsFailure()) return false;
1192 single_character_string_cache_ = FixedArray::cast(obj);
1193
1194 // Allocate cache for external strings pointing to native source code.
1195 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1196 if (obj->IsFailure()) return false;
1197 natives_source_cache_ = FixedArray::cast(obj);
1198
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001199 // Initialize keyed lookup cache.
1200 ClearKeyedLookupCache();
1201
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001202 // Initialize compilation cache.
1203 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001204
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001205 return true;
1206}
1207
1208
1209static inline int double_get_hash(double d) {
1210 DoubleRepresentation rep(d);
1211 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1212 (Heap::kNumberStringCacheSize - 1));
1213}
1214
1215
1216static inline int smi_get_hash(Smi* smi) {
1217 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1218}
1219
1220
1221
1222Object* Heap::GetNumberStringCache(Object* number) {
1223 int hash;
1224 if (number->IsSmi()) {
1225 hash = smi_get_hash(Smi::cast(number));
1226 } else {
1227 hash = double_get_hash(number->Number());
1228 }
1229 Object* key = number_string_cache_->get(hash * 2);
1230 if (key == number) {
1231 return String::cast(number_string_cache_->get(hash * 2 + 1));
1232 } else if (key->IsHeapNumber() &&
1233 number->IsHeapNumber() &&
1234 key->Number() == number->Number()) {
1235 return String::cast(number_string_cache_->get(hash * 2 + 1));
1236 }
1237 return undefined_value();
1238}
1239
1240
1241void Heap::SetNumberStringCache(Object* number, String* string) {
1242 int hash;
1243 if (number->IsSmi()) {
1244 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001245 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001246 } else {
1247 hash = double_get_hash(number->Number());
1248 number_string_cache_->set(hash * 2, number);
1249 }
1250 number_string_cache_->set(hash * 2 + 1, string);
1251}
1252
1253
1254Object* Heap::SmiOrNumberFromDouble(double value,
1255 bool new_object,
1256 PretenureFlag pretenure) {
1257 // We need to distinguish the minus zero value and this cannot be
1258 // done after conversion to int. Doing this by comparing bit
1259 // patterns is faster than using fpclassify() et al.
1260 static const DoubleRepresentation plus_zero(0.0);
1261 static const DoubleRepresentation minus_zero(-0.0);
1262 static const DoubleRepresentation nan(OS::nan_value());
1263 ASSERT(minus_zero_value_ != NULL);
1264 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1265
1266 DoubleRepresentation rep(value);
1267 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1268 if (rep.bits == minus_zero.bits) {
1269 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1270 : minus_zero_value_;
1271 }
1272 if (rep.bits == nan.bits) {
1273 return new_object
1274 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1275 : nan_value_;
1276 }
1277
1278 // Try to represent the value as a tagged small integer.
1279 int int_value = FastD2I(value);
1280 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1281 return Smi::FromInt(int_value);
1282 }
1283
1284 // Materialize the value in the heap.
1285 return AllocateHeapNumber(value, pretenure);
1286}
1287
1288
1289Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1290 return SmiOrNumberFromDouble(value,
1291 true /* number object must be new */,
1292 pretenure);
1293}
1294
1295
1296Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1297 return SmiOrNumberFromDouble(value,
1298 false /* use preallocated NaN, -0.0 */,
1299 pretenure);
1300}
1301
1302
1303Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1304 // Statically ensure that it is safe to allocate proxies in paged spaces.
1305 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001306 AllocationSpace space =
1307 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001308 Object* result = Allocate(proxy_map(), space);
1309 if (result->IsFailure()) return result;
1310
1311 Proxy::cast(result)->set_proxy(proxy);
1312 return result;
1313}
1314
1315
1316Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1317 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1318 if (result->IsFailure()) return result;
1319
1320 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1321 share->set_name(name);
1322 Code* illegal = Builtins::builtin(Builtins::Illegal);
1323 share->set_code(illegal);
1324 share->set_expected_nof_properties(0);
1325 share->set_length(0);
1326 share->set_formal_parameter_count(0);
1327 share->set_instance_class_name(Object_symbol());
1328 share->set_function_data(undefined_value());
1329 share->set_lazy_load_data(undefined_value());
1330 share->set_script(undefined_value());
1331 share->set_start_position_and_type(0);
1332 share->set_debug_info(undefined_value());
1333 return result;
1334}
1335
1336
1337Object* Heap::AllocateConsString(String* first, String* second) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001338 int first_length = first->length();
1339 int second_length = second->length();
1340 int length = first_length + second_length;
ager@chromium.org7c537e22008-10-16 08:43:32 +00001341 bool is_ascii = first->is_ascii_representation()
1342 && second->is_ascii_representation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001343
1344 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001345 if (length < String::kMinNonFlatLength) {
1346 ASSERT(first->IsFlat());
1347 ASSERT(second->IsFlat());
1348 if (is_ascii) {
1349 Object* result = AllocateRawAsciiString(length);
1350 if (result->IsFailure()) return result;
1351 // Copy the characters into the new object.
1352 char* dest = SeqAsciiString::cast(result)->GetChars();
1353 String::WriteToFlat(first, dest, 0, first_length);
1354 String::WriteToFlat(second, dest + first_length, 0, second_length);
1355 return result;
1356 } else {
1357 Object* result = AllocateRawTwoByteString(length);
1358 if (result->IsFailure()) return result;
1359 // Copy the characters into the new object.
1360 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1361 String::WriteToFlat(first, dest, 0, first_length);
1362 String::WriteToFlat(second, dest + first_length, 0, second_length);
1363 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001364 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001365 }
1366
1367 Map* map;
1368 if (length <= String::kMaxShortStringSize) {
1369 map = is_ascii ? short_cons_ascii_string_map()
1370 : short_cons_string_map();
1371 } else if (length <= String::kMaxMediumStringSize) {
1372 map = is_ascii ? medium_cons_ascii_string_map()
1373 : medium_cons_string_map();
1374 } else {
1375 map = is_ascii ? long_cons_ascii_string_map()
1376 : long_cons_string_map();
1377 }
1378
1379 Object* result = Allocate(map, NEW_SPACE);
1380 if (result->IsFailure()) return result;
1381
1382 ConsString* cons_string = ConsString::cast(result);
1383 cons_string->set_first(first);
1384 cons_string->set_second(second);
1385 cons_string->set_length(length);
1386
1387 return result;
1388}
1389
1390
1391Object* Heap::AllocateSlicedString(String* buffer, int start, int end) {
1392 int length = end - start;
1393
1394 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001395 if (end - start <= String::kMinNonFlatLength) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396 return Heap::AllocateSubString(buffer, start, end);
1397 }
1398
1399 Map* map;
1400 if (length <= String::kMaxShortStringSize) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001401 map = buffer->is_ascii_representation() ? short_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001402 : short_sliced_string_map();
1403 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001404 map = buffer->is_ascii_representation() ? medium_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405 : medium_sliced_string_map();
1406 } else {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001407 map = buffer->is_ascii_representation() ? long_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001408 : long_sliced_string_map();
1409 }
1410
1411 Object* result = Allocate(map, NEW_SPACE);
1412 if (result->IsFailure()) return result;
1413
1414 SlicedString* sliced_string = SlicedString::cast(result);
1415 sliced_string->set_buffer(buffer);
1416 sliced_string->set_start(start);
1417 sliced_string->set_length(length);
1418
1419 return result;
1420}
1421
1422
1423Object* Heap::AllocateSubString(String* buffer, int start, int end) {
1424 int length = end - start;
1425
ager@chromium.org7c537e22008-10-16 08:43:32 +00001426 if (length == 1) {
1427 return Heap::LookupSingleCharacterStringFromCode(buffer->Get(start));
1428 }
1429
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001430 // Make an attempt to flatten the buffer to reduce access time.
1431 buffer->TryFlatten();
1432
ager@chromium.org7c537e22008-10-16 08:43:32 +00001433 Object* result = buffer->is_ascii_representation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001434 ? AllocateRawAsciiString(length)
1435 : AllocateRawTwoByteString(length);
1436 if (result->IsFailure()) return result;
1437
1438 // Copy the characters into the new object.
1439 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001440 StringHasher hasher(length);
1441 int i = 0;
1442 for (; i < length && hasher.is_array_index(); i++) {
1443 uc32 c = buffer->Get(start + i);
1444 hasher.AddCharacter(c);
1445 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001446 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001447 for (; i < length; i++) {
1448 uc32 c = buffer->Get(start + i);
1449 hasher.AddCharacterNoIndex(c);
1450 string_result->Set(i, c);
1451 }
1452 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001453 return result;
1454}
1455
1456
1457Object* Heap::AllocateExternalStringFromAscii(
1458 ExternalAsciiString::Resource* resource) {
1459 Map* map;
1460 int length = resource->length();
1461 if (length <= String::kMaxShortStringSize) {
1462 map = short_external_ascii_string_map();
1463 } else if (length <= String::kMaxMediumStringSize) {
1464 map = medium_external_ascii_string_map();
1465 } else {
1466 map = long_external_ascii_string_map();
1467 }
1468
1469 Object* result = Allocate(map, NEW_SPACE);
1470 if (result->IsFailure()) return result;
1471
1472 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1473 external_string->set_length(length);
1474 external_string->set_resource(resource);
1475
1476 return result;
1477}
1478
1479
1480Object* Heap::AllocateExternalStringFromTwoByte(
1481 ExternalTwoByteString::Resource* resource) {
1482 Map* map;
1483 int length = resource->length();
1484 if (length <= String::kMaxShortStringSize) {
1485 map = short_external_string_map();
1486 } else if (length <= String::kMaxMediumStringSize) {
1487 map = medium_external_string_map();
1488 } else {
1489 map = long_external_string_map();
1490 }
1491
1492 Object* result = Allocate(map, NEW_SPACE);
1493 if (result->IsFailure()) return result;
1494
1495 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1496 external_string->set_length(length);
1497 external_string->set_resource(resource);
1498
1499 return result;
1500}
1501
1502
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001503Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001504 if (code <= String::kMaxAsciiCharCode) {
1505 Object* value = Heap::single_character_string_cache()->get(code);
1506 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001507
1508 char buffer[1];
1509 buffer[0] = static_cast<char>(code);
1510 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1511
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001512 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001513 Heap::single_character_string_cache()->set(code, result);
1514 return result;
1515 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001516
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001517 Object* result = Heap::AllocateRawTwoByteString(1);
1518 if (result->IsFailure()) return result;
1519 String::cast(result)->Set(0, code);
1520 return result;
1521}
1522
1523
1524Object* Heap::AllocateByteArray(int length) {
1525 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001526 AllocationSpace space =
1527 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001528
1529 Object* result = AllocateRaw(size, space);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001530
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001531 if (result->IsFailure()) return result;
1532
1533 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1534 reinterpret_cast<Array*>(result)->set_length(length);
1535 return result;
1536}
1537
1538
1539Object* Heap::CreateCode(const CodeDesc& desc,
1540 ScopeInfo<>* sinfo,
1541 Code::Flags flags) {
1542 // Compute size
1543 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1544 int sinfo_size = 0;
1545 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1546 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001547 Object* result;
1548 if (obj_size > MaxHeapObjectSize()) {
1549 result = lo_space_->AllocateRawCode(obj_size);
1550 } else {
1551 result = code_space_->AllocateRaw(obj_size);
1552 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554 if (result->IsFailure()) return result;
1555
1556 // Initialize the object
1557 HeapObject::cast(result)->set_map(code_map());
1558 Code* code = Code::cast(result);
1559 code->set_instruction_size(desc.instr_size);
1560 code->set_relocation_size(desc.reloc_size);
1561 code->set_sinfo_size(sinfo_size);
1562 code->set_flags(flags);
1563 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
1564 code->CopyFrom(desc); // migrate generated code
1565 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1566
1567#ifdef DEBUG
1568 code->Verify();
1569#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570 return code;
1571}
1572
1573
1574Object* Heap::CopyCode(Code* code) {
1575 // Allocate an object the same size as the code object.
1576 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001577 Object* result;
1578 if (obj_size > MaxHeapObjectSize()) {
1579 result = lo_space_->AllocateRawCode(obj_size);
1580 } else {
1581 result = code_space_->AllocateRaw(obj_size);
1582 }
1583
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 if (result->IsFailure()) return result;
1585
1586 // Copy code object.
1587 Address old_addr = code->address();
1588 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001589 CopyBlock(reinterpret_cast<Object**>(new_addr),
1590 reinterpret_cast<Object**>(old_addr),
1591 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001592 // Relocate the copy.
1593 Code* new_code = Code::cast(result);
1594 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001595 return new_code;
1596}
1597
1598
1599Object* Heap::Allocate(Map* map, AllocationSpace space) {
1600 ASSERT(gc_state_ == NOT_IN_GC);
1601 ASSERT(map->instance_type() != MAP_TYPE);
1602 Object* result = AllocateRaw(map->instance_size(), space);
1603 if (result->IsFailure()) return result;
1604 HeapObject::cast(result)->set_map(map);
1605 return result;
1606}
1607
1608
1609Object* Heap::InitializeFunction(JSFunction* function,
1610 SharedFunctionInfo* shared,
1611 Object* prototype) {
1612 ASSERT(!prototype->IsMap());
1613 function->initialize_properties();
1614 function->initialize_elements();
1615 function->set_shared(shared);
1616 function->set_prototype_or_initial_map(prototype);
1617 function->set_context(undefined_value());
1618 function->set_literals(empty_fixed_array());
1619 return function;
1620}
1621
1622
1623Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1624 // Allocate the prototype.
1625 Object* prototype =
1626 AllocateJSObject(Top::context()->global_context()->object_function());
1627 if (prototype->IsFailure()) return prototype;
1628 // When creating the prototype for the function we must set its
1629 // constructor to the function.
1630 Object* result =
1631 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1632 function,
1633 DONT_ENUM);
1634 if (result->IsFailure()) return result;
1635 return prototype;
1636}
1637
1638
1639Object* Heap::AllocateFunction(Map* function_map,
1640 SharedFunctionInfo* shared,
1641 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001642 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643 if (result->IsFailure()) return result;
1644 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1645}
1646
1647
1648Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001649 // To get fast allocation and map sharing for arguments objects we
1650 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001651
1652 // This calls Copy directly rather than using Heap::AllocateRaw so we
1653 // duplicate the check here.
1654 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1655
1656 JSObject* boilerplate =
1657 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001658
1659 // Make the clone.
1660 Map* map = boilerplate->map();
1661 int object_size = map->instance_size();
1662 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001663 if (result->IsFailure()) return result;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001664 ASSERT(Heap::InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001666 // Copy the content.
1667 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1668 reinterpret_cast<Object**>(boilerplate->address()),
1669 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001670
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001671 // Set the two properties.
1672 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
1673 callee,
1674 SKIP_WRITE_BARRIER);
1675 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1676 Smi::FromInt(length),
1677 SKIP_WRITE_BARRIER);
1678
1679 // Allocate the elements if needed.
1680 if (length > 0) {
1681 // Allocate the fixed array.
1682 Object* obj = Heap::AllocateFixedArray(length);
1683 if (obj->IsFailure()) return obj;
1684 JSObject::cast(result)->set_elements(FixedArray::cast(obj));
1685 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001686
1687 // Check the state of the object
1688 ASSERT(JSObject::cast(result)->HasFastProperties());
1689 ASSERT(JSObject::cast(result)->HasFastElements());
1690
1691 return result;
1692}
1693
1694
1695Object* Heap::AllocateInitialMap(JSFunction* fun) {
1696 ASSERT(!fun->has_initial_map());
1697
ager@chromium.org7c537e22008-10-16 08:43:32 +00001698 // First create a new map with the expected number of properties being
1699 // allocated in-object.
1700 int expected_nof_properties = fun->shared()->expected_nof_properties();
1701 int instance_size = JSObject::kHeaderSize +
1702 expected_nof_properties * kPointerSize;
1703 if (instance_size > JSObject::kMaxInstanceSize) {
1704 instance_size = JSObject::kMaxInstanceSize;
1705 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1706 kPointerSize;
1707 }
1708 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001709 if (map_obj->IsFailure()) return map_obj;
1710
1711 // Fetch or allocate prototype.
1712 Object* prototype;
1713 if (fun->has_instance_prototype()) {
1714 prototype = fun->instance_prototype();
1715 } else {
1716 prototype = AllocateFunctionPrototype(fun);
1717 if (prototype->IsFailure()) return prototype;
1718 }
1719 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001720 map->set_inobject_properties(expected_nof_properties);
1721 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 map->set_prototype(prototype);
1723 return map;
1724}
1725
1726
1727void Heap::InitializeJSObjectFromMap(JSObject* obj,
1728 FixedArray* properties,
1729 Map* map) {
1730 obj->set_properties(properties);
1731 obj->initialize_elements();
1732 // TODO(1240798): Initialize the object's body using valid initial values
1733 // according to the object's initial map. For example, if the map's
1734 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1735 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1736 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1737 // verification code has to cope with (temporarily) invalid objects. See
1738 // for example, JSArray::JSArrayVerify).
1739 obj->InitializeBody(map->instance_size());
1740}
1741
1742
1743Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1744 // JSFunctions should be allocated using AllocateFunction to be
1745 // properly initialized.
1746 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1747
1748 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001749 int prop_size = map->unused_property_fields() - map->inobject_properties();
1750 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001751 if (properties->IsFailure()) return properties;
1752
1753 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001754 AllocationSpace space =
1755 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001756 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1757 Object* obj = Allocate(map, space);
1758 if (obj->IsFailure()) return obj;
1759
1760 // Initialize the JSObject.
1761 InitializeJSObjectFromMap(JSObject::cast(obj),
1762 FixedArray::cast(properties),
1763 map);
1764 return obj;
1765}
1766
1767
1768Object* Heap::AllocateJSObject(JSFunction* constructor,
1769 PretenureFlag pretenure) {
1770 // Allocate the initial map if absent.
1771 if (!constructor->has_initial_map()) {
1772 Object* initial_map = AllocateInitialMap(constructor);
1773 if (initial_map->IsFailure()) return initial_map;
1774 constructor->set_initial_map(Map::cast(initial_map));
1775 Map::cast(initial_map)->set_constructor(constructor);
1776 }
1777 // Allocate the object based on the constructors initial map.
1778 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1779}
1780
1781
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001782Object* Heap::CopyJSObject(JSObject* source) {
1783 // Never used to copy functions. If functions need to be copied we
1784 // have to be careful to clear the literals array.
1785 ASSERT(!source->IsJSFunction());
1786
1787 // Make the clone.
1788 Map* map = source->map();
1789 int object_size = map->instance_size();
1790 Object* clone = new_space_.AllocateRaw(object_size);
1791 if (clone->IsFailure()) return clone;
1792 ASSERT(Heap::InNewSpace(clone));
1793
1794 // Copy the content.
1795 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1796 reinterpret_cast<Object**>(source->address()),
1797 object_size);
1798
1799 FixedArray* elements = FixedArray::cast(source->elements());
1800 FixedArray* properties = FixedArray::cast(source->properties());
1801 // Update elements if necessary.
1802 if (elements->length()> 0) {
1803 Object* elem = CopyFixedArray(elements);
1804 if (elem->IsFailure()) return elem;
1805 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1806 }
1807 // Update properties if necessary.
1808 if (properties->length() > 0) {
1809 Object* prop = CopyFixedArray(properties);
1810 if (prop->IsFailure()) return prop;
1811 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1812 }
1813 // Return the new clone.
1814 return clone;
1815}
1816
1817
1818Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1819 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001820 // Allocate initial map if absent.
1821 if (!constructor->has_initial_map()) {
1822 Object* initial_map = AllocateInitialMap(constructor);
1823 if (initial_map->IsFailure()) return initial_map;
1824 constructor->set_initial_map(Map::cast(initial_map));
1825 Map::cast(initial_map)->set_constructor(constructor);
1826 }
1827
1828 Map* map = constructor->initial_map();
1829
1830 // Check that the already allocated object has the same size as
1831 // objects allocated using the constructor.
1832 ASSERT(map->instance_size() == object->map()->instance_size());
1833
1834 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001835 int prop_size = map->unused_property_fields() - map->inobject_properties();
1836 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001837 if (properties->IsFailure()) return properties;
1838
1839 // Reset the map for the object.
1840 object->set_map(constructor->initial_map());
1841
1842 // Reinitialize the object from the constructor map.
1843 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1844 return object;
1845}
1846
1847
1848Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1849 PretenureFlag pretenure) {
1850 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1851 if (result->IsFailure()) return result;
1852
1853 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001854 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001855 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001856 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001857 }
1858 return result;
1859}
1860
1861
1862Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1863 PretenureFlag pretenure) {
1864 // Count the number of characters in the UTF-8 string and check if
1865 // it is an ASCII string.
1866 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1867 decoder->Reset(string.start(), string.length());
1868 int chars = 0;
1869 bool is_ascii = true;
1870 while (decoder->has_more()) {
1871 uc32 r = decoder->GetNext();
1872 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1873 chars++;
1874 }
1875
1876 // If the string is ascii, we do not need to convert the characters
1877 // since UTF8 is backwards compatible with ascii.
1878 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1879
1880 Object* result = AllocateRawTwoByteString(chars, pretenure);
1881 if (result->IsFailure()) return result;
1882
1883 // Convert and copy the characters into the new object.
1884 String* string_result = String::cast(result);
1885 decoder->Reset(string.start(), string.length());
1886 for (int i = 0; i < chars; i++) {
1887 uc32 r = decoder->GetNext();
1888 string_result->Set(i, r);
1889 }
1890 return result;
1891}
1892
1893
1894Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1895 PretenureFlag pretenure) {
1896 // Check if the string is an ASCII string.
1897 int i = 0;
1898 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1899
1900 Object* result;
1901 if (i == string.length()) { // It's an ASCII string.
1902 result = AllocateRawAsciiString(string.length(), pretenure);
1903 } else { // It's not an ASCII string.
1904 result = AllocateRawTwoByteString(string.length(), pretenure);
1905 }
1906 if (result->IsFailure()) return result;
1907
1908 // Copy the characters into the new object, which may be either ASCII or
1909 // UTF-16.
1910 String* string_result = String::cast(result);
1911 for (int i = 0; i < string.length(); i++) {
1912 string_result->Set(i, string[i]);
1913 }
1914 return result;
1915}
1916
1917
1918Map* Heap::SymbolMapForString(String* string) {
1919 // If the string is in new space it cannot be used as a symbol.
1920 if (InNewSpace(string)) return NULL;
1921
1922 // Find the corresponding symbol map for strings.
1923 Map* map = string->map();
1924
1925 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
1926 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
1927 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
1928
1929 if (map == short_string_map()) return short_symbol_map();
1930 if (map == medium_string_map()) return medium_symbol_map();
1931 if (map == long_string_map()) return long_symbol_map();
1932
1933 if (map == short_cons_string_map()) return short_cons_symbol_map();
1934 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
1935 if (map == long_cons_string_map()) return long_cons_symbol_map();
1936
1937 if (map == short_cons_ascii_string_map()) {
1938 return short_cons_ascii_symbol_map();
1939 }
1940 if (map == medium_cons_ascii_string_map()) {
1941 return medium_cons_ascii_symbol_map();
1942 }
1943 if (map == long_cons_ascii_string_map()) {
1944 return long_cons_ascii_symbol_map();
1945 }
1946
1947 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
1948 if (map == medium_sliced_string_map()) return short_sliced_symbol_map();
1949 if (map == long_sliced_string_map()) return short_sliced_symbol_map();
1950
1951 if (map == short_sliced_ascii_string_map()) {
1952 return short_sliced_ascii_symbol_map();
1953 }
1954 if (map == medium_sliced_ascii_string_map()) {
1955 return short_sliced_ascii_symbol_map();
1956 }
1957 if (map == long_sliced_ascii_string_map()) {
1958 return short_sliced_ascii_symbol_map();
1959 }
1960
1961 if (map == short_external_string_map()) return short_external_string_map();
1962 if (map == medium_external_string_map()) return medium_external_string_map();
1963 if (map == long_external_string_map()) return long_external_string_map();
1964
1965 if (map == short_external_ascii_string_map()) {
1966 return short_external_ascii_string_map();
1967 }
1968 if (map == medium_external_ascii_string_map()) {
1969 return medium_external_ascii_string_map();
1970 }
1971 if (map == long_external_ascii_string_map()) {
1972 return long_external_ascii_string_map();
1973 }
1974
1975 // No match found.
1976 return NULL;
1977}
1978
1979
1980Object* Heap::AllocateSymbol(unibrow::CharacterStream* buffer,
1981 int chars,
ager@chromium.org7c537e22008-10-16 08:43:32 +00001982 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001983 // Ensure the chars matches the number of characters in the buffer.
1984 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
1985 // Determine whether the string is ascii.
1986 bool is_ascii = true;
1987 while (buffer->has_more()) {
1988 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
1989 }
1990 buffer->Rewind();
1991
1992 // Compute map and object size.
1993 int size;
1994 Map* map;
1995
1996 if (is_ascii) {
1997 if (chars <= String::kMaxShortStringSize) {
1998 map = short_ascii_symbol_map();
1999 } else if (chars <= String::kMaxMediumStringSize) {
2000 map = medium_ascii_symbol_map();
2001 } else {
2002 map = long_ascii_symbol_map();
2003 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002004 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002005 } else {
2006 if (chars <= String::kMaxShortStringSize) {
2007 map = short_symbol_map();
2008 } else if (chars <= String::kMaxMediumStringSize) {
2009 map = medium_symbol_map();
2010 } else {
2011 map = long_symbol_map();
2012 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002013 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002014 }
2015
2016 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002017 AllocationSpace space =
2018 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002019 Object* result = AllocateRaw(size, space);
2020 if (result->IsFailure()) return result;
2021
2022 reinterpret_cast<HeapObject*>(result)->set_map(map);
2023 // The hash value contains the length of the string.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002024 String::cast(result)->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002025
2026 ASSERT_EQ(size, String::cast(result)->Size());
2027
2028 // Fill in the characters.
2029 for (int i = 0; i < chars; i++) {
2030 String::cast(result)->Set(i, buffer->GetNext());
2031 }
2032 return result;
2033}
2034
2035
2036Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002037 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002038 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002039 if (size > MaxHeapObjectSize()) {
2040 space = LO_SPACE;
2041 }
2042
2043 // Use AllocateRaw rather than Allocate because the object's size cannot be
2044 // determined from the map.
2045 Object* result = AllocateRaw(size, space);
2046 if (result->IsFailure()) return result;
2047
2048 // Determine the map based on the string's length.
2049 Map* map;
2050 if (length <= String::kMaxShortStringSize) {
2051 map = short_ascii_string_map();
2052 } else if (length <= String::kMaxMediumStringSize) {
2053 map = medium_ascii_string_map();
2054 } else {
2055 map = long_ascii_string_map();
2056 }
2057
2058 // Partially initialize the object.
2059 HeapObject::cast(result)->set_map(map);
2060 String::cast(result)->set_length(length);
2061 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2062 return result;
2063}
2064
2065
2066Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002067 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002068 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002069 if (size > MaxHeapObjectSize()) {
2070 space = LO_SPACE;
2071 }
2072
2073 // Use AllocateRaw rather than Allocate because the object's size cannot be
2074 // determined from the map.
2075 Object* result = AllocateRaw(size, space);
2076 if (result->IsFailure()) return result;
2077
2078 // Determine the map based on the string's length.
2079 Map* map;
2080 if (length <= String::kMaxShortStringSize) {
2081 map = short_string_map();
2082 } else if (length <= String::kMaxMediumStringSize) {
2083 map = medium_string_map();
2084 } else {
2085 map = long_string_map();
2086 }
2087
2088 // Partially initialize the object.
2089 HeapObject::cast(result)->set_map(map);
2090 String::cast(result)->set_length(length);
2091 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2092 return result;
2093}
2094
2095
2096Object* Heap::AllocateEmptyFixedArray() {
2097 int size = FixedArray::SizeFor(0);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002098 Object* result = AllocateRaw(size, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002099 if (result->IsFailure()) return result;
2100 // Initialize the object.
2101 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2102 reinterpret_cast<Array*>(result)->set_length(0);
2103 return result;
2104}
2105
2106
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002107Object* Heap::AllocateRawFixedArray(int length) {
2108 // Allocate the raw data for a fixed array.
2109 int size = FixedArray::SizeFor(length);
2110 return (size > MaxHeapObjectSize())
2111 ? lo_space_->AllocateRawFixedArray(size)
2112 : new_space_.AllocateRaw(size);
2113}
2114
2115
2116Object* Heap::CopyFixedArray(FixedArray* src) {
2117 int len = src->length();
2118 Object* obj = AllocateRawFixedArray(len);
2119 if (obj->IsFailure()) return obj;
2120 if (Heap::InNewSpace(obj)) {
2121 HeapObject* dst = HeapObject::cast(obj);
2122 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2123 reinterpret_cast<Object**>(src->address()),
2124 FixedArray::SizeFor(len));
2125 return obj;
2126 }
2127 HeapObject::cast(obj)->set_map(src->map());
2128 FixedArray* result = FixedArray::cast(obj);
2129 result->set_length(len);
2130 // Copy the content
2131 WriteBarrierMode mode = result->GetWriteBarrierMode();
2132 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2133 return result;
2134}
2135
2136
2137Object* Heap::AllocateFixedArray(int length) {
2138 Object* result = AllocateRawFixedArray(length);
2139 if (!result->IsFailure()) {
2140 // Initialize header.
2141 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2142 FixedArray* array = FixedArray::cast(result);
2143 array->set_length(length);
2144 Object* value = undefined_value();
2145 // Initialize body.
2146 for (int index = 0; index < length; index++) {
2147 array->set(index, value, SKIP_WRITE_BARRIER);
2148 }
2149 }
2150 return result;
2151}
2152
2153
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002154Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2155 ASSERT(empty_fixed_array()->IsFixedArray());
2156 if (length == 0) return empty_fixed_array();
2157
2158 int size = FixedArray::SizeFor(length);
2159 Object* result;
2160 if (size > MaxHeapObjectSize()) {
2161 result = lo_space_->AllocateRawFixedArray(size);
2162 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002163 AllocationSpace space =
2164 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002165 result = AllocateRaw(size, space);
2166 }
2167 if (result->IsFailure()) return result;
2168
2169 // Initialize the object.
2170 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2171 FixedArray* array = FixedArray::cast(result);
2172 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002173 Object* value = undefined_value();
2174 for (int index = 0; index < length; index++) {
2175 array->set(index, value, SKIP_WRITE_BARRIER);
2176 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002177 return array;
2178}
2179
2180
2181Object* Heap::AllocateFixedArrayWithHoles(int length) {
2182 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002183 Object* result = AllocateRawFixedArray(length);
2184 if (!result->IsFailure()) {
2185 // Initialize header.
2186 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2187 FixedArray* array = FixedArray::cast(result);
2188 array->set_length(length);
2189 // Initialize body.
2190 Object* value = the_hole_value();
2191 for (int index = 0; index < length; index++) {
2192 array->set(index, value, SKIP_WRITE_BARRIER);
2193 }
2194 }
2195 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002196}
2197
2198
2199Object* Heap::AllocateHashTable(int length) {
2200 Object* result = Heap::AllocateFixedArray(length);
2201 if (result->IsFailure()) return result;
2202 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2203 ASSERT(result->IsDictionary());
2204 return result;
2205}
2206
2207
2208Object* Heap::AllocateGlobalContext() {
2209 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2210 if (result->IsFailure()) return result;
2211 Context* context = reinterpret_cast<Context*>(result);
2212 context->set_map(global_context_map());
2213 ASSERT(context->IsGlobalContext());
2214 ASSERT(result->IsContext());
2215 return result;
2216}
2217
2218
2219Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2220 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2221 Object* result = Heap::AllocateFixedArray(length);
2222 if (result->IsFailure()) return result;
2223 Context* context = reinterpret_cast<Context*>(result);
2224 context->set_map(context_map());
2225 context->set_closure(function);
2226 context->set_fcontext(context);
2227 context->set_previous(NULL);
2228 context->set_extension(NULL);
2229 context->set_global(function->context()->global());
2230 ASSERT(!context->IsGlobalContext());
2231 ASSERT(context->is_function_context());
2232 ASSERT(result->IsContext());
2233 return result;
2234}
2235
2236
2237Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2238 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2239 if (result->IsFailure()) return result;
2240 Context* context = reinterpret_cast<Context*>(result);
2241 context->set_map(context_map());
2242 context->set_closure(previous->closure());
2243 context->set_fcontext(previous->fcontext());
2244 context->set_previous(previous);
2245 context->set_extension(extension);
2246 context->set_global(previous->global());
2247 ASSERT(!context->IsGlobalContext());
2248 ASSERT(!context->is_function_context());
2249 ASSERT(result->IsContext());
2250 return result;
2251}
2252
2253
2254Object* Heap::AllocateStruct(InstanceType type) {
2255 Map* map;
2256 switch (type) {
2257#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2258STRUCT_LIST(MAKE_CASE)
2259#undef MAKE_CASE
2260 default:
2261 UNREACHABLE();
2262 return Failure::InternalError();
2263 }
2264 int size = map->instance_size();
2265 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002266 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002267 Object* result = Heap::Allocate(map, space);
2268 if (result->IsFailure()) return result;
2269 Struct::cast(result)->InitializeBody(size);
2270 return result;
2271}
2272
2273
2274#ifdef DEBUG
2275
2276void Heap::Print() {
2277 if (!HasBeenSetup()) return;
2278 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002279 AllSpaces spaces;
2280 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002281}
2282
2283
2284void Heap::ReportCodeStatistics(const char* title) {
2285 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2286 PagedSpace::ResetCodeStatistics();
2287 // We do not look for code in new space, map space, or old space. If code
2288 // somehow ends up in those spaces, we would miss it here.
2289 code_space_->CollectCodeStatistics();
2290 lo_space_->CollectCodeStatistics();
2291 PagedSpace::ReportCodeStatistics();
2292}
2293
2294
2295// This function expects that NewSpace's allocated objects histogram is
2296// populated (via a call to CollectStatistics or else as a side effect of a
2297// just-completed scavenge collection).
2298void Heap::ReportHeapStatistics(const char* title) {
2299 USE(title);
2300 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2301 title, gc_count_);
2302 PrintF("mark-compact GC : %d\n", mc_count_);
2303 PrintF("promoted_space_limit_ %d\n", promoted_space_limit_);
2304
2305 PrintF("\n");
2306 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2307 GlobalHandles::PrintStats();
2308 PrintF("\n");
2309
2310 PrintF("Heap statistics : ");
2311 MemoryAllocator::ReportStatistics();
2312 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002313 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002314 PrintF("Old pointer space : ");
2315 old_pointer_space_->ReportStatistics();
2316 PrintF("Old data space : ");
2317 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002318 PrintF("Code space : ");
2319 code_space_->ReportStatistics();
2320 PrintF("Map space : ");
2321 map_space_->ReportStatistics();
2322 PrintF("Large object space : ");
2323 lo_space_->ReportStatistics();
2324 PrintF(">>>>>> ========================================= >>>>>>\n");
2325}
2326
2327#endif // DEBUG
2328
2329bool Heap::Contains(HeapObject* value) {
2330 return Contains(value->address());
2331}
2332
2333
2334bool Heap::Contains(Address addr) {
2335 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2336 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002337 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002338 old_pointer_space_->Contains(addr) ||
2339 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002340 code_space_->Contains(addr) ||
2341 map_space_->Contains(addr) ||
2342 lo_space_->SlowContains(addr));
2343}
2344
2345
2346bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2347 return InSpace(value->address(), space);
2348}
2349
2350
2351bool Heap::InSpace(Address addr, AllocationSpace space) {
2352 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2353 if (!HasBeenSetup()) return false;
2354
2355 switch (space) {
2356 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002357 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002358 case OLD_POINTER_SPACE:
2359 return old_pointer_space_->Contains(addr);
2360 case OLD_DATA_SPACE:
2361 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002362 case CODE_SPACE:
2363 return code_space_->Contains(addr);
2364 case MAP_SPACE:
2365 return map_space_->Contains(addr);
2366 case LO_SPACE:
2367 return lo_space_->SlowContains(addr);
2368 }
2369
2370 return false;
2371}
2372
2373
2374#ifdef DEBUG
2375void Heap::Verify() {
2376 ASSERT(HasBeenSetup());
2377
2378 VerifyPointersVisitor visitor;
2379 Heap::IterateRoots(&visitor);
2380
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002381 AllSpaces spaces;
2382 while (Space* space = spaces.next()) {
2383 space->Verify();
2384 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002385}
2386#endif // DEBUG
2387
2388
2389Object* Heap::LookupSymbol(Vector<const char> string) {
2390 Object* symbol = NULL;
2391 Object* new_table =
2392 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2393 if (new_table->IsFailure()) return new_table;
2394 symbol_table_ = new_table;
2395 ASSERT(symbol != NULL);
2396 return symbol;
2397}
2398
2399
2400Object* Heap::LookupSymbol(String* string) {
2401 if (string->IsSymbol()) return string;
2402 Object* symbol = NULL;
2403 Object* new_table =
2404 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2405 if (new_table->IsFailure()) return new_table;
2406 symbol_table_ = new_table;
2407 ASSERT(symbol != NULL);
2408 return symbol;
2409}
2410
2411
ager@chromium.org7c537e22008-10-16 08:43:32 +00002412bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2413 if (string->IsSymbol()) {
2414 *symbol = string;
2415 return true;
2416 }
2417 SymbolTable* table = SymbolTable::cast(symbol_table_);
2418 return table->LookupSymbolIfExists(string, symbol);
2419}
2420
2421
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002422#ifdef DEBUG
2423void Heap::ZapFromSpace() {
2424 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002425 for (Address a = new_space_.FromSpaceLow();
2426 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002427 a += kPointerSize) {
2428 Memory::Address_at(a) = kFromSpaceZapValue;
2429 }
2430}
2431#endif // DEBUG
2432
2433
2434void Heap::IterateRSetRange(Address object_start,
2435 Address object_end,
2436 Address rset_start,
2437 ObjectSlotCallback copy_object_func) {
2438 Address object_address = object_start;
2439 Address rset_address = rset_start;
2440
2441 // Loop over all the pointers in [object_start, object_end).
2442 while (object_address < object_end) {
2443 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002444 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002445 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002446 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002447 // Do not dereference pointers at or past object_end.
2448 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2449 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002450 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002451 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2452 }
2453 // If this pointer does not need to be remembered anymore, clear
2454 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002455 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002456 }
2457 object_address += kPointerSize;
2458 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002459 // Update the remembered set if it has changed.
2460 if (result_rset != rset_word) {
2461 Memory::uint32_at(rset_address) = result_rset;
2462 }
2463 } else {
2464 // No bits in the word were set. This is the common case.
2465 object_address += kPointerSize * kBitsPerInt;
2466 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002467 rset_address += kIntSize;
2468 }
2469}
2470
2471
2472void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2473 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002474 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002475
2476 PageIterator it(space, PageIterator::PAGES_IN_USE);
2477 while (it.has_next()) {
2478 Page* page = it.next();
2479 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2480 page->RSetStart(), copy_object_func);
2481 }
2482}
2483
2484
2485#ifdef DEBUG
2486#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2487#else
2488#define SYNCHRONIZE_TAG(tag)
2489#endif
2490
2491void Heap::IterateRoots(ObjectVisitor* v) {
2492 IterateStrongRoots(v);
2493 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2494 SYNCHRONIZE_TAG("symbol_table");
2495}
2496
2497
2498void Heap::IterateStrongRoots(ObjectVisitor* v) {
2499#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002500 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002501 STRONG_ROOT_LIST(ROOT_ITERATE);
2502#undef ROOT_ITERATE
2503 SYNCHRONIZE_TAG("strong_root_list");
2504
2505#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002506 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002507 STRUCT_LIST(STRUCT_MAP_ITERATE);
2508#undef STRUCT_MAP_ITERATE
2509 SYNCHRONIZE_TAG("struct_map");
2510
2511#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002512 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002513 SYMBOL_LIST(SYMBOL_ITERATE)
2514#undef SYMBOL_ITERATE
2515 SYNCHRONIZE_TAG("symbol");
2516
2517 Bootstrapper::Iterate(v);
2518 SYNCHRONIZE_TAG("bootstrapper");
2519 Top::Iterate(v);
2520 SYNCHRONIZE_TAG("top");
2521 Debug::Iterate(v);
2522 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002523 CompilationCache::Iterate(v);
2524 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002525
2526 // Iterate over local handles in handle scopes.
2527 HandleScopeImplementer::Iterate(v);
2528 SYNCHRONIZE_TAG("handlescope");
2529
2530 // Iterate over the builtin code objects and code stubs in the heap. Note
2531 // that it is not strictly necessary to iterate over code objects on
2532 // scavenge collections. We still do it here because this same function
2533 // is used by the mark-sweep collector and the deserializer.
2534 Builtins::IterateBuiltins(v);
2535 SYNCHRONIZE_TAG("builtins");
2536
2537 // Iterate over global handles.
2538 GlobalHandles::IterateRoots(v);
2539 SYNCHRONIZE_TAG("globalhandles");
2540
2541 // Iterate over pointers being held by inactive threads.
2542 ThreadManager::Iterate(v);
2543 SYNCHRONIZE_TAG("threadmanager");
2544}
2545#undef SYNCHRONIZE_TAG
2546
2547
2548// Flag is set when the heap has been configured. The heap can be repeatedly
2549// configured through the API until it is setup.
2550static bool heap_configured = false;
2551
2552// TODO(1236194): Since the heap size is configurable on the command line
2553// and through the API, we should gracefully handle the case that the heap
2554// size is not big enough to fit all the initial objects.
2555bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2556 if (HasBeenSetup()) return false;
2557
2558 if (semispace_size > 0) semispace_size_ = semispace_size;
2559 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2560
2561 // The new space size must be a power of two to support single-bit testing
2562 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002563 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002564 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2565 young_generation_size_ = 2 * semispace_size_;
2566
2567 // The old generation is paged.
2568 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2569
2570 heap_configured = true;
2571 return true;
2572}
2573
2574
kasper.lund7276f142008-07-30 08:49:36 +00002575bool Heap::ConfigureHeapDefault() {
2576 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2577}
2578
2579
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002580int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002581 return old_pointer_space_->Size()
2582 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002583 + code_space_->Size()
2584 + map_space_->Size()
2585 + lo_space_->Size();
2586}
2587
2588
kasper.lund7276f142008-07-30 08:49:36 +00002589int Heap::PromotedExternalMemorySize() {
2590 if (amount_of_external_allocated_memory_
2591 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2592 return amount_of_external_allocated_memory_
2593 - amount_of_external_allocated_memory_at_last_global_gc_;
2594}
2595
2596
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002597bool Heap::Setup(bool create_heap_objects) {
2598 // Initialize heap spaces and initial maps and objects. Whenever something
2599 // goes wrong, just return false. The caller should check the results and
2600 // call Heap::TearDown() to release allocated memory.
2601 //
2602 // If the heap is not yet configured (eg, through the API), configure it.
2603 // Configuration is based on the flags new-space-size (really the semispace
2604 // size) and old-space-size if set or the initial values of semispace_size_
2605 // and old_generation_size_ otherwise.
2606 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002607 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002608 }
2609
2610 // Setup memory allocator and allocate an initial chunk of memory. The
2611 // initial chunk is double the size of the new space to ensure that we can
2612 // find a pair of semispaces that are contiguous and aligned to their size.
2613 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2614 void* chunk
2615 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2616 if (chunk == NULL) return false;
2617
2618 // Put the initial chunk of the old space at the start of the initial
2619 // chunk, then the two new space semispaces, then the initial chunk of
2620 // code space. Align the pair of semispaces to their size, which must be
2621 // a power of 2.
2622 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002623 Address code_space_start = reinterpret_cast<Address>(chunk);
2624 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2625 Address old_space_start = new_space_start + young_generation_size_;
2626 int code_space_size = new_space_start - code_space_start;
2627 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002628
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002629 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002630 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002631
2632 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002633 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002634 old_pointer_space_ =
2635 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2636 if (old_pointer_space_ == NULL) return false;
2637 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2638 return false;
2639 }
2640 old_data_space_ =
2641 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2642 if (old_data_space_ == NULL) return false;
2643 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2644 old_space_size >> 1)) {
2645 return false;
2646 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002647
2648 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002649 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002650 code_space_ =
2651 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002652 if (code_space_ == NULL) return false;
2653 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2654
2655 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002656 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002657 if (map_space_ == NULL) return false;
2658 // Setting up a paged space without giving it a virtual memory range big
2659 // enough to hold at least a page will cause it to allocate.
2660 if (!map_space_->Setup(NULL, 0)) return false;
2661
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002662 // The large object code space may contain code or data. We set the memory
2663 // to be non-executable here for safety, but this means we need to enable it
2664 // explicitly when allocating large code objects.
2665 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002666 if (lo_space_ == NULL) return false;
2667 if (!lo_space_->Setup()) return false;
2668
2669 if (create_heap_objects) {
2670 // Create initial maps.
2671 if (!CreateInitialMaps()) return false;
2672 if (!CreateApiObjects()) return false;
2673
2674 // Create initial objects
2675 if (!CreateInitialObjects()) return false;
2676 }
2677
2678 LOG(IntEvent("heap-capacity", Capacity()));
2679 LOG(IntEvent("heap-available", Available()));
2680
2681 return true;
2682}
2683
2684
2685void Heap::TearDown() {
2686 GlobalHandles::TearDown();
2687
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002688 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002689
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002690 if (old_pointer_space_ != NULL) {
2691 old_pointer_space_->TearDown();
2692 delete old_pointer_space_;
2693 old_pointer_space_ = NULL;
2694 }
2695
2696 if (old_data_space_ != NULL) {
2697 old_data_space_->TearDown();
2698 delete old_data_space_;
2699 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002700 }
2701
2702 if (code_space_ != NULL) {
2703 code_space_->TearDown();
2704 delete code_space_;
2705 code_space_ = NULL;
2706 }
2707
2708 if (map_space_ != NULL) {
2709 map_space_->TearDown();
2710 delete map_space_;
2711 map_space_ = NULL;
2712 }
2713
2714 if (lo_space_ != NULL) {
2715 lo_space_->TearDown();
2716 delete lo_space_;
2717 lo_space_ = NULL;
2718 }
2719
2720 MemoryAllocator::TearDown();
2721}
2722
2723
2724void Heap::Shrink() {
2725 // Try to shrink map, old, and code spaces.
2726 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002727 old_pointer_space_->Shrink();
2728 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002729 code_space_->Shrink();
2730}
2731
2732
2733#ifdef DEBUG
2734
2735class PrintHandleVisitor: public ObjectVisitor {
2736 public:
2737 void VisitPointers(Object** start, Object** end) {
2738 for (Object** p = start; p < end; p++)
2739 PrintF(" handle %p to %p\n", p, *p);
2740 }
2741};
2742
2743void Heap::PrintHandles() {
2744 PrintF("Handles:\n");
2745 PrintHandleVisitor v;
2746 HandleScopeImplementer::Iterate(&v);
2747}
2748
2749#endif
2750
2751
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002752Space* AllSpaces::next() {
2753 switch (counter_++) {
2754 case NEW_SPACE:
2755 return Heap::new_space();
2756 case OLD_POINTER_SPACE:
2757 return Heap::old_pointer_space();
2758 case OLD_DATA_SPACE:
2759 return Heap::old_data_space();
2760 case CODE_SPACE:
2761 return Heap::code_space();
2762 case MAP_SPACE:
2763 return Heap::map_space();
2764 case LO_SPACE:
2765 return Heap::lo_space();
2766 default:
2767 return NULL;
2768 }
2769}
2770
2771
2772PagedSpace* PagedSpaces::next() {
2773 switch (counter_++) {
2774 case OLD_POINTER_SPACE:
2775 return Heap::old_pointer_space();
2776 case OLD_DATA_SPACE:
2777 return Heap::old_data_space();
2778 case CODE_SPACE:
2779 return Heap::code_space();
2780 case MAP_SPACE:
2781 return Heap::map_space();
2782 default:
2783 return NULL;
2784 }
2785}
2786
2787
2788
2789OldSpace* OldSpaces::next() {
2790 switch (counter_++) {
2791 case OLD_POINTER_SPACE:
2792 return Heap::old_pointer_space();
2793 case OLD_DATA_SPACE:
2794 return Heap::old_data_space();
2795 case CODE_SPACE:
2796 return Heap::code_space();
2797 default:
2798 return NULL;
2799 }
2800}
2801
2802
kasper.lund7276f142008-07-30 08:49:36 +00002803SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2804}
2805
2806
2807SpaceIterator::~SpaceIterator() {
2808 // Delete active iterator if any.
2809 delete iterator_;
2810}
2811
2812
2813bool SpaceIterator::has_next() {
2814 // Iterate until no more spaces.
2815 return current_space_ != LAST_SPACE;
2816}
2817
2818
2819ObjectIterator* SpaceIterator::next() {
2820 if (iterator_ != NULL) {
2821 delete iterator_;
2822 iterator_ = NULL;
2823 // Move to the next space
2824 current_space_++;
2825 if (current_space_ > LAST_SPACE) {
2826 return NULL;
2827 }
2828 }
2829
2830 // Return iterator for the new current space.
2831 return CreateIterator();
2832}
2833
2834
2835// Create an iterator for the space to iterate.
2836ObjectIterator* SpaceIterator::CreateIterator() {
2837 ASSERT(iterator_ == NULL);
2838
2839 switch (current_space_) {
2840 case NEW_SPACE:
2841 iterator_ = new SemiSpaceIterator(Heap::new_space());
2842 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002843 case OLD_POINTER_SPACE:
2844 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2845 break;
2846 case OLD_DATA_SPACE:
2847 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002848 break;
2849 case CODE_SPACE:
2850 iterator_ = new HeapObjectIterator(Heap::code_space());
2851 break;
2852 case MAP_SPACE:
2853 iterator_ = new HeapObjectIterator(Heap::map_space());
2854 break;
2855 case LO_SPACE:
2856 iterator_ = new LargeObjectIterator(Heap::lo_space());
2857 break;
2858 }
2859
2860 // Return the newly allocated iterator;
2861 ASSERT(iterator_ != NULL);
2862 return iterator_;
2863}
2864
2865
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002866HeapIterator::HeapIterator() {
2867 Init();
2868}
2869
2870
2871HeapIterator::~HeapIterator() {
2872 Shutdown();
2873}
2874
2875
2876void HeapIterator::Init() {
2877 // Start the iteration.
2878 space_iterator_ = new SpaceIterator();
2879 object_iterator_ = space_iterator_->next();
2880}
2881
2882
2883void HeapIterator::Shutdown() {
2884 // Make sure the last iterator is deallocated.
2885 delete space_iterator_;
2886 space_iterator_ = NULL;
2887 object_iterator_ = NULL;
2888}
2889
2890
2891bool HeapIterator::has_next() {
2892 // No iterator means we are done.
2893 if (object_iterator_ == NULL) return false;
2894
2895 if (object_iterator_->has_next_object()) {
2896 // If the current iterator has more objects we are fine.
2897 return true;
2898 } else {
2899 // Go though the spaces looking for one that has objects.
2900 while (space_iterator_->has_next()) {
2901 object_iterator_ = space_iterator_->next();
2902 if (object_iterator_->has_next_object()) {
2903 return true;
2904 }
2905 }
2906 }
2907 // Done with the last space.
2908 object_iterator_ = NULL;
2909 return false;
2910}
2911
2912
2913HeapObject* HeapIterator::next() {
2914 if (has_next()) {
2915 return object_iterator_->next_object();
2916 } else {
2917 return NULL;
2918 }
2919}
2920
2921
2922void HeapIterator::reset() {
2923 // Restart the iterator.
2924 Shutdown();
2925 Init();
2926}
2927
2928
2929//
2930// HeapProfiler class implementation.
2931//
2932#ifdef ENABLE_LOGGING_AND_PROFILING
2933void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
2934 InstanceType type = obj->map()->instance_type();
2935 ASSERT(0 <= type && type <= LAST_TYPE);
2936 info[type].increment_number(1);
2937 info[type].increment_bytes(obj->Size());
2938}
2939#endif
2940
2941
2942#ifdef ENABLE_LOGGING_AND_PROFILING
2943void HeapProfiler::WriteSample() {
2944 LOG(HeapSampleBeginEvent("Heap", "allocated"));
2945
2946 HistogramInfo info[LAST_TYPE+1];
2947#define DEF_TYPE_NAME(name) info[name].set_name(#name);
2948 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
2949#undef DEF_TYPE_NAME
2950
2951 HeapIterator iterator;
2952 while (iterator.has_next()) {
2953 CollectStats(iterator.next(), info);
2954 }
2955
2956 // Lump all the string types together.
2957 int string_number = 0;
2958 int string_bytes = 0;
2959#define INCREMENT_SIZE(type, size, name) \
2960 string_number += info[type].number(); \
2961 string_bytes += info[type].bytes();
2962 STRING_TYPE_LIST(INCREMENT_SIZE)
2963#undef INCREMENT_SIZE
2964 if (string_bytes > 0) {
2965 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
2966 }
2967
2968 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
2969 if (info[i].bytes() > 0) {
2970 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
2971 info[i].bytes()));
2972 }
2973 }
2974
2975 LOG(HeapSampleEndEvent("Heap", "allocated"));
2976}
2977
2978
2979#endif
2980
2981
2982
2983#ifdef DEBUG
2984
2985static bool search_for_any_global;
2986static Object* search_target;
2987static bool found_target;
2988static List<Object*> object_stack(20);
2989
2990
2991// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2992static const int kMarkTag = 2;
2993
2994static void MarkObjectRecursively(Object** p);
2995class MarkObjectVisitor : public ObjectVisitor {
2996 public:
2997 void VisitPointers(Object** start, Object** end) {
2998 // Copy all HeapObject pointers in [start, end)
2999 for (Object** p = start; p < end; p++) {
3000 if ((*p)->IsHeapObject())
3001 MarkObjectRecursively(p);
3002 }
3003 }
3004};
3005
3006static MarkObjectVisitor mark_visitor;
3007
3008static void MarkObjectRecursively(Object** p) {
3009 if (!(*p)->IsHeapObject()) return;
3010
3011 HeapObject* obj = HeapObject::cast(*p);
3012
3013 Object* map = obj->map();
3014
3015 if (!map->IsHeapObject()) return; // visited before
3016
3017 if (found_target) return; // stop if target found
3018 object_stack.Add(obj);
3019 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3020 (!search_for_any_global && (obj == search_target))) {
3021 found_target = true;
3022 return;
3023 }
3024
3025 if (obj->IsCode()) {
3026 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3027 }
3028
3029 // not visited yet
3030 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3031
3032 Address map_addr = map_p->address();
3033
3034 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3035
3036 MarkObjectRecursively(&map);
3037
3038 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3039 &mark_visitor);
3040
3041 if (!found_target) // don't pop if found the target
3042 object_stack.RemoveLast();
3043}
3044
3045
3046static void UnmarkObjectRecursively(Object** p);
3047class UnmarkObjectVisitor : public ObjectVisitor {
3048 public:
3049 void VisitPointers(Object** start, Object** end) {
3050 // Copy all HeapObject pointers in [start, end)
3051 for (Object** p = start; p < end; p++) {
3052 if ((*p)->IsHeapObject())
3053 UnmarkObjectRecursively(p);
3054 }
3055 }
3056};
3057
3058static UnmarkObjectVisitor unmark_visitor;
3059
3060static void UnmarkObjectRecursively(Object** p) {
3061 if (!(*p)->IsHeapObject()) return;
3062
3063 HeapObject* obj = HeapObject::cast(*p);
3064
3065 Object* map = obj->map();
3066
3067 if (map->IsHeapObject()) return; // unmarked already
3068
3069 Address map_addr = reinterpret_cast<Address>(map);
3070
3071 map_addr -= kMarkTag;
3072
3073 ASSERT_TAG_ALIGNED(map_addr);
3074
3075 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3076
3077 obj->set_map(reinterpret_cast<Map*>(map_p));
3078
3079 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3080
3081 obj->IterateBody(Map::cast(map_p)->instance_type(),
3082 obj->SizeFromMap(Map::cast(map_p)),
3083 &unmark_visitor);
3084
3085 if (obj->IsCode()) {
3086 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3087 }
3088}
3089
3090
3091static void MarkRootObjectRecursively(Object** root) {
3092 if (search_for_any_global) {
3093 ASSERT(search_target == NULL);
3094 } else {
3095 ASSERT(search_target->IsHeapObject());
3096 }
3097 found_target = false;
3098 object_stack.Clear();
3099
3100 MarkObjectRecursively(root);
3101 UnmarkObjectRecursively(root);
3102
3103 if (found_target) {
3104 PrintF("=====================================\n");
3105 PrintF("==== Path to object ====\n");
3106 PrintF("=====================================\n\n");
3107
3108 ASSERT(!object_stack.is_empty());
3109 for (int i = 0; i < object_stack.length(); i++) {
3110 if (i > 0) PrintF("\n |\n |\n V\n\n");
3111 Object* obj = object_stack[i];
3112 obj->Print();
3113 }
3114 PrintF("=====================================\n");
3115 }
3116}
3117
3118
3119// Helper class for visiting HeapObjects recursively.
3120class MarkRootVisitor: public ObjectVisitor {
3121 public:
3122 void VisitPointers(Object** start, Object** end) {
3123 // Visit all HeapObject pointers in [start, end)
3124 for (Object** p = start; p < end; p++) {
3125 if ((*p)->IsHeapObject())
3126 MarkRootObjectRecursively(p);
3127 }
3128 }
3129};
3130
3131
3132// Triggers a depth-first traversal of reachable objects from roots
3133// and finds a path to a specific heap object and prints it.
3134void Heap::TracePathToObject() {
3135 search_target = NULL;
3136 search_for_any_global = false;
3137
3138 MarkRootVisitor root_visitor;
3139 IterateRoots(&root_visitor);
3140}
3141
3142
3143// Triggers a depth-first traversal of reachable objects from roots
3144// and finds a path to any global object and prints it. Useful for
3145// determining the source for leaks of global objects.
3146void Heap::TracePathToGlobal() {
3147 search_target = NULL;
3148 search_for_any_global = true;
3149
3150 MarkRootVisitor root_visitor;
3151 IterateRoots(&root_visitor);
3152}
3153#endif
3154
3155
kasper.lund7276f142008-07-30 08:49:36 +00003156GCTracer::GCTracer()
3157 : start_time_(0.0),
3158 start_size_(0.0),
3159 gc_count_(0),
3160 full_gc_count_(0),
3161 is_compacting_(false),
3162 marked_count_(0) {
3163 // These two fields reflect the state of the previous full collection.
3164 // Set them before they are changed by the collector.
3165 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3166 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3167 if (!FLAG_trace_gc) return;
3168 start_time_ = OS::TimeCurrentMillis();
3169 start_size_ = SizeOfHeapObjects();
3170}
3171
3172
3173GCTracer::~GCTracer() {
3174 if (!FLAG_trace_gc) return;
3175 // Printf ONE line iff flag is set.
3176 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3177 CollectorString(),
3178 start_size_, SizeOfHeapObjects(),
3179 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3180}
3181
3182
3183const char* GCTracer::CollectorString() {
3184 switch (collector_) {
3185 case SCAVENGER:
3186 return "Scavenge";
3187 case MARK_COMPACTOR:
3188 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3189 : "Mark-sweep";
3190 }
3191 return "Unknown GC";
3192}
3193
3194
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003195#ifdef DEBUG
3196bool Heap::GarbageCollectionGreedyCheck() {
3197 ASSERT(FLAG_gc_greedy);
3198 if (Bootstrapper::IsActive()) return true;
3199 if (disallow_allocation_failure()) return true;
3200 return CollectGarbage(0, NEW_SPACE);
3201}
3202#endif
3203
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003204} } // namespace v8::internal