blob: bb30deb2cb9bd153beee997790af54ed404fcc07 [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
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000067static const int kMinimumPromotionLimit = 2*MB;
68static const int kMinimumAllocationLimit = 8*MB;
69
70int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
71int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
72
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073int Heap::old_gen_exhausted_ = false;
74
kasper.lund7276f142008-07-30 08:49:36 +000075int Heap::amount_of_external_allocated_memory_ = 0;
76int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
77
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078// semispace_size_ should be a power of 2 and old_generation_size_ should be
79// a multiple of Page::kPageSize.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000080int Heap::semispace_size_ = 2*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081int Heap::old_generation_size_ = 512*MB;
82int Heap::initial_semispace_size_ = 256*KB;
83
84GCCallback Heap::global_gc_prologue_callback_ = NULL;
85GCCallback Heap::global_gc_epilogue_callback_ = NULL;
86
87// Variables set based on semispace_size_ and old_generation_size_ in
88// ConfigureHeap.
89int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
90
91// Double the new space after this many scavenge collections.
92int Heap::new_space_growth_limit_ = 8;
93int Heap::scavenge_count_ = 0;
94Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
95
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000096int Heap::mc_count_ = 0;
97int Heap::gc_count_ = 0;
98
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000099int Heap::always_allocate_scope_depth_ = 0;
100
kasper.lund7276f142008-07-30 08:49:36 +0000101#ifdef DEBUG
102bool Heap::allocation_allowed_ = true;
103
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000104int Heap::allocation_timeout_ = 0;
105bool Heap::disallow_allocation_failure_ = false;
106#endif // DEBUG
107
108
109int Heap::Capacity() {
110 if (!HasBeenSetup()) return 0;
111
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000112 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000113 old_pointer_space_->Capacity() +
114 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115 code_space_->Capacity() +
116 map_space_->Capacity();
117}
118
119
120int Heap::Available() {
121 if (!HasBeenSetup()) return 0;
122
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000123 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000124 old_pointer_space_->Available() +
125 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000126 code_space_->Available() +
127 map_space_->Available();
128}
129
130
131bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000132 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000133 old_data_space_ != NULL &&
134 code_space_ != NULL &&
135 map_space_ != NULL &&
136 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000137}
138
139
140GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
141 // Is global GC requested?
142 if (space != NEW_SPACE || FLAG_gc_global) {
143 Counters::gc_compactor_caused_by_request.Increment();
144 return MARK_COMPACTOR;
145 }
146
147 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000148 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000149 Counters::gc_compactor_caused_by_promoted_data.Increment();
150 return MARK_COMPACTOR;
151 }
152
153 // Have allocation in OLD and LO failed?
154 if (old_gen_exhausted_) {
155 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
156 return MARK_COMPACTOR;
157 }
158
159 // Is there enough space left in OLD to guarantee that a scavenge can
160 // succeed?
161 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000162 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000163 // for object promotion. It counts only the bytes that the memory
164 // allocator has not yet allocated from the OS and assigned to any space,
165 // and does not count available bytes already in the old space or code
166 // space. Undercounting is safe---we may get an unrequested full GC when
167 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000168 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000169 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
170 return MARK_COMPACTOR;
171 }
172
173 // Default
174 return SCAVENGER;
175}
176
177
178// TODO(1238405): Combine the infrastructure for --heap-stats and
179// --log-gc to avoid the complicated preprocessor and flag testing.
180#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
181void Heap::ReportStatisticsBeforeGC() {
182 // Heap::ReportHeapStatistics will also log NewSpace statistics when
183 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
184 // following logic is used to avoid double logging.
185#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000186 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187 if (FLAG_heap_stats) {
188 ReportHeapStatistics("Before GC");
189 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000190 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000192 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193#elif defined(DEBUG)
194 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000195 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000196 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 }
199#elif defined(ENABLE_LOGGING_AND_PROFILING)
200 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000201 new_space_.CollectStatistics();
202 new_space_.ReportStatistics();
203 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 }
205#endif
206}
207
208
209// TODO(1238405): Combine the infrastructure for --heap-stats and
210// --log-gc to avoid the complicated preprocessor and flag testing.
211void Heap::ReportStatisticsAfterGC() {
212 // Similar to the before GC, we use some complicated logic to ensure that
213 // NewSpace statistics are logged exactly once when --log-gc is turned on.
214#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
215 if (FLAG_heap_stats) {
216 ReportHeapStatistics("After GC");
217 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000218 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000219 }
220#elif defined(DEBUG)
221 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
222#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000223 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000224#endif
225}
226#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
227
228
229void Heap::GarbageCollectionPrologue() {
230 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000231 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232#ifdef DEBUG
233 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
234 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235
236 if (FLAG_verify_heap) {
237 Verify();
238 }
239
240 if (FLAG_gc_verbose) Print();
241
242 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000243 // Not all spaces have remembered set bits that we care about.
244 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 map_space_->PrintRSet();
246 lo_space_->PrintRSet();
247 }
248#endif
249
250#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
251 ReportStatisticsBeforeGC();
252#endif
253}
254
255int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000256 int total = 0;
257 AllSpaces spaces;
258 while (Space* space = spaces.next()) total += space->Size();
259 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000260}
261
262void Heap::GarbageCollectionEpilogue() {
263#ifdef DEBUG
264 allow_allocation(true);
265 ZapFromSpace();
266
267 if (FLAG_verify_heap) {
268 Verify();
269 }
270
271 if (FLAG_print_global_handles) GlobalHandles::Print();
272 if (FLAG_print_handles) PrintHandles();
273 if (FLAG_gc_verbose) Print();
274 if (FLAG_code_stats) ReportCodeStatistics("After GC");
275#endif
276
277 Counters::alive_after_last_gc.Set(SizeOfObjects());
278
279 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
280 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
281 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
282#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
283 ReportStatisticsAfterGC();
284#endif
285}
286
287
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000288void Heap::CollectAllGarbage() {
289 // Since we are ignoring the return value, the exact choice of space does
290 // not matter, so long as we do not specify NEW_SPACE, which would not
291 // cause a full GC.
292 CollectGarbage(0, OLD_POINTER_SPACE);
293}
294
295
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000296bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
297 // The VM is in the GC state until exiting this function.
298 VMState state(GC);
299
300#ifdef DEBUG
301 // Reset the allocation timeout to the GC interval, but make sure to
302 // allow at least a few allocations after a collection. The reason
303 // for this is that we have a lot of allocation sequences and we
304 // assume that a garbage collection will allow the subsequent
305 // allocation attempts to go through.
306 allocation_timeout_ = Max(6, FLAG_gc_interval);
307#endif
308
309 { GCTracer tracer;
310 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000311 // The GC count was incremented in the prologue. Tell the tracer about
312 // it.
313 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000314
315 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000316 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317 tracer.set_collector(collector);
318
319 StatsRate* rate = (collector == SCAVENGER)
320 ? &Counters::gc_scavenger
321 : &Counters::gc_compactor;
322 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000323 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 rate->Stop();
325
326 GarbageCollectionEpilogue();
327 }
328
329
330#ifdef ENABLE_LOGGING_AND_PROFILING
331 if (FLAG_log_gc) HeapProfiler::WriteSample();
332#endif
333
334 switch (space) {
335 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000336 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000337 case OLD_POINTER_SPACE:
338 return old_pointer_space_->Available() >= requested_size;
339 case OLD_DATA_SPACE:
340 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 case CODE_SPACE:
342 return code_space_->Available() >= requested_size;
343 case MAP_SPACE:
344 return map_space_->Available() >= requested_size;
345 case LO_SPACE:
346 return lo_space_->Available() >= requested_size;
347 }
348 return false;
349}
350
351
kasper.lund7276f142008-07-30 08:49:36 +0000352void Heap::PerformScavenge() {
353 GCTracer tracer;
354 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
355}
356
357
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000358void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000359 GarbageCollector collector,
360 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
362 ASSERT(!allocation_allowed_);
363 global_gc_prologue_callback_();
364 }
365
366 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000367 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000369 int old_gen_size = PromotedSpaceSize();
370 old_gen_promotion_limit_ =
371 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
372 old_gen_allocation_limit_ =
373 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374 old_gen_exhausted_ = false;
375
376 // If we have used the mark-compact collector to collect the new
377 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000378 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379 // case where (1) a new space collection was requested, (2) the
380 // collector selection policy selected the mark-compact collector,
381 // and (3) the mark-compact collector policy selected not to
382 // compact the new space. In that case, there is no more (usable)
383 // free space in the new space after the collection compared to
384 // before.
385 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
386 Scavenge();
387 }
388 } else {
389 Scavenge();
390 }
391 Counters::objs_since_last_young.Set(0);
392
393 // Process weak handles post gc.
394 GlobalHandles::PostGarbageCollectionProcessing();
395
kasper.lund7276f142008-07-30 08:49:36 +0000396 if (collector == MARK_COMPACTOR) {
397 // Register the amount of external allocated memory.
398 amount_of_external_allocated_memory_at_last_global_gc_ =
399 amount_of_external_allocated_memory_;
400 }
401
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
403 ASSERT(!allocation_allowed_);
404 global_gc_epilogue_callback_();
405 }
406}
407
408
kasper.lund7276f142008-07-30 08:49:36 +0000409void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000410 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000412 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413 LOG(ResourceEvent("markcompact", "begin"));
414
415 MarkCompactPrologue();
416
kasper.lund7276f142008-07-30 08:49:36 +0000417 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418
419 MarkCompactEpilogue();
420
421 LOG(ResourceEvent("markcompact", "end"));
422
423 gc_state_ = NOT_IN_GC;
424
425 Shrink();
426
427 Counters::objs_since_last_full.Set(0);
428}
429
430
431void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000432 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000433 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000434 RegExpImpl::OldSpaceCollectionPrologue();
435 Top::MarkCompactPrologue();
436 ThreadManager::MarkCompactPrologue();
437}
438
439
440void Heap::MarkCompactEpilogue() {
441 Top::MarkCompactEpilogue();
442 ThreadManager::MarkCompactEpilogue();
443}
444
445
446Object* Heap::FindCodeObject(Address a) {
447 Object* obj = code_space_->FindObject(a);
448 if (obj->IsFailure()) {
449 obj = lo_space_->FindObject(a);
450 }
kasper.lund7276f142008-07-30 08:49:36 +0000451 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000452 return obj;
453}
454
455
456// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000457class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000458 public:
459
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000460 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461
462 void VisitPointers(Object** start, Object** end) {
463 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000464 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 }
466
467 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000468 void ScavengePointer(Object** p) {
469 Object* object = *p;
470 if (!Heap::InNewSpace(object)) return;
471 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
472 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000473 }
474};
475
476
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000477// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000478static Address promoted_top = NULL;
479
480
481#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000482// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000483// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000484class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000485 public:
486 void VisitPointers(Object** start, Object**end) {
487 for (Object** current = start; current < end; current++) {
488 if ((*current)->IsHeapObject()) {
489 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
490 }
491 }
492 }
493};
494#endif
495
496void Heap::Scavenge() {
497#ifdef DEBUG
498 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000499 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500 HeapObjectIterator it(code_space_);
501 while (it.has_next()) {
502 HeapObject* object = it.next();
503 if (object->IsCode()) {
504 Code::cast(object)->ConvertICTargetsFromAddressToObject();
505 }
506 object->Iterate(&v);
507 if (object->IsCode()) {
508 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
509 }
510 }
511 }
512#endif
513
514 gc_state_ = SCAVENGE;
515
516 // Implements Cheney's copying algorithm
517 LOG(ResourceEvent("scavenge", "begin"));
518
519 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000520 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521 scavenge_count_ > new_space_growth_limit_) {
522 // Double the size of the new space, and double the limit. The next
523 // doubling attempt will occur after the current new_space_growth_limit_
524 // more collections.
525 // TODO(1240712): NewSpace::Double has a return value which is
526 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000527 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528 new_space_growth_limit_ *= 2;
529 }
530
531 // Flip the semispaces. After flipping, to space is empty, from space has
532 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000533 new_space_.Flip();
534 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000535
536 // We need to sweep newly copied objects which can be in either the to space
537 // or the old space. For to space objects, we use a mark. Newly copied
538 // objects lie between the mark and the allocation top. For objects
539 // promoted to old space, we write their addresses downward from the top of
540 // the new space. Sweeping newly promoted objects requires an allocation
541 // pointer and a mark. Note that the allocation pointer 'top' actually
542 // moves downward from the high address in the to space.
543 //
544 // There is guaranteed to be enough room at the top of the to space for the
545 // addresses of promoted objects: every object promoted frees up its size in
546 // bytes from the top of the new space, and objects are at least one pointer
547 // in size. Using the new space to record promoted addresses makes the
548 // scavenge collector agnostic to the allocation strategy (eg, linear or
549 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000550 Address new_mark = new_space_.ToSpaceLow();
551 Address promoted_mark = new_space_.ToSpaceHigh();
552 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000553
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000554 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000556 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557
558 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000559 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000560 IterateRSet(old_pointer_space_, &ScavengePointer);
561 IterateRSet(map_space_, &ScavengePointer);
562 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563
564 bool has_processed_weak_pointers = false;
565
566 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000567 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 ASSERT(promoted_mark >= promoted_top);
569
570 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000571 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572 // Sweep newly copied objects in the to space. The allocation pointer
573 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000574 Address previous_top = new_space_.top();
575 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000577 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578 }
579 new_mark = previous_top;
580
581 // Sweep newly copied objects in the old space. The promotion 'top'
582 // pointer could change during sweeping.
583 previous_top = promoted_top;
584 for (Address current = promoted_mark - kPointerSize;
585 current >= previous_top;
586 current -= kPointerSize) {
587 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000588 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 UpdateRSet(object);
590 }
591 promoted_mark = previous_top;
592 }
593
594 if (has_processed_weak_pointers) break; // We are done.
595 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000596 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597 has_processed_weak_pointers = true;
598 }
599
600 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000601 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602
603 LOG(ResourceEvent("scavenge", "end"));
604
605 gc_state_ = NOT_IN_GC;
606}
607
608
609void Heap::ClearRSetRange(Address start, int size_in_bytes) {
610 uint32_t start_bit;
611 Address start_word_address =
612 Page::ComputeRSetBitPosition(start, 0, &start_bit);
613 uint32_t end_bit;
614 Address end_word_address =
615 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
616 0,
617 &end_bit);
618
619 // We want to clear the bits in the starting word starting with the
620 // first bit, and in the ending word up to and including the last
621 // bit. Build a pair of bitmasks to do that.
622 uint32_t start_bitmask = start_bit - 1;
623 uint32_t end_bitmask = ~((end_bit << 1) - 1);
624
625 // If the start address and end address are the same, we mask that
626 // word once, otherwise mask the starting and ending word
627 // separately and all the ones in between.
628 if (start_word_address == end_word_address) {
629 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
630 } else {
631 Memory::uint32_at(start_word_address) &= start_bitmask;
632 Memory::uint32_at(end_word_address) &= end_bitmask;
633 start_word_address += kIntSize;
634 memset(start_word_address, 0, end_word_address - start_word_address);
635 }
636}
637
638
639class UpdateRSetVisitor: public ObjectVisitor {
640 public:
641
642 void VisitPointer(Object** p) {
643 UpdateRSet(p);
644 }
645
646 void VisitPointers(Object** start, Object** end) {
647 // Update a store into slots [start, end), used (a) to update remembered
648 // set when promoting a young object to old space or (b) to rebuild
649 // remembered sets after a mark-compact collection.
650 for (Object** p = start; p < end; p++) UpdateRSet(p);
651 }
652 private:
653
654 void UpdateRSet(Object** p) {
655 // The remembered set should not be set. It should be clear for objects
656 // newly copied to old space, and it is cleared before rebuilding in the
657 // mark-compact collector.
658 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
659 if (Heap::InNewSpace(*p)) {
660 Page::SetRSet(reinterpret_cast<Address>(p), 0);
661 }
662 }
663};
664
665
666int Heap::UpdateRSet(HeapObject* obj) {
667 ASSERT(!InNewSpace(obj));
668 // Special handling of fixed arrays to iterate the body based on the start
669 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
670 // will not work because Page::SetRSet needs to have the start of the
671 // object.
672 if (obj->IsFixedArray()) {
673 FixedArray* array = FixedArray::cast(obj);
674 int length = array->length();
675 for (int i = 0; i < length; i++) {
676 int offset = FixedArray::kHeaderSize + i * kPointerSize;
677 ASSERT(!Page::IsRSetSet(obj->address(), offset));
678 if (Heap::InNewSpace(array->get(i))) {
679 Page::SetRSet(obj->address(), offset);
680 }
681 }
682 } else if (!obj->IsCode()) {
683 // Skip code object, we know it does not contain inter-generational
684 // pointers.
685 UpdateRSetVisitor v;
686 obj->Iterate(&v);
687 }
688 return obj->Size();
689}
690
691
692void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000693 // By definition, we do not care about remembered set bits in code or data
694 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000695 map_space_->ClearRSet();
696 RebuildRSets(map_space_);
697
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000698 old_pointer_space_->ClearRSet();
699 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000700
701 Heap::lo_space_->ClearRSet();
702 RebuildRSets(lo_space_);
703}
704
705
706void Heap::RebuildRSets(PagedSpace* space) {
707 HeapObjectIterator it(space);
708 while (it.has_next()) Heap::UpdateRSet(it.next());
709}
710
711
712void Heap::RebuildRSets(LargeObjectSpace* space) {
713 LargeObjectIterator it(space);
714 while (it.has_next()) Heap::UpdateRSet(it.next());
715}
716
717
718#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
719void Heap::RecordCopiedObject(HeapObject* obj) {
720 bool should_record = false;
721#ifdef DEBUG
722 should_record = FLAG_heap_stats;
723#endif
724#ifdef ENABLE_LOGGING_AND_PROFILING
725 should_record = should_record || FLAG_log_gc;
726#endif
727 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000728 if (new_space_.Contains(obj)) {
729 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000730 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000731 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000732 }
733 }
734}
735#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
736
737
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000738
739HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000740 HeapObject* target,
741 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000742 // Copy the content of source to target.
743 CopyBlock(reinterpret_cast<Object**>(target->address()),
744 reinterpret_cast<Object**>(source->address()),
745 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000746
kasper.lund7276f142008-07-30 08:49:36 +0000747 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000748 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000749
750 // Update NewSpace stats if necessary.
751#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
752 RecordCopiedObject(target);
753#endif
754
755 return target;
756}
757
758
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000759// Inlined function.
760void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
761 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000762
kasper.lund7276f142008-07-30 08:49:36 +0000763 // We use the first word (where the map pointer usually is) of a heap
764 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000765 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000767 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000768
kasper.lund7276f142008-07-30 08:49:36 +0000769 // If the first word is a forwarding address, the object has already been
770 // copied.
771 if (first_word.IsForwardingAddress()) {
772 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773 return;
774 }
775
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000776 // Call the slow part of scavenge object.
777 return ScavengeObjectSlow(p, object);
778}
779
780static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
781 // A ConString object with Heap::empty_string() as the right side
782 // is a candidate for being shortcut by the scavenger.
783 ASSERT(object->map() == map);
784 return (map->instance_type() < FIRST_NONSTRING_TYPE) &&
785 (String::cast(object)->map_representation_tag(map) == kConsStringTag) &&
786 (ConsString::cast(object)->second() == Heap::empty_string());
787}
788
789
790void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
791 ASSERT(InFromSpace(object));
792 MapWord first_word = object->map_word();
793 ASSERT(!first_word.IsForwardingAddress());
794
795 // Optimization: Bypass flattened ConsString objects.
796 if (IsShortcutCandidate(object, first_word.ToMap())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 object = HeapObject::cast(ConsString::cast(object)->first());
798 *p = object;
799 // After patching *p we have to repeat the checks that object is in the
800 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000801 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000802 first_word = object->map_word();
803 if (first_word.IsForwardingAddress()) {
804 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000805 return;
806 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 }
808
kasper.lund7276f142008-07-30 08:49:36 +0000809 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000810 // If the object should be promoted, we try to copy it to old space.
811 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000812 OldSpace* target_space = Heap::TargetSpace(object);
813 ASSERT(target_space == Heap::old_pointer_space_ ||
814 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000815 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000817 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000818 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000819 // Record the object's address at the top of the to space, to allow
820 // it to be swept by the scavenger.
821 promoted_top -= kPointerSize;
822 Memory::Object_at(promoted_top) = *p;
823 } else {
824#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000825 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000827 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000828 (*p)->Iterate(&v);
829#endif
830 }
831 return;
832 }
833 }
834
835 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000836 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837 // Failed allocation at this point is utterly unexpected.
838 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000839 *p = MigrateObject(object, HeapObject::cast(result), object_size);
840}
841
842
843void Heap::ScavengePointer(HeapObject** p) {
844 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845}
846
847
848Object* Heap::AllocatePartialMap(InstanceType instance_type,
849 int instance_size) {
850 Object* result = AllocateRawMap(Map::kSize);
851 if (result->IsFailure()) return result;
852
853 // Map::cast cannot be used due to uninitialized map field.
854 reinterpret_cast<Map*>(result)->set_map(meta_map());
855 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
856 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000857 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000858 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
859 return result;
860}
861
862
863Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
864 Object* result = AllocateRawMap(Map::kSize);
865 if (result->IsFailure()) return result;
866
867 Map* map = reinterpret_cast<Map*>(result);
868 map->set_map(meta_map());
869 map->set_instance_type(instance_type);
870 map->set_prototype(null_value());
871 map->set_constructor(null_value());
872 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000873 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000874 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000875 map->set_code_cache(empty_fixed_array());
876 map->set_unused_property_fields(0);
877 map->set_bit_field(0);
878 return map;
879}
880
881
882bool Heap::CreateInitialMaps() {
883 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
884 if (obj->IsFailure()) return false;
885
886 // Map::cast cannot be used due to uninitialized map field.
887 meta_map_ = reinterpret_cast<Map*>(obj);
888 meta_map()->set_map(meta_map());
889
890 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
891 if (obj->IsFailure()) return false;
892 fixed_array_map_ = Map::cast(obj);
893
894 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
895 if (obj->IsFailure()) return false;
896 oddball_map_ = Map::cast(obj);
897
898 // Allocate the empty array
899 obj = AllocateEmptyFixedArray();
900 if (obj->IsFailure()) return false;
901 empty_fixed_array_ = FixedArray::cast(obj);
902
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000903 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000904 if (obj->IsFailure()) return false;
905 null_value_ = obj;
906
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000907 // Allocate the empty descriptor array. AllocateMap can now be used.
908 obj = AllocateEmptyFixedArray();
909 if (obj->IsFailure()) return false;
910 // There is a check against empty_descriptor_array() in cast().
911 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000912
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000913 // Fix the instance_descriptors for the existing maps.
914 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000915 meta_map()->set_code_cache(empty_fixed_array());
916
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000917 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000918 fixed_array_map()->set_code_cache(empty_fixed_array());
919
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000920 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000921 oddball_map()->set_code_cache(empty_fixed_array());
922
923 // Fix prototype object for existing maps.
924 meta_map()->set_prototype(null_value());
925 meta_map()->set_constructor(null_value());
926
927 fixed_array_map()->set_prototype(null_value());
928 fixed_array_map()->set_constructor(null_value());
929 oddball_map()->set_prototype(null_value());
930 oddball_map()->set_constructor(null_value());
931
932 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
933 if (obj->IsFailure()) return false;
934 heap_number_map_ = Map::cast(obj);
935
936 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
937 if (obj->IsFailure()) return false;
938 proxy_map_ = Map::cast(obj);
939
940#define ALLOCATE_STRING_MAP(type, size, name) \
941 obj = AllocateMap(type, size); \
942 if (obj->IsFailure()) return false; \
943 name##_map_ = Map::cast(obj);
944 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
945#undef ALLOCATE_STRING_MAP
946
ager@chromium.org7c537e22008-10-16 08:43:32 +0000947 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000948 if (obj->IsFailure()) return false;
949 undetectable_short_string_map_ = Map::cast(obj);
950 undetectable_short_string_map_->set_is_undetectable();
951
ager@chromium.org7c537e22008-10-16 08:43:32 +0000952 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000953 if (obj->IsFailure()) return false;
954 undetectable_medium_string_map_ = Map::cast(obj);
955 undetectable_medium_string_map_->set_is_undetectable();
956
ager@chromium.org7c537e22008-10-16 08:43:32 +0000957 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958 if (obj->IsFailure()) return false;
959 undetectable_long_string_map_ = Map::cast(obj);
960 undetectable_long_string_map_->set_is_undetectable();
961
ager@chromium.org7c537e22008-10-16 08:43:32 +0000962 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963 if (obj->IsFailure()) return false;
964 undetectable_short_ascii_string_map_ = Map::cast(obj);
965 undetectable_short_ascii_string_map_->set_is_undetectable();
966
ager@chromium.org7c537e22008-10-16 08:43:32 +0000967 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000968 if (obj->IsFailure()) return false;
969 undetectable_medium_ascii_string_map_ = Map::cast(obj);
970 undetectable_medium_ascii_string_map_->set_is_undetectable();
971
ager@chromium.org7c537e22008-10-16 08:43:32 +0000972 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000973 if (obj->IsFailure()) return false;
974 undetectable_long_ascii_string_map_ = Map::cast(obj);
975 undetectable_long_ascii_string_map_->set_is_undetectable();
976
977 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
978 if (obj->IsFailure()) return false;
979 byte_array_map_ = Map::cast(obj);
980
981 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
982 if (obj->IsFailure()) return false;
983 code_map_ = Map::cast(obj);
984
985 obj = AllocateMap(FILLER_TYPE, kPointerSize);
986 if (obj->IsFailure()) return false;
987 one_word_filler_map_ = Map::cast(obj);
988
989 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
990 if (obj->IsFailure()) return false;
991 two_word_filler_map_ = Map::cast(obj);
992
993#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
994 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
995 if (obj->IsFailure()) return false; \
996 name##_map_ = Map::cast(obj);
997 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
998#undef ALLOCATE_STRUCT_MAP
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 hash_table_map_ = Map::cast(obj);
1003
ager@chromium.org236ad962008-09-25 09:45:57 +00001004 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001005 if (obj->IsFailure()) return false;
1006 context_map_ = Map::cast(obj);
1007
ager@chromium.org236ad962008-09-25 09:45:57 +00001008 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001009 if (obj->IsFailure()) return false;
1010 global_context_map_ = Map::cast(obj);
1011
1012 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1013 if (obj->IsFailure()) return false;
1014 boilerplate_function_map_ = Map::cast(obj);
1015
1016 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1017 if (obj->IsFailure()) return false;
1018 shared_function_info_map_ = Map::cast(obj);
1019
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001020 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001021 return true;
1022}
1023
1024
1025Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1026 // Statically ensure that it is safe to allocate heap numbers in paged
1027 // spaces.
1028 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001029 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001030 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001031 if (result->IsFailure()) return result;
1032
1033 HeapObject::cast(result)->set_map(heap_number_map());
1034 HeapNumber::cast(result)->set_value(value);
1035 return result;
1036}
1037
1038
1039Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001040 // Use general version, if we're forced to always allocate.
1041 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001042 // This version of AllocateHeapNumber is optimized for
1043 // allocation in new space.
1044 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1045 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001046 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001047 if (result->IsFailure()) return result;
1048 HeapObject::cast(result)->set_map(heap_number_map());
1049 HeapNumber::cast(result)->set_value(value);
1050 return result;
1051}
1052
1053
1054Object* Heap::CreateOddball(Map* map,
1055 const char* to_string,
1056 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001057 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001058 if (result->IsFailure()) return result;
1059 return Oddball::cast(result)->Initialize(to_string, to_number);
1060}
1061
1062
1063bool Heap::CreateApiObjects() {
1064 Object* obj;
1065
1066 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1067 if (obj->IsFailure()) return false;
1068 neander_map_ = Map::cast(obj);
1069
1070 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1071 if (obj->IsFailure()) return false;
1072 Object* elements = AllocateFixedArray(2);
1073 if (elements->IsFailure()) return false;
1074 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1075 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1076 message_listeners_ = JSObject::cast(obj);
1077
1078 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1079 if (obj->IsFailure()) return false;
1080 elements = AllocateFixedArray(2);
1081 if (elements->IsFailure()) return false;
1082 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1083 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1084 debug_event_listeners_ = JSObject::cast(obj);
1085
1086 return true;
1087}
1088
1089void Heap::CreateFixedStubs() {
1090 // Here we create roots for fixed stubs. They are needed at GC
1091 // for cooking and uncooking (check out frames.cc).
1092 // The eliminates the need for doing dictionary lookup in the
1093 // stub cache for these stubs.
1094 HandleScope scope;
1095 {
1096 CEntryStub stub;
1097 c_entry_code_ = *stub.GetCode();
1098 }
1099 {
1100 CEntryDebugBreakStub stub;
1101 c_entry_debug_break_code_ = *stub.GetCode();
1102 }
1103 {
1104 JSEntryStub stub;
1105 js_entry_code_ = *stub.GetCode();
1106 }
1107 {
1108 JSConstructEntryStub stub;
1109 js_construct_entry_code_ = *stub.GetCode();
1110 }
1111}
1112
1113
1114bool Heap::CreateInitialObjects() {
1115 Object* obj;
1116
1117 // The -0 value must be set before NumberFromDouble works.
1118 obj = AllocateHeapNumber(-0.0, TENURED);
1119 if (obj->IsFailure()) return false;
1120 minus_zero_value_ = obj;
1121 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1122
1123 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1124 if (obj->IsFailure()) return false;
1125 nan_value_ = obj;
1126
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001127 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001128 if (obj->IsFailure()) return false;
1129 undefined_value_ = obj;
1130 ASSERT(!InNewSpace(undefined_value()));
1131
1132 // Allocate initial symbol table.
1133 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1134 if (obj->IsFailure()) return false;
1135 symbol_table_ = obj;
1136
1137 // Assign the print strings for oddballs after creating symboltable.
1138 Object* symbol = LookupAsciiSymbol("undefined");
1139 if (symbol->IsFailure()) return false;
1140 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1141 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1142
1143 // Assign the print strings for oddballs after creating symboltable.
1144 symbol = LookupAsciiSymbol("null");
1145 if (symbol->IsFailure()) return false;
1146 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1147 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1148
1149 // Allocate the null_value
1150 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1151 if (obj->IsFailure()) return false;
1152
1153 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1154 if (obj->IsFailure()) return false;
1155 true_value_ = obj;
1156
1157 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1158 if (obj->IsFailure()) return false;
1159 false_value_ = obj;
1160
1161 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1162 if (obj->IsFailure()) return false;
1163 the_hole_value_ = obj;
1164
1165 // Allocate the empty string.
1166 obj = AllocateRawAsciiString(0, TENURED);
1167 if (obj->IsFailure()) return false;
1168 empty_string_ = String::cast(obj);
1169
1170#define SYMBOL_INITIALIZE(name, string) \
1171 obj = LookupAsciiSymbol(string); \
1172 if (obj->IsFailure()) return false; \
1173 (name##_) = String::cast(obj);
1174 SYMBOL_LIST(SYMBOL_INITIALIZE)
1175#undef SYMBOL_INITIALIZE
1176
1177 // Allocate the proxy for __proto__.
1178 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1179 if (obj->IsFailure()) return false;
1180 prototype_accessors_ = Proxy::cast(obj);
1181
1182 // Allocate the code_stubs dictionary.
1183 obj = Dictionary::Allocate(4);
1184 if (obj->IsFailure()) return false;
1185 code_stubs_ = Dictionary::cast(obj);
1186
1187 // Allocate the non_monomorphic_cache used in stub-cache.cc
1188 obj = Dictionary::Allocate(4);
1189 if (obj->IsFailure()) return false;
1190 non_monomorphic_cache_ = Dictionary::cast(obj);
1191
1192 CreateFixedStubs();
1193
1194 // Allocate the number->string conversion cache
1195 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1196 if (obj->IsFailure()) return false;
1197 number_string_cache_ = FixedArray::cast(obj);
1198
1199 // Allocate cache for single character strings.
1200 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1201 if (obj->IsFailure()) return false;
1202 single_character_string_cache_ = FixedArray::cast(obj);
1203
1204 // Allocate cache for external strings pointing to native source code.
1205 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1206 if (obj->IsFailure()) return false;
1207 natives_source_cache_ = FixedArray::cast(obj);
1208
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001209 // Initialize keyed lookup cache.
1210 ClearKeyedLookupCache();
1211
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001212 // Initialize compilation cache.
1213 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001214
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001215 return true;
1216}
1217
1218
1219static inline int double_get_hash(double d) {
1220 DoubleRepresentation rep(d);
1221 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1222 (Heap::kNumberStringCacheSize - 1));
1223}
1224
1225
1226static inline int smi_get_hash(Smi* smi) {
1227 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1228}
1229
1230
1231
1232Object* Heap::GetNumberStringCache(Object* number) {
1233 int hash;
1234 if (number->IsSmi()) {
1235 hash = smi_get_hash(Smi::cast(number));
1236 } else {
1237 hash = double_get_hash(number->Number());
1238 }
1239 Object* key = number_string_cache_->get(hash * 2);
1240 if (key == number) {
1241 return String::cast(number_string_cache_->get(hash * 2 + 1));
1242 } else if (key->IsHeapNumber() &&
1243 number->IsHeapNumber() &&
1244 key->Number() == number->Number()) {
1245 return String::cast(number_string_cache_->get(hash * 2 + 1));
1246 }
1247 return undefined_value();
1248}
1249
1250
1251void Heap::SetNumberStringCache(Object* number, String* string) {
1252 int hash;
1253 if (number->IsSmi()) {
1254 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001255 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001256 } else {
1257 hash = double_get_hash(number->Number());
1258 number_string_cache_->set(hash * 2, number);
1259 }
1260 number_string_cache_->set(hash * 2 + 1, string);
1261}
1262
1263
1264Object* Heap::SmiOrNumberFromDouble(double value,
1265 bool new_object,
1266 PretenureFlag pretenure) {
1267 // We need to distinguish the minus zero value and this cannot be
1268 // done after conversion to int. Doing this by comparing bit
1269 // patterns is faster than using fpclassify() et al.
1270 static const DoubleRepresentation plus_zero(0.0);
1271 static const DoubleRepresentation minus_zero(-0.0);
1272 static const DoubleRepresentation nan(OS::nan_value());
1273 ASSERT(minus_zero_value_ != NULL);
1274 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1275
1276 DoubleRepresentation rep(value);
1277 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1278 if (rep.bits == minus_zero.bits) {
1279 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1280 : minus_zero_value_;
1281 }
1282 if (rep.bits == nan.bits) {
1283 return new_object
1284 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1285 : nan_value_;
1286 }
1287
1288 // Try to represent the value as a tagged small integer.
1289 int int_value = FastD2I(value);
1290 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1291 return Smi::FromInt(int_value);
1292 }
1293
1294 // Materialize the value in the heap.
1295 return AllocateHeapNumber(value, pretenure);
1296}
1297
1298
1299Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1300 return SmiOrNumberFromDouble(value,
1301 true /* number object must be new */,
1302 pretenure);
1303}
1304
1305
1306Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1307 return SmiOrNumberFromDouble(value,
1308 false /* use preallocated NaN, -0.0 */,
1309 pretenure);
1310}
1311
1312
1313Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1314 // Statically ensure that it is safe to allocate proxies in paged spaces.
1315 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001316 AllocationSpace space =
1317 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001318 Object* result = Allocate(proxy_map(), space);
1319 if (result->IsFailure()) return result;
1320
1321 Proxy::cast(result)->set_proxy(proxy);
1322 return result;
1323}
1324
1325
1326Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1327 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1328 if (result->IsFailure()) return result;
1329
1330 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1331 share->set_name(name);
1332 Code* illegal = Builtins::builtin(Builtins::Illegal);
1333 share->set_code(illegal);
1334 share->set_expected_nof_properties(0);
1335 share->set_length(0);
1336 share->set_formal_parameter_count(0);
1337 share->set_instance_class_name(Object_symbol());
1338 share->set_function_data(undefined_value());
1339 share->set_lazy_load_data(undefined_value());
1340 share->set_script(undefined_value());
1341 share->set_start_position_and_type(0);
1342 share->set_debug_info(undefined_value());
1343 return result;
1344}
1345
1346
1347Object* Heap::AllocateConsString(String* first, String* second) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001348 int first_length = first->length();
1349 int second_length = second->length();
1350 int length = first_length + second_length;
ager@chromium.org7c537e22008-10-16 08:43:32 +00001351 bool is_ascii = first->is_ascii_representation()
1352 && second->is_ascii_representation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001353
1354 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001355 if (length < String::kMinNonFlatLength) {
1356 ASSERT(first->IsFlat());
1357 ASSERT(second->IsFlat());
1358 if (is_ascii) {
1359 Object* result = AllocateRawAsciiString(length);
1360 if (result->IsFailure()) return result;
1361 // Copy the characters into the new object.
1362 char* dest = SeqAsciiString::cast(result)->GetChars();
1363 String::WriteToFlat(first, dest, 0, first_length);
1364 String::WriteToFlat(second, dest + first_length, 0, second_length);
1365 return result;
1366 } else {
1367 Object* result = AllocateRawTwoByteString(length);
1368 if (result->IsFailure()) return result;
1369 // Copy the characters into the new object.
1370 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1371 String::WriteToFlat(first, dest, 0, first_length);
1372 String::WriteToFlat(second, dest + first_length, 0, second_length);
1373 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001375 }
1376
1377 Map* map;
1378 if (length <= String::kMaxShortStringSize) {
1379 map = is_ascii ? short_cons_ascii_string_map()
1380 : short_cons_string_map();
1381 } else if (length <= String::kMaxMediumStringSize) {
1382 map = is_ascii ? medium_cons_ascii_string_map()
1383 : medium_cons_string_map();
1384 } else {
1385 map = is_ascii ? long_cons_ascii_string_map()
1386 : long_cons_string_map();
1387 }
1388
1389 Object* result = Allocate(map, NEW_SPACE);
1390 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001391 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001392 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001393 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1394 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001395 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396 return result;
1397}
1398
1399
1400Object* Heap::AllocateSlicedString(String* buffer, int start, int end) {
1401 int length = end - start;
1402
1403 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001404 if (end - start <= String::kMinNonFlatLength) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405 return Heap::AllocateSubString(buffer, start, end);
1406 }
1407
1408 Map* map;
1409 if (length <= String::kMaxShortStringSize) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001410 map = buffer->is_ascii_representation() ? short_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001411 : short_sliced_string_map();
1412 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001413 map = buffer->is_ascii_representation() ? medium_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001414 : medium_sliced_string_map();
1415 } else {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001416 map = buffer->is_ascii_representation() ? long_sliced_ascii_string_map()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 : long_sliced_string_map();
1418 }
1419
1420 Object* result = Allocate(map, NEW_SPACE);
1421 if (result->IsFailure()) return result;
1422
1423 SlicedString* sliced_string = SlicedString::cast(result);
1424 sliced_string->set_buffer(buffer);
1425 sliced_string->set_start(start);
1426 sliced_string->set_length(length);
1427
1428 return result;
1429}
1430
1431
1432Object* Heap::AllocateSubString(String* buffer, int start, int end) {
1433 int length = end - start;
1434
ager@chromium.org7c537e22008-10-16 08:43:32 +00001435 if (length == 1) {
1436 return Heap::LookupSingleCharacterStringFromCode(buffer->Get(start));
1437 }
1438
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001439 // Make an attempt to flatten the buffer to reduce access time.
1440 buffer->TryFlatten();
1441
ager@chromium.org7c537e22008-10-16 08:43:32 +00001442 Object* result = buffer->is_ascii_representation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001443 ? AllocateRawAsciiString(length)
1444 : AllocateRawTwoByteString(length);
1445 if (result->IsFailure()) return result;
1446
1447 // Copy the characters into the new object.
1448 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001449 StringHasher hasher(length);
1450 int i = 0;
1451 for (; i < length && hasher.is_array_index(); i++) {
1452 uc32 c = buffer->Get(start + i);
1453 hasher.AddCharacter(c);
1454 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001455 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001456 for (; i < length; i++) {
1457 uc32 c = buffer->Get(start + i);
1458 hasher.AddCharacterNoIndex(c);
1459 string_result->Set(i, c);
1460 }
1461 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001462 return result;
1463}
1464
1465
1466Object* Heap::AllocateExternalStringFromAscii(
1467 ExternalAsciiString::Resource* resource) {
1468 Map* map;
1469 int length = resource->length();
1470 if (length <= String::kMaxShortStringSize) {
1471 map = short_external_ascii_string_map();
1472 } else if (length <= String::kMaxMediumStringSize) {
1473 map = medium_external_ascii_string_map();
1474 } else {
1475 map = long_external_ascii_string_map();
1476 }
1477
1478 Object* result = Allocate(map, NEW_SPACE);
1479 if (result->IsFailure()) return result;
1480
1481 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1482 external_string->set_length(length);
1483 external_string->set_resource(resource);
1484
1485 return result;
1486}
1487
1488
1489Object* Heap::AllocateExternalStringFromTwoByte(
1490 ExternalTwoByteString::Resource* resource) {
1491 Map* map;
1492 int length = resource->length();
1493 if (length <= String::kMaxShortStringSize) {
1494 map = short_external_string_map();
1495 } else if (length <= String::kMaxMediumStringSize) {
1496 map = medium_external_string_map();
1497 } else {
1498 map = long_external_string_map();
1499 }
1500
1501 Object* result = Allocate(map, NEW_SPACE);
1502 if (result->IsFailure()) return result;
1503
1504 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1505 external_string->set_length(length);
1506 external_string->set_resource(resource);
1507
1508 return result;
1509}
1510
1511
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001512Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001513 if (code <= String::kMaxAsciiCharCode) {
1514 Object* value = Heap::single_character_string_cache()->get(code);
1515 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001516
1517 char buffer[1];
1518 buffer[0] = static_cast<char>(code);
1519 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1520
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001521 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522 Heap::single_character_string_cache()->set(code, result);
1523 return result;
1524 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001525
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001526 Object* result = Heap::AllocateRawTwoByteString(1);
1527 if (result->IsFailure()) return result;
1528 String::cast(result)->Set(0, code);
1529 return result;
1530}
1531
1532
1533Object* Heap::AllocateByteArray(int length) {
1534 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001535 AllocationSpace space =
1536 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001537
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001538 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001539
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001540 if (result->IsFailure()) return result;
1541
1542 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1543 reinterpret_cast<Array*>(result)->set_length(length);
1544 return result;
1545}
1546
1547
1548Object* Heap::CreateCode(const CodeDesc& desc,
1549 ScopeInfo<>* sinfo,
1550 Code::Flags flags) {
1551 // Compute size
1552 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1553 int sinfo_size = 0;
1554 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1555 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001556 Object* result;
1557 if (obj_size > MaxHeapObjectSize()) {
1558 result = lo_space_->AllocateRawCode(obj_size);
1559 } else {
1560 result = code_space_->AllocateRaw(obj_size);
1561 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001562
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001563 if (result->IsFailure()) return result;
1564
1565 // Initialize the object
1566 HeapObject::cast(result)->set_map(code_map());
1567 Code* code = Code::cast(result);
1568 code->set_instruction_size(desc.instr_size);
1569 code->set_relocation_size(desc.reloc_size);
1570 code->set_sinfo_size(sinfo_size);
1571 code->set_flags(flags);
1572 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
1573 code->CopyFrom(desc); // migrate generated code
1574 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1575
1576#ifdef DEBUG
1577 code->Verify();
1578#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579 return code;
1580}
1581
1582
1583Object* Heap::CopyCode(Code* code) {
1584 // Allocate an object the same size as the code object.
1585 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001586 Object* result;
1587 if (obj_size > MaxHeapObjectSize()) {
1588 result = lo_space_->AllocateRawCode(obj_size);
1589 } else {
1590 result = code_space_->AllocateRaw(obj_size);
1591 }
1592
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001593 if (result->IsFailure()) return result;
1594
1595 // Copy code object.
1596 Address old_addr = code->address();
1597 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001598 CopyBlock(reinterpret_cast<Object**>(new_addr),
1599 reinterpret_cast<Object**>(old_addr),
1600 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001601 // Relocate the copy.
1602 Code* new_code = Code::cast(result);
1603 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001604 return new_code;
1605}
1606
1607
1608Object* Heap::Allocate(Map* map, AllocationSpace space) {
1609 ASSERT(gc_state_ == NOT_IN_GC);
1610 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001611 Object* result = AllocateRaw(map->instance_size(),
1612 space,
1613 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614 if (result->IsFailure()) return result;
1615 HeapObject::cast(result)->set_map(map);
1616 return result;
1617}
1618
1619
1620Object* Heap::InitializeFunction(JSFunction* function,
1621 SharedFunctionInfo* shared,
1622 Object* prototype) {
1623 ASSERT(!prototype->IsMap());
1624 function->initialize_properties();
1625 function->initialize_elements();
1626 function->set_shared(shared);
1627 function->set_prototype_or_initial_map(prototype);
1628 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001629 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001630 return function;
1631}
1632
1633
1634Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1635 // Allocate the prototype.
1636 Object* prototype =
1637 AllocateJSObject(Top::context()->global_context()->object_function());
1638 if (prototype->IsFailure()) return prototype;
1639 // When creating the prototype for the function we must set its
1640 // constructor to the function.
1641 Object* result =
1642 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1643 function,
1644 DONT_ENUM);
1645 if (result->IsFailure()) return result;
1646 return prototype;
1647}
1648
1649
1650Object* Heap::AllocateFunction(Map* function_map,
1651 SharedFunctionInfo* shared,
1652 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001653 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654 if (result->IsFailure()) return result;
1655 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1656}
1657
1658
1659Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001660 // To get fast allocation and map sharing for arguments objects we
1661 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001662
1663 // This calls Copy directly rather than using Heap::AllocateRaw so we
1664 // duplicate the check here.
1665 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1666
1667 JSObject* boilerplate =
1668 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001669
1670 // Make the clone.
1671 Map* map = boilerplate->map();
1672 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001673 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001674 if (result->IsFailure()) return result;
1675
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001676 // Copy the content. The arguments boilerplate doesn't have any
1677 // fields that point to new space so it's safe to skip the write
1678 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001679 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1680 reinterpret_cast<Object**>(boilerplate->address()),
1681 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001683 // Set the two properties.
1684 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001685 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001686 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1687 Smi::FromInt(length),
1688 SKIP_WRITE_BARRIER);
1689
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001690 // Check the state of the object
1691 ASSERT(JSObject::cast(result)->HasFastProperties());
1692 ASSERT(JSObject::cast(result)->HasFastElements());
1693
1694 return result;
1695}
1696
1697
1698Object* Heap::AllocateInitialMap(JSFunction* fun) {
1699 ASSERT(!fun->has_initial_map());
1700
ager@chromium.org7c537e22008-10-16 08:43:32 +00001701 // First create a new map with the expected number of properties being
1702 // allocated in-object.
1703 int expected_nof_properties = fun->shared()->expected_nof_properties();
1704 int instance_size = JSObject::kHeaderSize +
1705 expected_nof_properties * kPointerSize;
1706 if (instance_size > JSObject::kMaxInstanceSize) {
1707 instance_size = JSObject::kMaxInstanceSize;
1708 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1709 kPointerSize;
1710 }
1711 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 if (map_obj->IsFailure()) return map_obj;
1713
1714 // Fetch or allocate prototype.
1715 Object* prototype;
1716 if (fun->has_instance_prototype()) {
1717 prototype = fun->instance_prototype();
1718 } else {
1719 prototype = AllocateFunctionPrototype(fun);
1720 if (prototype->IsFailure()) return prototype;
1721 }
1722 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001723 map->set_inobject_properties(expected_nof_properties);
1724 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001725 map->set_prototype(prototype);
1726 return map;
1727}
1728
1729
1730void Heap::InitializeJSObjectFromMap(JSObject* obj,
1731 FixedArray* properties,
1732 Map* map) {
1733 obj->set_properties(properties);
1734 obj->initialize_elements();
1735 // TODO(1240798): Initialize the object's body using valid initial values
1736 // according to the object's initial map. For example, if the map's
1737 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1738 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1739 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1740 // verification code has to cope with (temporarily) invalid objects. See
1741 // for example, JSArray::JSArrayVerify).
1742 obj->InitializeBody(map->instance_size());
1743}
1744
1745
1746Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1747 // JSFunctions should be allocated using AllocateFunction to be
1748 // properly initialized.
1749 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1750
1751 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001752 int prop_size = map->unused_property_fields() - map->inobject_properties();
1753 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754 if (properties->IsFailure()) return properties;
1755
1756 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001757 AllocationSpace space =
1758 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001759 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1760 Object* obj = Allocate(map, space);
1761 if (obj->IsFailure()) return obj;
1762
1763 // Initialize the JSObject.
1764 InitializeJSObjectFromMap(JSObject::cast(obj),
1765 FixedArray::cast(properties),
1766 map);
1767 return obj;
1768}
1769
1770
1771Object* Heap::AllocateJSObject(JSFunction* constructor,
1772 PretenureFlag pretenure) {
1773 // Allocate the initial map if absent.
1774 if (!constructor->has_initial_map()) {
1775 Object* initial_map = AllocateInitialMap(constructor);
1776 if (initial_map->IsFailure()) return initial_map;
1777 constructor->set_initial_map(Map::cast(initial_map));
1778 Map::cast(initial_map)->set_constructor(constructor);
1779 }
1780 // Allocate the object based on the constructors initial map.
1781 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1782}
1783
1784
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001785Object* Heap::CopyJSObject(JSObject* source) {
1786 // Never used to copy functions. If functions need to be copied we
1787 // have to be careful to clear the literals array.
1788 ASSERT(!source->IsJSFunction());
1789
1790 // Make the clone.
1791 Map* map = source->map();
1792 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001793 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001794
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001795 // If we're forced to always allocate, we use the general allocation
1796 // functions which may leave us with an object in old space.
1797 if (always_allocate()) {
1798 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1799 if (clone->IsFailure()) return clone;
1800 Address clone_address = HeapObject::cast(clone)->address();
1801 CopyBlock(reinterpret_cast<Object**>(clone_address),
1802 reinterpret_cast<Object**>(source->address()),
1803 object_size);
1804 // Update write barrier for all fields that lie beyond the header.
1805 for (int offset = JSObject::kHeaderSize;
1806 offset < object_size;
1807 offset += kPointerSize) {
1808 RecordWrite(clone_address, offset);
1809 }
1810 } else {
1811 clone = new_space_.AllocateRaw(object_size);
1812 if (clone->IsFailure()) return clone;
1813 ASSERT(Heap::InNewSpace(clone));
1814 // Since we know the clone is allocated in new space, we can copy
1815 // the contents without worring about updating the write barrier.
1816 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1817 reinterpret_cast<Object**>(source->address()),
1818 object_size);
1819 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001820
1821 FixedArray* elements = FixedArray::cast(source->elements());
1822 FixedArray* properties = FixedArray::cast(source->properties());
1823 // Update elements if necessary.
1824 if (elements->length()> 0) {
1825 Object* elem = CopyFixedArray(elements);
1826 if (elem->IsFailure()) return elem;
1827 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1828 }
1829 // Update properties if necessary.
1830 if (properties->length() > 0) {
1831 Object* prop = CopyFixedArray(properties);
1832 if (prop->IsFailure()) return prop;
1833 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1834 }
1835 // Return the new clone.
1836 return clone;
1837}
1838
1839
1840Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1841 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001842 // Allocate initial map if absent.
1843 if (!constructor->has_initial_map()) {
1844 Object* initial_map = AllocateInitialMap(constructor);
1845 if (initial_map->IsFailure()) return initial_map;
1846 constructor->set_initial_map(Map::cast(initial_map));
1847 Map::cast(initial_map)->set_constructor(constructor);
1848 }
1849
1850 Map* map = constructor->initial_map();
1851
1852 // Check that the already allocated object has the same size as
1853 // objects allocated using the constructor.
1854 ASSERT(map->instance_size() == object->map()->instance_size());
1855
1856 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001857 int prop_size = map->unused_property_fields() - map->inobject_properties();
1858 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 if (properties->IsFailure()) return properties;
1860
1861 // Reset the map for the object.
1862 object->set_map(constructor->initial_map());
1863
1864 // Reinitialize the object from the constructor map.
1865 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1866 return object;
1867}
1868
1869
1870Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1871 PretenureFlag pretenure) {
1872 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1873 if (result->IsFailure()) return result;
1874
1875 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001876 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001877 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001878 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001879 }
1880 return result;
1881}
1882
1883
1884Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1885 PretenureFlag pretenure) {
1886 // Count the number of characters in the UTF-8 string and check if
1887 // it is an ASCII string.
1888 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1889 decoder->Reset(string.start(), string.length());
1890 int chars = 0;
1891 bool is_ascii = true;
1892 while (decoder->has_more()) {
1893 uc32 r = decoder->GetNext();
1894 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1895 chars++;
1896 }
1897
1898 // If the string is ascii, we do not need to convert the characters
1899 // since UTF8 is backwards compatible with ascii.
1900 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1901
1902 Object* result = AllocateRawTwoByteString(chars, pretenure);
1903 if (result->IsFailure()) return result;
1904
1905 // Convert and copy the characters into the new object.
1906 String* string_result = String::cast(result);
1907 decoder->Reset(string.start(), string.length());
1908 for (int i = 0; i < chars; i++) {
1909 uc32 r = decoder->GetNext();
1910 string_result->Set(i, r);
1911 }
1912 return result;
1913}
1914
1915
1916Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1917 PretenureFlag pretenure) {
1918 // Check if the string is an ASCII string.
1919 int i = 0;
1920 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1921
1922 Object* result;
1923 if (i == string.length()) { // It's an ASCII string.
1924 result = AllocateRawAsciiString(string.length(), pretenure);
1925 } else { // It's not an ASCII string.
1926 result = AllocateRawTwoByteString(string.length(), pretenure);
1927 }
1928 if (result->IsFailure()) return result;
1929
1930 // Copy the characters into the new object, which may be either ASCII or
1931 // UTF-16.
1932 String* string_result = String::cast(result);
1933 for (int i = 0; i < string.length(); i++) {
1934 string_result->Set(i, string[i]);
1935 }
1936 return result;
1937}
1938
1939
1940Map* Heap::SymbolMapForString(String* string) {
1941 // If the string is in new space it cannot be used as a symbol.
1942 if (InNewSpace(string)) return NULL;
1943
1944 // Find the corresponding symbol map for strings.
1945 Map* map = string->map();
1946
1947 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
1948 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
1949 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
1950
1951 if (map == short_string_map()) return short_symbol_map();
1952 if (map == medium_string_map()) return medium_symbol_map();
1953 if (map == long_string_map()) return long_symbol_map();
1954
1955 if (map == short_cons_string_map()) return short_cons_symbol_map();
1956 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
1957 if (map == long_cons_string_map()) return long_cons_symbol_map();
1958
1959 if (map == short_cons_ascii_string_map()) {
1960 return short_cons_ascii_symbol_map();
1961 }
1962 if (map == medium_cons_ascii_string_map()) {
1963 return medium_cons_ascii_symbol_map();
1964 }
1965 if (map == long_cons_ascii_string_map()) {
1966 return long_cons_ascii_symbol_map();
1967 }
1968
1969 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001970 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
1971 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001972
1973 if (map == short_sliced_ascii_string_map()) {
1974 return short_sliced_ascii_symbol_map();
1975 }
1976 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001977 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001978 }
1979 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001980 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001981 }
1982
1983 if (map == short_external_string_map()) return short_external_string_map();
1984 if (map == medium_external_string_map()) return medium_external_string_map();
1985 if (map == long_external_string_map()) return long_external_string_map();
1986
1987 if (map == short_external_ascii_string_map()) {
1988 return short_external_ascii_string_map();
1989 }
1990 if (map == medium_external_ascii_string_map()) {
1991 return medium_external_ascii_string_map();
1992 }
1993 if (map == long_external_ascii_string_map()) {
1994 return long_external_ascii_string_map();
1995 }
1996
1997 // No match found.
1998 return NULL;
1999}
2000
2001
2002Object* Heap::AllocateSymbol(unibrow::CharacterStream* buffer,
2003 int chars,
ager@chromium.org7c537e22008-10-16 08:43:32 +00002004 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002005 // Ensure the chars matches the number of characters in the buffer.
2006 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2007 // Determine whether the string is ascii.
2008 bool is_ascii = true;
2009 while (buffer->has_more()) {
2010 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2011 }
2012 buffer->Rewind();
2013
2014 // Compute map and object size.
2015 int size;
2016 Map* map;
2017
2018 if (is_ascii) {
2019 if (chars <= String::kMaxShortStringSize) {
2020 map = short_ascii_symbol_map();
2021 } else if (chars <= String::kMaxMediumStringSize) {
2022 map = medium_ascii_symbol_map();
2023 } else {
2024 map = long_ascii_symbol_map();
2025 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002026 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002027 } else {
2028 if (chars <= String::kMaxShortStringSize) {
2029 map = short_symbol_map();
2030 } else if (chars <= String::kMaxMediumStringSize) {
2031 map = medium_symbol_map();
2032 } else {
2033 map = long_symbol_map();
2034 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002035 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002036 }
2037
2038 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002039 AllocationSpace space =
2040 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002041 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002042 if (result->IsFailure()) return result;
2043
2044 reinterpret_cast<HeapObject*>(result)->set_map(map);
2045 // The hash value contains the length of the string.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002046 String::cast(result)->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002047
2048 ASSERT_EQ(size, String::cast(result)->Size());
2049
2050 // Fill in the characters.
2051 for (int i = 0; i < chars; i++) {
2052 String::cast(result)->Set(i, buffer->GetNext());
2053 }
2054 return result;
2055}
2056
2057
2058Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002059 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002060 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002061 if (size > MaxHeapObjectSize()) {
2062 space = LO_SPACE;
2063 }
2064
2065 // Use AllocateRaw rather than Allocate because the object's size cannot be
2066 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002067 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002068 if (result->IsFailure()) return result;
2069
2070 // Determine the map based on the string's length.
2071 Map* map;
2072 if (length <= String::kMaxShortStringSize) {
2073 map = short_ascii_string_map();
2074 } else if (length <= String::kMaxMediumStringSize) {
2075 map = medium_ascii_string_map();
2076 } else {
2077 map = long_ascii_string_map();
2078 }
2079
2080 // Partially initialize the object.
2081 HeapObject::cast(result)->set_map(map);
2082 String::cast(result)->set_length(length);
2083 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2084 return result;
2085}
2086
2087
2088Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002089 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002090 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002091 if (size > MaxHeapObjectSize()) {
2092 space = LO_SPACE;
2093 }
2094
2095 // Use AllocateRaw rather than Allocate because the object's size cannot be
2096 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002097 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002098 if (result->IsFailure()) return result;
2099
2100 // Determine the map based on the string's length.
2101 Map* map;
2102 if (length <= String::kMaxShortStringSize) {
2103 map = short_string_map();
2104 } else if (length <= String::kMaxMediumStringSize) {
2105 map = medium_string_map();
2106 } else {
2107 map = long_string_map();
2108 }
2109
2110 // Partially initialize the object.
2111 HeapObject::cast(result)->set_map(map);
2112 String::cast(result)->set_length(length);
2113 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2114 return result;
2115}
2116
2117
2118Object* Heap::AllocateEmptyFixedArray() {
2119 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002120 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002121 if (result->IsFailure()) return result;
2122 // Initialize the object.
2123 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2124 reinterpret_cast<Array*>(result)->set_length(0);
2125 return result;
2126}
2127
2128
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002129Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002130 // Use the general function if we're forced to always allocate.
2131 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002132 // Allocate the raw data for a fixed array.
2133 int size = FixedArray::SizeFor(length);
2134 return (size > MaxHeapObjectSize())
2135 ? lo_space_->AllocateRawFixedArray(size)
2136 : new_space_.AllocateRaw(size);
2137}
2138
2139
2140Object* Heap::CopyFixedArray(FixedArray* src) {
2141 int len = src->length();
2142 Object* obj = AllocateRawFixedArray(len);
2143 if (obj->IsFailure()) return obj;
2144 if (Heap::InNewSpace(obj)) {
2145 HeapObject* dst = HeapObject::cast(obj);
2146 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2147 reinterpret_cast<Object**>(src->address()),
2148 FixedArray::SizeFor(len));
2149 return obj;
2150 }
2151 HeapObject::cast(obj)->set_map(src->map());
2152 FixedArray* result = FixedArray::cast(obj);
2153 result->set_length(len);
2154 // Copy the content
2155 WriteBarrierMode mode = result->GetWriteBarrierMode();
2156 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2157 return result;
2158}
2159
2160
2161Object* Heap::AllocateFixedArray(int length) {
2162 Object* result = AllocateRawFixedArray(length);
2163 if (!result->IsFailure()) {
2164 // Initialize header.
2165 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2166 FixedArray* array = FixedArray::cast(result);
2167 array->set_length(length);
2168 Object* value = undefined_value();
2169 // Initialize body.
2170 for (int index = 0; index < length; index++) {
2171 array->set(index, value, SKIP_WRITE_BARRIER);
2172 }
2173 }
2174 return result;
2175}
2176
2177
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002178Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2179 ASSERT(empty_fixed_array()->IsFixedArray());
2180 if (length == 0) return empty_fixed_array();
2181
2182 int size = FixedArray::SizeFor(length);
2183 Object* result;
2184 if (size > MaxHeapObjectSize()) {
2185 result = lo_space_->AllocateRawFixedArray(size);
2186 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002187 AllocationSpace space =
2188 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002189 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002190 }
2191 if (result->IsFailure()) return result;
2192
2193 // Initialize the object.
2194 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2195 FixedArray* array = FixedArray::cast(result);
2196 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002197 Object* value = undefined_value();
2198 for (int index = 0; index < length; index++) {
2199 array->set(index, value, SKIP_WRITE_BARRIER);
2200 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002201 return array;
2202}
2203
2204
2205Object* Heap::AllocateFixedArrayWithHoles(int length) {
2206 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002207 Object* result = AllocateRawFixedArray(length);
2208 if (!result->IsFailure()) {
2209 // Initialize header.
2210 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2211 FixedArray* array = FixedArray::cast(result);
2212 array->set_length(length);
2213 // Initialize body.
2214 Object* value = the_hole_value();
2215 for (int index = 0; index < length; index++) {
2216 array->set(index, value, SKIP_WRITE_BARRIER);
2217 }
2218 }
2219 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002220}
2221
2222
2223Object* Heap::AllocateHashTable(int length) {
2224 Object* result = Heap::AllocateFixedArray(length);
2225 if (result->IsFailure()) return result;
2226 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2227 ASSERT(result->IsDictionary());
2228 return result;
2229}
2230
2231
2232Object* Heap::AllocateGlobalContext() {
2233 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2234 if (result->IsFailure()) return result;
2235 Context* context = reinterpret_cast<Context*>(result);
2236 context->set_map(global_context_map());
2237 ASSERT(context->IsGlobalContext());
2238 ASSERT(result->IsContext());
2239 return result;
2240}
2241
2242
2243Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2244 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2245 Object* result = Heap::AllocateFixedArray(length);
2246 if (result->IsFailure()) return result;
2247 Context* context = reinterpret_cast<Context*>(result);
2248 context->set_map(context_map());
2249 context->set_closure(function);
2250 context->set_fcontext(context);
2251 context->set_previous(NULL);
2252 context->set_extension(NULL);
2253 context->set_global(function->context()->global());
2254 ASSERT(!context->IsGlobalContext());
2255 ASSERT(context->is_function_context());
2256 ASSERT(result->IsContext());
2257 return result;
2258}
2259
2260
2261Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2262 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2263 if (result->IsFailure()) return result;
2264 Context* context = reinterpret_cast<Context*>(result);
2265 context->set_map(context_map());
2266 context->set_closure(previous->closure());
2267 context->set_fcontext(previous->fcontext());
2268 context->set_previous(previous);
2269 context->set_extension(extension);
2270 context->set_global(previous->global());
2271 ASSERT(!context->IsGlobalContext());
2272 ASSERT(!context->is_function_context());
2273 ASSERT(result->IsContext());
2274 return result;
2275}
2276
2277
2278Object* Heap::AllocateStruct(InstanceType type) {
2279 Map* map;
2280 switch (type) {
2281#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2282STRUCT_LIST(MAKE_CASE)
2283#undef MAKE_CASE
2284 default:
2285 UNREACHABLE();
2286 return Failure::InternalError();
2287 }
2288 int size = map->instance_size();
2289 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002290 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002291 Object* result = Heap::Allocate(map, space);
2292 if (result->IsFailure()) return result;
2293 Struct::cast(result)->InitializeBody(size);
2294 return result;
2295}
2296
2297
2298#ifdef DEBUG
2299
2300void Heap::Print() {
2301 if (!HasBeenSetup()) return;
2302 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002303 AllSpaces spaces;
2304 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002305}
2306
2307
2308void Heap::ReportCodeStatistics(const char* title) {
2309 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2310 PagedSpace::ResetCodeStatistics();
2311 // We do not look for code in new space, map space, or old space. If code
2312 // somehow ends up in those spaces, we would miss it here.
2313 code_space_->CollectCodeStatistics();
2314 lo_space_->CollectCodeStatistics();
2315 PagedSpace::ReportCodeStatistics();
2316}
2317
2318
2319// This function expects that NewSpace's allocated objects histogram is
2320// populated (via a call to CollectStatistics or else as a side effect of a
2321// just-completed scavenge collection).
2322void Heap::ReportHeapStatistics(const char* title) {
2323 USE(title);
2324 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2325 title, gc_count_);
2326 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002327 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2328 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002329
2330 PrintF("\n");
2331 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2332 GlobalHandles::PrintStats();
2333 PrintF("\n");
2334
2335 PrintF("Heap statistics : ");
2336 MemoryAllocator::ReportStatistics();
2337 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002338 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002339 PrintF("Old pointer space : ");
2340 old_pointer_space_->ReportStatistics();
2341 PrintF("Old data space : ");
2342 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002343 PrintF("Code space : ");
2344 code_space_->ReportStatistics();
2345 PrintF("Map space : ");
2346 map_space_->ReportStatistics();
2347 PrintF("Large object space : ");
2348 lo_space_->ReportStatistics();
2349 PrintF(">>>>>> ========================================= >>>>>>\n");
2350}
2351
2352#endif // DEBUG
2353
2354bool Heap::Contains(HeapObject* value) {
2355 return Contains(value->address());
2356}
2357
2358
2359bool Heap::Contains(Address addr) {
2360 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2361 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002362 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002363 old_pointer_space_->Contains(addr) ||
2364 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002365 code_space_->Contains(addr) ||
2366 map_space_->Contains(addr) ||
2367 lo_space_->SlowContains(addr));
2368}
2369
2370
2371bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2372 return InSpace(value->address(), space);
2373}
2374
2375
2376bool Heap::InSpace(Address addr, AllocationSpace space) {
2377 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2378 if (!HasBeenSetup()) return false;
2379
2380 switch (space) {
2381 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002382 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002383 case OLD_POINTER_SPACE:
2384 return old_pointer_space_->Contains(addr);
2385 case OLD_DATA_SPACE:
2386 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002387 case CODE_SPACE:
2388 return code_space_->Contains(addr);
2389 case MAP_SPACE:
2390 return map_space_->Contains(addr);
2391 case LO_SPACE:
2392 return lo_space_->SlowContains(addr);
2393 }
2394
2395 return false;
2396}
2397
2398
2399#ifdef DEBUG
2400void Heap::Verify() {
2401 ASSERT(HasBeenSetup());
2402
2403 VerifyPointersVisitor visitor;
2404 Heap::IterateRoots(&visitor);
2405
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002406 AllSpaces spaces;
2407 while (Space* space = spaces.next()) {
2408 space->Verify();
2409 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002410}
2411#endif // DEBUG
2412
2413
2414Object* Heap::LookupSymbol(Vector<const char> string) {
2415 Object* symbol = NULL;
2416 Object* new_table =
2417 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2418 if (new_table->IsFailure()) return new_table;
2419 symbol_table_ = new_table;
2420 ASSERT(symbol != NULL);
2421 return symbol;
2422}
2423
2424
2425Object* Heap::LookupSymbol(String* string) {
2426 if (string->IsSymbol()) return string;
2427 Object* symbol = NULL;
2428 Object* new_table =
2429 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2430 if (new_table->IsFailure()) return new_table;
2431 symbol_table_ = new_table;
2432 ASSERT(symbol != NULL);
2433 return symbol;
2434}
2435
2436
ager@chromium.org7c537e22008-10-16 08:43:32 +00002437bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2438 if (string->IsSymbol()) {
2439 *symbol = string;
2440 return true;
2441 }
2442 SymbolTable* table = SymbolTable::cast(symbol_table_);
2443 return table->LookupSymbolIfExists(string, symbol);
2444}
2445
2446
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002447#ifdef DEBUG
2448void Heap::ZapFromSpace() {
2449 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002450 for (Address a = new_space_.FromSpaceLow();
2451 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002452 a += kPointerSize) {
2453 Memory::Address_at(a) = kFromSpaceZapValue;
2454 }
2455}
2456#endif // DEBUG
2457
2458
2459void Heap::IterateRSetRange(Address object_start,
2460 Address object_end,
2461 Address rset_start,
2462 ObjectSlotCallback copy_object_func) {
2463 Address object_address = object_start;
2464 Address rset_address = rset_start;
2465
2466 // Loop over all the pointers in [object_start, object_end).
2467 while (object_address < object_end) {
2468 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002469 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002470 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002471 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002472 // Do not dereference pointers at or past object_end.
2473 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2474 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002475 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002476 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2477 }
2478 // If this pointer does not need to be remembered anymore, clear
2479 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002480 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002481 }
2482 object_address += kPointerSize;
2483 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002484 // Update the remembered set if it has changed.
2485 if (result_rset != rset_word) {
2486 Memory::uint32_at(rset_address) = result_rset;
2487 }
2488 } else {
2489 // No bits in the word were set. This is the common case.
2490 object_address += kPointerSize * kBitsPerInt;
2491 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002492 rset_address += kIntSize;
2493 }
2494}
2495
2496
2497void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2498 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002499 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002500
2501 PageIterator it(space, PageIterator::PAGES_IN_USE);
2502 while (it.has_next()) {
2503 Page* page = it.next();
2504 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2505 page->RSetStart(), copy_object_func);
2506 }
2507}
2508
2509
2510#ifdef DEBUG
2511#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2512#else
2513#define SYNCHRONIZE_TAG(tag)
2514#endif
2515
2516void Heap::IterateRoots(ObjectVisitor* v) {
2517 IterateStrongRoots(v);
2518 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2519 SYNCHRONIZE_TAG("symbol_table");
2520}
2521
2522
2523void Heap::IterateStrongRoots(ObjectVisitor* v) {
2524#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002525 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002526 STRONG_ROOT_LIST(ROOT_ITERATE);
2527#undef ROOT_ITERATE
2528 SYNCHRONIZE_TAG("strong_root_list");
2529
2530#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002531 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002532 STRUCT_LIST(STRUCT_MAP_ITERATE);
2533#undef STRUCT_MAP_ITERATE
2534 SYNCHRONIZE_TAG("struct_map");
2535
2536#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002537 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002538 SYMBOL_LIST(SYMBOL_ITERATE)
2539#undef SYMBOL_ITERATE
2540 SYNCHRONIZE_TAG("symbol");
2541
2542 Bootstrapper::Iterate(v);
2543 SYNCHRONIZE_TAG("bootstrapper");
2544 Top::Iterate(v);
2545 SYNCHRONIZE_TAG("top");
2546 Debug::Iterate(v);
2547 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002548 CompilationCache::Iterate(v);
2549 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002550
2551 // Iterate over local handles in handle scopes.
2552 HandleScopeImplementer::Iterate(v);
2553 SYNCHRONIZE_TAG("handlescope");
2554
2555 // Iterate over the builtin code objects and code stubs in the heap. Note
2556 // that it is not strictly necessary to iterate over code objects on
2557 // scavenge collections. We still do it here because this same function
2558 // is used by the mark-sweep collector and the deserializer.
2559 Builtins::IterateBuiltins(v);
2560 SYNCHRONIZE_TAG("builtins");
2561
2562 // Iterate over global handles.
2563 GlobalHandles::IterateRoots(v);
2564 SYNCHRONIZE_TAG("globalhandles");
2565
2566 // Iterate over pointers being held by inactive threads.
2567 ThreadManager::Iterate(v);
2568 SYNCHRONIZE_TAG("threadmanager");
2569}
2570#undef SYNCHRONIZE_TAG
2571
2572
2573// Flag is set when the heap has been configured. The heap can be repeatedly
2574// configured through the API until it is setup.
2575static bool heap_configured = false;
2576
2577// TODO(1236194): Since the heap size is configurable on the command line
2578// and through the API, we should gracefully handle the case that the heap
2579// size is not big enough to fit all the initial objects.
2580bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2581 if (HasBeenSetup()) return false;
2582
2583 if (semispace_size > 0) semispace_size_ = semispace_size;
2584 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2585
2586 // The new space size must be a power of two to support single-bit testing
2587 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002588 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002589 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2590 young_generation_size_ = 2 * semispace_size_;
2591
2592 // The old generation is paged.
2593 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2594
2595 heap_configured = true;
2596 return true;
2597}
2598
2599
kasper.lund7276f142008-07-30 08:49:36 +00002600bool Heap::ConfigureHeapDefault() {
2601 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2602}
2603
2604
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002605int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002606 return old_pointer_space_->Size()
2607 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002608 + code_space_->Size()
2609 + map_space_->Size()
2610 + lo_space_->Size();
2611}
2612
2613
kasper.lund7276f142008-07-30 08:49:36 +00002614int Heap::PromotedExternalMemorySize() {
2615 if (amount_of_external_allocated_memory_
2616 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2617 return amount_of_external_allocated_memory_
2618 - amount_of_external_allocated_memory_at_last_global_gc_;
2619}
2620
2621
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002622bool Heap::Setup(bool create_heap_objects) {
2623 // Initialize heap spaces and initial maps and objects. Whenever something
2624 // goes wrong, just return false. The caller should check the results and
2625 // call Heap::TearDown() to release allocated memory.
2626 //
2627 // If the heap is not yet configured (eg, through the API), configure it.
2628 // Configuration is based on the flags new-space-size (really the semispace
2629 // size) and old-space-size if set or the initial values of semispace_size_
2630 // and old_generation_size_ otherwise.
2631 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002632 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002633 }
2634
2635 // Setup memory allocator and allocate an initial chunk of memory. The
2636 // initial chunk is double the size of the new space to ensure that we can
2637 // find a pair of semispaces that are contiguous and aligned to their size.
2638 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2639 void* chunk
2640 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2641 if (chunk == NULL) return false;
2642
2643 // Put the initial chunk of the old space at the start of the initial
2644 // chunk, then the two new space semispaces, then the initial chunk of
2645 // code space. Align the pair of semispaces to their size, which must be
2646 // a power of 2.
2647 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002648 Address code_space_start = reinterpret_cast<Address>(chunk);
2649 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2650 Address old_space_start = new_space_start + young_generation_size_;
2651 int code_space_size = new_space_start - code_space_start;
2652 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002653
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002654 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002655 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002656
2657 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002658 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002659 old_pointer_space_ =
2660 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2661 if (old_pointer_space_ == NULL) return false;
2662 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2663 return false;
2664 }
2665 old_data_space_ =
2666 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2667 if (old_data_space_ == NULL) return false;
2668 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2669 old_space_size >> 1)) {
2670 return false;
2671 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002672
2673 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002674 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002675 code_space_ =
2676 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002677 if (code_space_ == NULL) return false;
2678 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2679
2680 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002681 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002682 if (map_space_ == NULL) return false;
2683 // Setting up a paged space without giving it a virtual memory range big
2684 // enough to hold at least a page will cause it to allocate.
2685 if (!map_space_->Setup(NULL, 0)) return false;
2686
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002687 // The large object code space may contain code or data. We set the memory
2688 // to be non-executable here for safety, but this means we need to enable it
2689 // explicitly when allocating large code objects.
2690 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002691 if (lo_space_ == NULL) return false;
2692 if (!lo_space_->Setup()) return false;
2693
2694 if (create_heap_objects) {
2695 // Create initial maps.
2696 if (!CreateInitialMaps()) return false;
2697 if (!CreateApiObjects()) return false;
2698
2699 // Create initial objects
2700 if (!CreateInitialObjects()) return false;
2701 }
2702
2703 LOG(IntEvent("heap-capacity", Capacity()));
2704 LOG(IntEvent("heap-available", Available()));
2705
2706 return true;
2707}
2708
2709
2710void Heap::TearDown() {
2711 GlobalHandles::TearDown();
2712
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002713 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002714
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002715 if (old_pointer_space_ != NULL) {
2716 old_pointer_space_->TearDown();
2717 delete old_pointer_space_;
2718 old_pointer_space_ = NULL;
2719 }
2720
2721 if (old_data_space_ != NULL) {
2722 old_data_space_->TearDown();
2723 delete old_data_space_;
2724 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002725 }
2726
2727 if (code_space_ != NULL) {
2728 code_space_->TearDown();
2729 delete code_space_;
2730 code_space_ = NULL;
2731 }
2732
2733 if (map_space_ != NULL) {
2734 map_space_->TearDown();
2735 delete map_space_;
2736 map_space_ = NULL;
2737 }
2738
2739 if (lo_space_ != NULL) {
2740 lo_space_->TearDown();
2741 delete lo_space_;
2742 lo_space_ = NULL;
2743 }
2744
2745 MemoryAllocator::TearDown();
2746}
2747
2748
2749void Heap::Shrink() {
2750 // Try to shrink map, old, and code spaces.
2751 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002752 old_pointer_space_->Shrink();
2753 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002754 code_space_->Shrink();
2755}
2756
2757
2758#ifdef DEBUG
2759
2760class PrintHandleVisitor: public ObjectVisitor {
2761 public:
2762 void VisitPointers(Object** start, Object** end) {
2763 for (Object** p = start; p < end; p++)
2764 PrintF(" handle %p to %p\n", p, *p);
2765 }
2766};
2767
2768void Heap::PrintHandles() {
2769 PrintF("Handles:\n");
2770 PrintHandleVisitor v;
2771 HandleScopeImplementer::Iterate(&v);
2772}
2773
2774#endif
2775
2776
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002777Space* AllSpaces::next() {
2778 switch (counter_++) {
2779 case NEW_SPACE:
2780 return Heap::new_space();
2781 case OLD_POINTER_SPACE:
2782 return Heap::old_pointer_space();
2783 case OLD_DATA_SPACE:
2784 return Heap::old_data_space();
2785 case CODE_SPACE:
2786 return Heap::code_space();
2787 case MAP_SPACE:
2788 return Heap::map_space();
2789 case LO_SPACE:
2790 return Heap::lo_space();
2791 default:
2792 return NULL;
2793 }
2794}
2795
2796
2797PagedSpace* PagedSpaces::next() {
2798 switch (counter_++) {
2799 case OLD_POINTER_SPACE:
2800 return Heap::old_pointer_space();
2801 case OLD_DATA_SPACE:
2802 return Heap::old_data_space();
2803 case CODE_SPACE:
2804 return Heap::code_space();
2805 case MAP_SPACE:
2806 return Heap::map_space();
2807 default:
2808 return NULL;
2809 }
2810}
2811
2812
2813
2814OldSpace* OldSpaces::next() {
2815 switch (counter_++) {
2816 case OLD_POINTER_SPACE:
2817 return Heap::old_pointer_space();
2818 case OLD_DATA_SPACE:
2819 return Heap::old_data_space();
2820 case CODE_SPACE:
2821 return Heap::code_space();
2822 default:
2823 return NULL;
2824 }
2825}
2826
2827
kasper.lund7276f142008-07-30 08:49:36 +00002828SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2829}
2830
2831
2832SpaceIterator::~SpaceIterator() {
2833 // Delete active iterator if any.
2834 delete iterator_;
2835}
2836
2837
2838bool SpaceIterator::has_next() {
2839 // Iterate until no more spaces.
2840 return current_space_ != LAST_SPACE;
2841}
2842
2843
2844ObjectIterator* SpaceIterator::next() {
2845 if (iterator_ != NULL) {
2846 delete iterator_;
2847 iterator_ = NULL;
2848 // Move to the next space
2849 current_space_++;
2850 if (current_space_ > LAST_SPACE) {
2851 return NULL;
2852 }
2853 }
2854
2855 // Return iterator for the new current space.
2856 return CreateIterator();
2857}
2858
2859
2860// Create an iterator for the space to iterate.
2861ObjectIterator* SpaceIterator::CreateIterator() {
2862 ASSERT(iterator_ == NULL);
2863
2864 switch (current_space_) {
2865 case NEW_SPACE:
2866 iterator_ = new SemiSpaceIterator(Heap::new_space());
2867 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002868 case OLD_POINTER_SPACE:
2869 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2870 break;
2871 case OLD_DATA_SPACE:
2872 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002873 break;
2874 case CODE_SPACE:
2875 iterator_ = new HeapObjectIterator(Heap::code_space());
2876 break;
2877 case MAP_SPACE:
2878 iterator_ = new HeapObjectIterator(Heap::map_space());
2879 break;
2880 case LO_SPACE:
2881 iterator_ = new LargeObjectIterator(Heap::lo_space());
2882 break;
2883 }
2884
2885 // Return the newly allocated iterator;
2886 ASSERT(iterator_ != NULL);
2887 return iterator_;
2888}
2889
2890
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002891HeapIterator::HeapIterator() {
2892 Init();
2893}
2894
2895
2896HeapIterator::~HeapIterator() {
2897 Shutdown();
2898}
2899
2900
2901void HeapIterator::Init() {
2902 // Start the iteration.
2903 space_iterator_ = new SpaceIterator();
2904 object_iterator_ = space_iterator_->next();
2905}
2906
2907
2908void HeapIterator::Shutdown() {
2909 // Make sure the last iterator is deallocated.
2910 delete space_iterator_;
2911 space_iterator_ = NULL;
2912 object_iterator_ = NULL;
2913}
2914
2915
2916bool HeapIterator::has_next() {
2917 // No iterator means we are done.
2918 if (object_iterator_ == NULL) return false;
2919
2920 if (object_iterator_->has_next_object()) {
2921 // If the current iterator has more objects we are fine.
2922 return true;
2923 } else {
2924 // Go though the spaces looking for one that has objects.
2925 while (space_iterator_->has_next()) {
2926 object_iterator_ = space_iterator_->next();
2927 if (object_iterator_->has_next_object()) {
2928 return true;
2929 }
2930 }
2931 }
2932 // Done with the last space.
2933 object_iterator_ = NULL;
2934 return false;
2935}
2936
2937
2938HeapObject* HeapIterator::next() {
2939 if (has_next()) {
2940 return object_iterator_->next_object();
2941 } else {
2942 return NULL;
2943 }
2944}
2945
2946
2947void HeapIterator::reset() {
2948 // Restart the iterator.
2949 Shutdown();
2950 Init();
2951}
2952
2953
2954//
2955// HeapProfiler class implementation.
2956//
2957#ifdef ENABLE_LOGGING_AND_PROFILING
2958void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
2959 InstanceType type = obj->map()->instance_type();
2960 ASSERT(0 <= type && type <= LAST_TYPE);
2961 info[type].increment_number(1);
2962 info[type].increment_bytes(obj->Size());
2963}
2964#endif
2965
2966
2967#ifdef ENABLE_LOGGING_AND_PROFILING
2968void HeapProfiler::WriteSample() {
2969 LOG(HeapSampleBeginEvent("Heap", "allocated"));
2970
2971 HistogramInfo info[LAST_TYPE+1];
2972#define DEF_TYPE_NAME(name) info[name].set_name(#name);
2973 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
2974#undef DEF_TYPE_NAME
2975
2976 HeapIterator iterator;
2977 while (iterator.has_next()) {
2978 CollectStats(iterator.next(), info);
2979 }
2980
2981 // Lump all the string types together.
2982 int string_number = 0;
2983 int string_bytes = 0;
2984#define INCREMENT_SIZE(type, size, name) \
2985 string_number += info[type].number(); \
2986 string_bytes += info[type].bytes();
2987 STRING_TYPE_LIST(INCREMENT_SIZE)
2988#undef INCREMENT_SIZE
2989 if (string_bytes > 0) {
2990 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
2991 }
2992
2993 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
2994 if (info[i].bytes() > 0) {
2995 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
2996 info[i].bytes()));
2997 }
2998 }
2999
3000 LOG(HeapSampleEndEvent("Heap", "allocated"));
3001}
3002
3003
3004#endif
3005
3006
3007
3008#ifdef DEBUG
3009
3010static bool search_for_any_global;
3011static Object* search_target;
3012static bool found_target;
3013static List<Object*> object_stack(20);
3014
3015
3016// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3017static const int kMarkTag = 2;
3018
3019static void MarkObjectRecursively(Object** p);
3020class MarkObjectVisitor : public ObjectVisitor {
3021 public:
3022 void VisitPointers(Object** start, Object** end) {
3023 // Copy all HeapObject pointers in [start, end)
3024 for (Object** p = start; p < end; p++) {
3025 if ((*p)->IsHeapObject())
3026 MarkObjectRecursively(p);
3027 }
3028 }
3029};
3030
3031static MarkObjectVisitor mark_visitor;
3032
3033static void MarkObjectRecursively(Object** p) {
3034 if (!(*p)->IsHeapObject()) return;
3035
3036 HeapObject* obj = HeapObject::cast(*p);
3037
3038 Object* map = obj->map();
3039
3040 if (!map->IsHeapObject()) return; // visited before
3041
3042 if (found_target) return; // stop if target found
3043 object_stack.Add(obj);
3044 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3045 (!search_for_any_global && (obj == search_target))) {
3046 found_target = true;
3047 return;
3048 }
3049
3050 if (obj->IsCode()) {
3051 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3052 }
3053
3054 // not visited yet
3055 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3056
3057 Address map_addr = map_p->address();
3058
3059 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3060
3061 MarkObjectRecursively(&map);
3062
3063 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3064 &mark_visitor);
3065
3066 if (!found_target) // don't pop if found the target
3067 object_stack.RemoveLast();
3068}
3069
3070
3071static void UnmarkObjectRecursively(Object** p);
3072class UnmarkObjectVisitor : public ObjectVisitor {
3073 public:
3074 void VisitPointers(Object** start, Object** end) {
3075 // Copy all HeapObject pointers in [start, end)
3076 for (Object** p = start; p < end; p++) {
3077 if ((*p)->IsHeapObject())
3078 UnmarkObjectRecursively(p);
3079 }
3080 }
3081};
3082
3083static UnmarkObjectVisitor unmark_visitor;
3084
3085static void UnmarkObjectRecursively(Object** p) {
3086 if (!(*p)->IsHeapObject()) return;
3087
3088 HeapObject* obj = HeapObject::cast(*p);
3089
3090 Object* map = obj->map();
3091
3092 if (map->IsHeapObject()) return; // unmarked already
3093
3094 Address map_addr = reinterpret_cast<Address>(map);
3095
3096 map_addr -= kMarkTag;
3097
3098 ASSERT_TAG_ALIGNED(map_addr);
3099
3100 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3101
3102 obj->set_map(reinterpret_cast<Map*>(map_p));
3103
3104 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3105
3106 obj->IterateBody(Map::cast(map_p)->instance_type(),
3107 obj->SizeFromMap(Map::cast(map_p)),
3108 &unmark_visitor);
3109
3110 if (obj->IsCode()) {
3111 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3112 }
3113}
3114
3115
3116static void MarkRootObjectRecursively(Object** root) {
3117 if (search_for_any_global) {
3118 ASSERT(search_target == NULL);
3119 } else {
3120 ASSERT(search_target->IsHeapObject());
3121 }
3122 found_target = false;
3123 object_stack.Clear();
3124
3125 MarkObjectRecursively(root);
3126 UnmarkObjectRecursively(root);
3127
3128 if (found_target) {
3129 PrintF("=====================================\n");
3130 PrintF("==== Path to object ====\n");
3131 PrintF("=====================================\n\n");
3132
3133 ASSERT(!object_stack.is_empty());
3134 for (int i = 0; i < object_stack.length(); i++) {
3135 if (i > 0) PrintF("\n |\n |\n V\n\n");
3136 Object* obj = object_stack[i];
3137 obj->Print();
3138 }
3139 PrintF("=====================================\n");
3140 }
3141}
3142
3143
3144// Helper class for visiting HeapObjects recursively.
3145class MarkRootVisitor: public ObjectVisitor {
3146 public:
3147 void VisitPointers(Object** start, Object** end) {
3148 // Visit all HeapObject pointers in [start, end)
3149 for (Object** p = start; p < end; p++) {
3150 if ((*p)->IsHeapObject())
3151 MarkRootObjectRecursively(p);
3152 }
3153 }
3154};
3155
3156
3157// Triggers a depth-first traversal of reachable objects from roots
3158// and finds a path to a specific heap object and prints it.
3159void Heap::TracePathToObject() {
3160 search_target = NULL;
3161 search_for_any_global = false;
3162
3163 MarkRootVisitor root_visitor;
3164 IterateRoots(&root_visitor);
3165}
3166
3167
3168// Triggers a depth-first traversal of reachable objects from roots
3169// and finds a path to any global object and prints it. Useful for
3170// determining the source for leaks of global objects.
3171void Heap::TracePathToGlobal() {
3172 search_target = NULL;
3173 search_for_any_global = true;
3174
3175 MarkRootVisitor root_visitor;
3176 IterateRoots(&root_visitor);
3177}
3178#endif
3179
3180
kasper.lund7276f142008-07-30 08:49:36 +00003181GCTracer::GCTracer()
3182 : start_time_(0.0),
3183 start_size_(0.0),
3184 gc_count_(0),
3185 full_gc_count_(0),
3186 is_compacting_(false),
3187 marked_count_(0) {
3188 // These two fields reflect the state of the previous full collection.
3189 // Set them before they are changed by the collector.
3190 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3191 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3192 if (!FLAG_trace_gc) return;
3193 start_time_ = OS::TimeCurrentMillis();
3194 start_size_ = SizeOfHeapObjects();
3195}
3196
3197
3198GCTracer::~GCTracer() {
3199 if (!FLAG_trace_gc) return;
3200 // Printf ONE line iff flag is set.
3201 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3202 CollectorString(),
3203 start_size_, SizeOfHeapObjects(),
3204 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3205}
3206
3207
3208const char* GCTracer::CollectorString() {
3209 switch (collector_) {
3210 case SCAVENGER:
3211 return "Scavenge";
3212 case MARK_COMPACTOR:
3213 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3214 : "Mark-sweep";
3215 }
3216 return "Unknown GC";
3217}
3218
3219
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003220#ifdef DEBUG
3221bool Heap::GarbageCollectionGreedyCheck() {
3222 ASSERT(FLAG_gc_greedy);
3223 if (Bootstrapper::IsActive()) return true;
3224 if (disallow_allocation_failure()) return true;
3225 return CollectGarbage(0, NEW_SPACE);
3226}
3227#endif
3228
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003229} } // namespace v8::internal