blob: 72f427ec564d325a21fd6d78cf4d7b154b705253 [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
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000393 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394
kasper.lund7276f142008-07-30 08:49:36 +0000395 if (collector == MARK_COMPACTOR) {
396 // Register the amount of external allocated memory.
397 amount_of_external_allocated_memory_at_last_global_gc_ =
398 amount_of_external_allocated_memory_;
399 }
400
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000401 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
402 ASSERT(!allocation_allowed_);
403 global_gc_epilogue_callback_();
404 }
405}
406
407
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000408void Heap::PostGarbageCollectionProcessing() {
409 // Process weak handles post gc.
410 GlobalHandles::PostGarbageCollectionProcessing();
411 // Update flat string readers.
412 FlatStringReader::PostGarbageCollectionProcessing();
413}
414
415
kasper.lund7276f142008-07-30 08:49:36 +0000416void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000419 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 LOG(ResourceEvent("markcompact", "begin"));
421
422 MarkCompactPrologue();
423
kasper.lund7276f142008-07-30 08:49:36 +0000424 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000425
426 MarkCompactEpilogue();
427
428 LOG(ResourceEvent("markcompact", "end"));
429
430 gc_state_ = NOT_IN_GC;
431
432 Shrink();
433
434 Counters::objs_since_last_full.Set(0);
435}
436
437
438void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000439 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000440 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000441 RegExpImpl::OldSpaceCollectionPrologue();
442 Top::MarkCompactPrologue();
443 ThreadManager::MarkCompactPrologue();
444}
445
446
447void Heap::MarkCompactEpilogue() {
448 Top::MarkCompactEpilogue();
449 ThreadManager::MarkCompactEpilogue();
450}
451
452
453Object* Heap::FindCodeObject(Address a) {
454 Object* obj = code_space_->FindObject(a);
455 if (obj->IsFailure()) {
456 obj = lo_space_->FindObject(a);
457 }
kasper.lund7276f142008-07-30 08:49:36 +0000458 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000459 return obj;
460}
461
462
463// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000464class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465 public:
466
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000467 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468
469 void VisitPointers(Object** start, Object** end) {
470 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000471 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472 }
473
474 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000475 void ScavengePointer(Object** p) {
476 Object* object = *p;
477 if (!Heap::InNewSpace(object)) return;
478 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
479 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480 }
481};
482
483
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000484// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000485static Address promoted_top = NULL;
486
487
488#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000489// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000490// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000491class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492 public:
493 void VisitPointers(Object** start, Object**end) {
494 for (Object** current = start; current < end; current++) {
495 if ((*current)->IsHeapObject()) {
496 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
497 }
498 }
499 }
500};
501#endif
502
503void Heap::Scavenge() {
504#ifdef DEBUG
505 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000506 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 HeapObjectIterator it(code_space_);
508 while (it.has_next()) {
509 HeapObject* object = it.next();
510 if (object->IsCode()) {
511 Code::cast(object)->ConvertICTargetsFromAddressToObject();
512 }
513 object->Iterate(&v);
514 if (object->IsCode()) {
515 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
516 }
517 }
518 }
519#endif
520
521 gc_state_ = SCAVENGE;
522
523 // Implements Cheney's copying algorithm
524 LOG(ResourceEvent("scavenge", "begin"));
525
526 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000527 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528 scavenge_count_ > new_space_growth_limit_) {
529 // Double the size of the new space, and double the limit. The next
530 // doubling attempt will occur after the current new_space_growth_limit_
531 // more collections.
532 // TODO(1240712): NewSpace::Double has a return value which is
533 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000534 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000535 new_space_growth_limit_ *= 2;
536 }
537
538 // Flip the semispaces. After flipping, to space is empty, from space has
539 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000540 new_space_.Flip();
541 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000542
543 // We need to sweep newly copied objects which can be in either the to space
544 // or the old space. For to space objects, we use a mark. Newly copied
545 // objects lie between the mark and the allocation top. For objects
546 // promoted to old space, we write their addresses downward from the top of
547 // the new space. Sweeping newly promoted objects requires an allocation
548 // pointer and a mark. Note that the allocation pointer 'top' actually
549 // moves downward from the high address in the to space.
550 //
551 // There is guaranteed to be enough room at the top of the to space for the
552 // addresses of promoted objects: every object promoted frees up its size in
553 // bytes from the top of the new space, and objects are at least one pointer
554 // in size. Using the new space to record promoted addresses makes the
555 // scavenge collector agnostic to the allocation strategy (eg, linear or
556 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000557 Address new_mark = new_space_.ToSpaceLow();
558 Address promoted_mark = new_space_.ToSpaceHigh();
559 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000560
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000561 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000563 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564
565 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000566 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000567 IterateRSet(old_pointer_space_, &ScavengePointer);
568 IterateRSet(map_space_, &ScavengePointer);
569 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570
571 bool has_processed_weak_pointers = false;
572
573 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000574 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000575 ASSERT(promoted_mark >= promoted_top);
576
577 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000578 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 // Sweep newly copied objects in the to space. The allocation pointer
580 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000581 Address previous_top = new_space_.top();
582 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000583 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000584 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 }
586 new_mark = previous_top;
587
588 // Sweep newly copied objects in the old space. The promotion 'top'
589 // pointer could change during sweeping.
590 previous_top = promoted_top;
591 for (Address current = promoted_mark - kPointerSize;
592 current >= previous_top;
593 current -= kPointerSize) {
594 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000595 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000596 UpdateRSet(object);
597 }
598 promoted_mark = previous_top;
599 }
600
601 if (has_processed_weak_pointers) break; // We are done.
602 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000603 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604 has_processed_weak_pointers = true;
605 }
606
607 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000608 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000609
610 LOG(ResourceEvent("scavenge", "end"));
611
612 gc_state_ = NOT_IN_GC;
613}
614
615
616void Heap::ClearRSetRange(Address start, int size_in_bytes) {
617 uint32_t start_bit;
618 Address start_word_address =
619 Page::ComputeRSetBitPosition(start, 0, &start_bit);
620 uint32_t end_bit;
621 Address end_word_address =
622 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
623 0,
624 &end_bit);
625
626 // We want to clear the bits in the starting word starting with the
627 // first bit, and in the ending word up to and including the last
628 // bit. Build a pair of bitmasks to do that.
629 uint32_t start_bitmask = start_bit - 1;
630 uint32_t end_bitmask = ~((end_bit << 1) - 1);
631
632 // If the start address and end address are the same, we mask that
633 // word once, otherwise mask the starting and ending word
634 // separately and all the ones in between.
635 if (start_word_address == end_word_address) {
636 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
637 } else {
638 Memory::uint32_at(start_word_address) &= start_bitmask;
639 Memory::uint32_at(end_word_address) &= end_bitmask;
640 start_word_address += kIntSize;
641 memset(start_word_address, 0, end_word_address - start_word_address);
642 }
643}
644
645
646class UpdateRSetVisitor: public ObjectVisitor {
647 public:
648
649 void VisitPointer(Object** p) {
650 UpdateRSet(p);
651 }
652
653 void VisitPointers(Object** start, Object** end) {
654 // Update a store into slots [start, end), used (a) to update remembered
655 // set when promoting a young object to old space or (b) to rebuild
656 // remembered sets after a mark-compact collection.
657 for (Object** p = start; p < end; p++) UpdateRSet(p);
658 }
659 private:
660
661 void UpdateRSet(Object** p) {
662 // The remembered set should not be set. It should be clear for objects
663 // newly copied to old space, and it is cleared before rebuilding in the
664 // mark-compact collector.
665 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
666 if (Heap::InNewSpace(*p)) {
667 Page::SetRSet(reinterpret_cast<Address>(p), 0);
668 }
669 }
670};
671
672
673int Heap::UpdateRSet(HeapObject* obj) {
674 ASSERT(!InNewSpace(obj));
675 // Special handling of fixed arrays to iterate the body based on the start
676 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
677 // will not work because Page::SetRSet needs to have the start of the
678 // object.
679 if (obj->IsFixedArray()) {
680 FixedArray* array = FixedArray::cast(obj);
681 int length = array->length();
682 for (int i = 0; i < length; i++) {
683 int offset = FixedArray::kHeaderSize + i * kPointerSize;
684 ASSERT(!Page::IsRSetSet(obj->address(), offset));
685 if (Heap::InNewSpace(array->get(i))) {
686 Page::SetRSet(obj->address(), offset);
687 }
688 }
689 } else if (!obj->IsCode()) {
690 // Skip code object, we know it does not contain inter-generational
691 // pointers.
692 UpdateRSetVisitor v;
693 obj->Iterate(&v);
694 }
695 return obj->Size();
696}
697
698
699void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000700 // By definition, we do not care about remembered set bits in code or data
701 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702 map_space_->ClearRSet();
703 RebuildRSets(map_space_);
704
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000705 old_pointer_space_->ClearRSet();
706 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707
708 Heap::lo_space_->ClearRSet();
709 RebuildRSets(lo_space_);
710}
711
712
713void Heap::RebuildRSets(PagedSpace* space) {
714 HeapObjectIterator it(space);
715 while (it.has_next()) Heap::UpdateRSet(it.next());
716}
717
718
719void Heap::RebuildRSets(LargeObjectSpace* space) {
720 LargeObjectIterator it(space);
721 while (it.has_next()) Heap::UpdateRSet(it.next());
722}
723
724
725#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
726void Heap::RecordCopiedObject(HeapObject* obj) {
727 bool should_record = false;
728#ifdef DEBUG
729 should_record = FLAG_heap_stats;
730#endif
731#ifdef ENABLE_LOGGING_AND_PROFILING
732 should_record = should_record || FLAG_log_gc;
733#endif
734 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000735 if (new_space_.Contains(obj)) {
736 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000738 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 }
740 }
741}
742#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
743
744
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000745
746HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000747 HeapObject* target,
748 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000749 // Copy the content of source to target.
750 CopyBlock(reinterpret_cast<Object**>(target->address()),
751 reinterpret_cast<Object**>(source->address()),
752 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753
kasper.lund7276f142008-07-30 08:49:36 +0000754 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000755 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000756
757 // Update NewSpace stats if necessary.
758#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
759 RecordCopiedObject(target);
760#endif
761
762 return target;
763}
764
765
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000766// Inlined function.
767void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
768 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000769
kasper.lund7276f142008-07-30 08:49:36 +0000770 // We use the first word (where the map pointer usually is) of a heap
771 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000772 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000774 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775
kasper.lund7276f142008-07-30 08:49:36 +0000776 // If the first word is a forwarding address, the object has already been
777 // copied.
778 if (first_word.IsForwardingAddress()) {
779 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000780 return;
781 }
782
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000783 // Call the slow part of scavenge object.
784 return ScavengeObjectSlow(p, object);
785}
786
ager@chromium.org870a0b62008-11-04 11:43:05 +0000787
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000788static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000789 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000790 // is a candidate for being shortcut by the scavenger.
791 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000792 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
ager@chromium.orgc3e50d82008-11-05 11:53:10 +0000793 return (StringShape(map).representation_tag() == kConsStringTag) &&
ager@chromium.org870a0b62008-11-04 11:43:05 +0000794 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000795}
796
797
798void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
799 ASSERT(InFromSpace(object));
800 MapWord first_word = object->map_word();
801 ASSERT(!first_word.IsForwardingAddress());
802
803 // Optimization: Bypass flattened ConsString objects.
804 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000805 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000806 *p = object;
807 // After patching *p we have to repeat the checks that object is in the
808 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000809 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000810 first_word = object->map_word();
811 if (first_word.IsForwardingAddress()) {
812 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000813 return;
814 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000815 }
816
kasper.lund7276f142008-07-30 08:49:36 +0000817 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000818 // If the object should be promoted, we try to copy it to old space.
819 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000820 OldSpace* target_space = Heap::TargetSpace(object);
821 ASSERT(target_space == Heap::old_pointer_space_ ||
822 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000823 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000824 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000825 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000826 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000827 // Record the object's address at the top of the to space, to allow
828 // it to be swept by the scavenger.
829 promoted_top -= kPointerSize;
830 Memory::Object_at(promoted_top) = *p;
831 } else {
832#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000833 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000835 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 (*p)->Iterate(&v);
837#endif
838 }
839 return;
840 }
841 }
842
843 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000844 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845 // Failed allocation at this point is utterly unexpected.
846 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000847 *p = MigrateObject(object, HeapObject::cast(result), object_size);
848}
849
850
851void Heap::ScavengePointer(HeapObject** p) {
852 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000853}
854
855
856Object* Heap::AllocatePartialMap(InstanceType instance_type,
857 int instance_size) {
858 Object* result = AllocateRawMap(Map::kSize);
859 if (result->IsFailure()) return result;
860
861 // Map::cast cannot be used due to uninitialized map field.
862 reinterpret_cast<Map*>(result)->set_map(meta_map());
863 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
864 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000865 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000866 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
867 return result;
868}
869
870
871Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
872 Object* result = AllocateRawMap(Map::kSize);
873 if (result->IsFailure()) return result;
874
875 Map* map = reinterpret_cast<Map*>(result);
876 map->set_map(meta_map());
877 map->set_instance_type(instance_type);
878 map->set_prototype(null_value());
879 map->set_constructor(null_value());
880 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000881 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000882 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000883 map->set_code_cache(empty_fixed_array());
884 map->set_unused_property_fields(0);
885 map->set_bit_field(0);
886 return map;
887}
888
889
890bool Heap::CreateInitialMaps() {
891 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
892 if (obj->IsFailure()) return false;
893
894 // Map::cast cannot be used due to uninitialized map field.
895 meta_map_ = reinterpret_cast<Map*>(obj);
896 meta_map()->set_map(meta_map());
897
898 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
899 if (obj->IsFailure()) return false;
900 fixed_array_map_ = Map::cast(obj);
901
902 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
903 if (obj->IsFailure()) return false;
904 oddball_map_ = Map::cast(obj);
905
906 // Allocate the empty array
907 obj = AllocateEmptyFixedArray();
908 if (obj->IsFailure()) return false;
909 empty_fixed_array_ = FixedArray::cast(obj);
910
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000911 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000912 if (obj->IsFailure()) return false;
913 null_value_ = obj;
914
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000915 // Allocate the empty descriptor array. AllocateMap can now be used.
916 obj = AllocateEmptyFixedArray();
917 if (obj->IsFailure()) return false;
918 // There is a check against empty_descriptor_array() in cast().
919 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000920
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000921 // Fix the instance_descriptors for the existing maps.
922 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000923 meta_map()->set_code_cache(empty_fixed_array());
924
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000925 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000926 fixed_array_map()->set_code_cache(empty_fixed_array());
927
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000928 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000929 oddball_map()->set_code_cache(empty_fixed_array());
930
931 // Fix prototype object for existing maps.
932 meta_map()->set_prototype(null_value());
933 meta_map()->set_constructor(null_value());
934
935 fixed_array_map()->set_prototype(null_value());
936 fixed_array_map()->set_constructor(null_value());
937 oddball_map()->set_prototype(null_value());
938 oddball_map()->set_constructor(null_value());
939
940 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
941 if (obj->IsFailure()) return false;
942 heap_number_map_ = Map::cast(obj);
943
944 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
945 if (obj->IsFailure()) return false;
946 proxy_map_ = Map::cast(obj);
947
948#define ALLOCATE_STRING_MAP(type, size, name) \
949 obj = AllocateMap(type, size); \
950 if (obj->IsFailure()) return false; \
951 name##_map_ = Map::cast(obj);
952 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
953#undef ALLOCATE_STRING_MAP
954
ager@chromium.org7c537e22008-10-16 08:43:32 +0000955 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000956 if (obj->IsFailure()) return false;
957 undetectable_short_string_map_ = Map::cast(obj);
958 undetectable_short_string_map_->set_is_undetectable();
959
ager@chromium.org7c537e22008-10-16 08:43:32 +0000960 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000961 if (obj->IsFailure()) return false;
962 undetectable_medium_string_map_ = Map::cast(obj);
963 undetectable_medium_string_map_->set_is_undetectable();
964
ager@chromium.org7c537e22008-10-16 08:43:32 +0000965 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000966 if (obj->IsFailure()) return false;
967 undetectable_long_string_map_ = Map::cast(obj);
968 undetectable_long_string_map_->set_is_undetectable();
969
ager@chromium.org7c537e22008-10-16 08:43:32 +0000970 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000971 if (obj->IsFailure()) return false;
972 undetectable_short_ascii_string_map_ = Map::cast(obj);
973 undetectable_short_ascii_string_map_->set_is_undetectable();
974
ager@chromium.org7c537e22008-10-16 08:43:32 +0000975 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000976 if (obj->IsFailure()) return false;
977 undetectable_medium_ascii_string_map_ = Map::cast(obj);
978 undetectable_medium_ascii_string_map_->set_is_undetectable();
979
ager@chromium.org7c537e22008-10-16 08:43:32 +0000980 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000981 if (obj->IsFailure()) return false;
982 undetectable_long_ascii_string_map_ = Map::cast(obj);
983 undetectable_long_ascii_string_map_->set_is_undetectable();
984
985 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
986 if (obj->IsFailure()) return false;
987 byte_array_map_ = Map::cast(obj);
988
989 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
990 if (obj->IsFailure()) return false;
991 code_map_ = Map::cast(obj);
992
993 obj = AllocateMap(FILLER_TYPE, kPointerSize);
994 if (obj->IsFailure()) return false;
995 one_word_filler_map_ = Map::cast(obj);
996
997 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
998 if (obj->IsFailure()) return false;
999 two_word_filler_map_ = Map::cast(obj);
1000
1001#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1002 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1003 if (obj->IsFailure()) return false; \
1004 name##_map_ = Map::cast(obj);
1005 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1006#undef ALLOCATE_STRUCT_MAP
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 hash_table_map_ = Map::cast(obj);
1011
ager@chromium.org236ad962008-09-25 09:45:57 +00001012 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 if (obj->IsFailure()) return false;
1014 context_map_ = Map::cast(obj);
1015
ager@chromium.org236ad962008-09-25 09:45:57 +00001016 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001017 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001018 catch_context_map_ = Map::cast(obj);
1019
1020 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1021 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 global_context_map_ = Map::cast(obj);
1023
1024 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1025 if (obj->IsFailure()) return false;
1026 boilerplate_function_map_ = Map::cast(obj);
1027
1028 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1029 if (obj->IsFailure()) return false;
1030 shared_function_info_map_ = Map::cast(obj);
1031
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001032 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001033 return true;
1034}
1035
1036
1037Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1038 // Statically ensure that it is safe to allocate heap numbers in paged
1039 // spaces.
1040 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001041 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001042 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001043 if (result->IsFailure()) return result;
1044
1045 HeapObject::cast(result)->set_map(heap_number_map());
1046 HeapNumber::cast(result)->set_value(value);
1047 return result;
1048}
1049
1050
1051Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001052 // Use general version, if we're forced to always allocate.
1053 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001054 // This version of AllocateHeapNumber is optimized for
1055 // allocation in new space.
1056 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1057 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001058 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001059 if (result->IsFailure()) return result;
1060 HeapObject::cast(result)->set_map(heap_number_map());
1061 HeapNumber::cast(result)->set_value(value);
1062 return result;
1063}
1064
1065
1066Object* Heap::CreateOddball(Map* map,
1067 const char* to_string,
1068 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001069 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001070 if (result->IsFailure()) return result;
1071 return Oddball::cast(result)->Initialize(to_string, to_number);
1072}
1073
1074
1075bool Heap::CreateApiObjects() {
1076 Object* obj;
1077
1078 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1079 if (obj->IsFailure()) return false;
1080 neander_map_ = Map::cast(obj);
1081
1082 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1083 if (obj->IsFailure()) return false;
1084 Object* elements = AllocateFixedArray(2);
1085 if (elements->IsFailure()) return false;
1086 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1087 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1088 message_listeners_ = JSObject::cast(obj);
1089
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001090 return true;
1091}
1092
1093void Heap::CreateFixedStubs() {
1094 // Here we create roots for fixed stubs. They are needed at GC
1095 // for cooking and uncooking (check out frames.cc).
1096 // The eliminates the need for doing dictionary lookup in the
1097 // stub cache for these stubs.
1098 HandleScope scope;
1099 {
1100 CEntryStub stub;
1101 c_entry_code_ = *stub.GetCode();
1102 }
1103 {
1104 CEntryDebugBreakStub stub;
1105 c_entry_debug_break_code_ = *stub.GetCode();
1106 }
1107 {
1108 JSEntryStub stub;
1109 js_entry_code_ = *stub.GetCode();
1110 }
1111 {
1112 JSConstructEntryStub stub;
1113 js_construct_entry_code_ = *stub.GetCode();
1114 }
1115}
1116
1117
1118bool Heap::CreateInitialObjects() {
1119 Object* obj;
1120
1121 // The -0 value must be set before NumberFromDouble works.
1122 obj = AllocateHeapNumber(-0.0, TENURED);
1123 if (obj->IsFailure()) return false;
1124 minus_zero_value_ = obj;
1125 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1126
1127 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1128 if (obj->IsFailure()) return false;
1129 nan_value_ = obj;
1130
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001131 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001132 if (obj->IsFailure()) return false;
1133 undefined_value_ = obj;
1134 ASSERT(!InNewSpace(undefined_value()));
1135
1136 // Allocate initial symbol table.
1137 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1138 if (obj->IsFailure()) return false;
1139 symbol_table_ = obj;
1140
1141 // Assign the print strings for oddballs after creating symboltable.
1142 Object* symbol = LookupAsciiSymbol("undefined");
1143 if (symbol->IsFailure()) return false;
1144 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1145 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1146
1147 // Assign the print strings for oddballs after creating symboltable.
1148 symbol = LookupAsciiSymbol("null");
1149 if (symbol->IsFailure()) return false;
1150 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1151 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1152
1153 // Allocate the null_value
1154 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1155 if (obj->IsFailure()) return false;
1156
1157 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1158 if (obj->IsFailure()) return false;
1159 true_value_ = obj;
1160
1161 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1162 if (obj->IsFailure()) return false;
1163 false_value_ = obj;
1164
1165 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1166 if (obj->IsFailure()) return false;
1167 the_hole_value_ = obj;
1168
1169 // Allocate the empty string.
1170 obj = AllocateRawAsciiString(0, TENURED);
1171 if (obj->IsFailure()) return false;
1172 empty_string_ = String::cast(obj);
1173
1174#define SYMBOL_INITIALIZE(name, string) \
1175 obj = LookupAsciiSymbol(string); \
1176 if (obj->IsFailure()) return false; \
1177 (name##_) = String::cast(obj);
1178 SYMBOL_LIST(SYMBOL_INITIALIZE)
1179#undef SYMBOL_INITIALIZE
1180
1181 // Allocate the proxy for __proto__.
1182 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1183 if (obj->IsFailure()) return false;
1184 prototype_accessors_ = Proxy::cast(obj);
1185
1186 // Allocate the code_stubs dictionary.
1187 obj = Dictionary::Allocate(4);
1188 if (obj->IsFailure()) return false;
1189 code_stubs_ = Dictionary::cast(obj);
1190
1191 // Allocate the non_monomorphic_cache used in stub-cache.cc
1192 obj = Dictionary::Allocate(4);
1193 if (obj->IsFailure()) return false;
1194 non_monomorphic_cache_ = Dictionary::cast(obj);
1195
1196 CreateFixedStubs();
1197
1198 // Allocate the number->string conversion cache
1199 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1200 if (obj->IsFailure()) return false;
1201 number_string_cache_ = FixedArray::cast(obj);
1202
1203 // Allocate cache for single character strings.
1204 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1205 if (obj->IsFailure()) return false;
1206 single_character_string_cache_ = FixedArray::cast(obj);
1207
1208 // Allocate cache for external strings pointing to native source code.
1209 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1210 if (obj->IsFailure()) return false;
1211 natives_source_cache_ = FixedArray::cast(obj);
1212
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001213 // Initialize keyed lookup cache.
1214 ClearKeyedLookupCache();
1215
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001216 // Initialize compilation cache.
1217 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001218
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001219 return true;
1220}
1221
1222
1223static inline int double_get_hash(double d) {
1224 DoubleRepresentation rep(d);
1225 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1226 (Heap::kNumberStringCacheSize - 1));
1227}
1228
1229
1230static inline int smi_get_hash(Smi* smi) {
1231 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1232}
1233
1234
1235
1236Object* Heap::GetNumberStringCache(Object* number) {
1237 int hash;
1238 if (number->IsSmi()) {
1239 hash = smi_get_hash(Smi::cast(number));
1240 } else {
1241 hash = double_get_hash(number->Number());
1242 }
1243 Object* key = number_string_cache_->get(hash * 2);
1244 if (key == number) {
1245 return String::cast(number_string_cache_->get(hash * 2 + 1));
1246 } else if (key->IsHeapNumber() &&
1247 number->IsHeapNumber() &&
1248 key->Number() == number->Number()) {
1249 return String::cast(number_string_cache_->get(hash * 2 + 1));
1250 }
1251 return undefined_value();
1252}
1253
1254
1255void Heap::SetNumberStringCache(Object* number, String* string) {
1256 int hash;
1257 if (number->IsSmi()) {
1258 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001259 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001260 } else {
1261 hash = double_get_hash(number->Number());
1262 number_string_cache_->set(hash * 2, number);
1263 }
1264 number_string_cache_->set(hash * 2 + 1, string);
1265}
1266
1267
1268Object* Heap::SmiOrNumberFromDouble(double value,
1269 bool new_object,
1270 PretenureFlag pretenure) {
1271 // We need to distinguish the minus zero value and this cannot be
1272 // done after conversion to int. Doing this by comparing bit
1273 // patterns is faster than using fpclassify() et al.
1274 static const DoubleRepresentation plus_zero(0.0);
1275 static const DoubleRepresentation minus_zero(-0.0);
1276 static const DoubleRepresentation nan(OS::nan_value());
1277 ASSERT(minus_zero_value_ != NULL);
1278 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1279
1280 DoubleRepresentation rep(value);
1281 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1282 if (rep.bits == minus_zero.bits) {
1283 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1284 : minus_zero_value_;
1285 }
1286 if (rep.bits == nan.bits) {
1287 return new_object
1288 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1289 : nan_value_;
1290 }
1291
1292 // Try to represent the value as a tagged small integer.
1293 int int_value = FastD2I(value);
1294 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1295 return Smi::FromInt(int_value);
1296 }
1297
1298 // Materialize the value in the heap.
1299 return AllocateHeapNumber(value, pretenure);
1300}
1301
1302
1303Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1304 return SmiOrNumberFromDouble(value,
1305 true /* number object must be new */,
1306 pretenure);
1307}
1308
1309
1310Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1311 return SmiOrNumberFromDouble(value,
1312 false /* use preallocated NaN, -0.0 */,
1313 pretenure);
1314}
1315
1316
1317Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1318 // Statically ensure that it is safe to allocate proxies in paged spaces.
1319 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001320 AllocationSpace space =
1321 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001322 Object* result = Allocate(proxy_map(), space);
1323 if (result->IsFailure()) return result;
1324
1325 Proxy::cast(result)->set_proxy(proxy);
1326 return result;
1327}
1328
1329
1330Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1331 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1332 if (result->IsFailure()) return result;
1333
1334 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1335 share->set_name(name);
1336 Code* illegal = Builtins::builtin(Builtins::Illegal);
1337 share->set_code(illegal);
1338 share->set_expected_nof_properties(0);
1339 share->set_length(0);
1340 share->set_formal_parameter_count(0);
1341 share->set_instance_class_name(Object_symbol());
1342 share->set_function_data(undefined_value());
1343 share->set_lazy_load_data(undefined_value());
1344 share->set_script(undefined_value());
1345 share->set_start_position_and_type(0);
1346 share->set_debug_info(undefined_value());
1347 return result;
1348}
1349
1350
ager@chromium.org870a0b62008-11-04 11:43:05 +00001351Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001352 String* second) {
1353 StringShape first_shape(first);
1354 StringShape second_shape(second);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001355 int first_length = first->length(first_shape);
1356 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001357 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001358 bool is_ascii = first_shape.IsAsciiRepresentation()
1359 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360
1361 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001362 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001363 ASSERT(first->IsFlat(first_shape));
1364 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001365 if (is_ascii) {
1366 Object* result = AllocateRawAsciiString(length);
1367 if (result->IsFailure()) return result;
1368 // Copy the characters into the new object.
1369 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001370 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1371 String::WriteToFlat(second,
1372 second_shape,
1373 dest + first_length,
1374 0,
1375 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001376 return result;
1377 } else {
1378 Object* result = AllocateRawTwoByteString(length);
1379 if (result->IsFailure()) return result;
1380 // Copy the characters into the new object.
1381 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001382 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1383 String::WriteToFlat(second,
1384 second_shape,
1385 dest + first_length,
1386 0,
1387 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001388 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001390 }
1391
1392 Map* map;
1393 if (length <= String::kMaxShortStringSize) {
1394 map = is_ascii ? short_cons_ascii_string_map()
1395 : short_cons_string_map();
1396 } else if (length <= String::kMaxMediumStringSize) {
1397 map = is_ascii ? medium_cons_ascii_string_map()
1398 : medium_cons_string_map();
1399 } else {
1400 map = is_ascii ? long_cons_ascii_string_map()
1401 : long_cons_string_map();
1402 }
1403
1404 Object* result = Allocate(map, NEW_SPACE);
1405 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001406 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001407 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001408 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1409 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001410 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001411 return result;
1412}
1413
1414
ager@chromium.org870a0b62008-11-04 11:43:05 +00001415Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001416 int start,
1417 int end) {
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001418 StringShape buffer_shape(buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001419 int length = end - start;
1420
1421 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001422 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001423 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001424 }
1425
1426 Map* map;
1427 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001428 map = buffer_shape.IsAsciiRepresentation() ?
1429 short_sliced_ascii_string_map() :
1430 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001431 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001432 map = buffer_shape.IsAsciiRepresentation() ?
1433 medium_sliced_ascii_string_map() :
1434 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001435 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001436 map = buffer_shape.IsAsciiRepresentation() ?
1437 long_sliced_ascii_string_map() :
1438 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001439 }
1440
1441 Object* result = Allocate(map, NEW_SPACE);
1442 if (result->IsFailure()) return result;
1443
1444 SlicedString* sliced_string = SlicedString::cast(result);
1445 sliced_string->set_buffer(buffer);
1446 sliced_string->set_start(start);
1447 sliced_string->set_length(length);
1448
1449 return result;
1450}
1451
1452
ager@chromium.org870a0b62008-11-04 11:43:05 +00001453Object* Heap::AllocateSubString(String* buffer,
1454 StringShape buffer_shape,
1455 int start,
1456 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001457 int length = end - start;
1458
ager@chromium.org7c537e22008-10-16 08:43:32 +00001459 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001460 return Heap::LookupSingleCharacterStringFromCode(
1461 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001462 }
1463
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001464 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001465 if (!buffer->IsFlat(buffer_shape)) {
1466 buffer->TryFlatten(buffer_shape);
1467 buffer_shape = StringShape(buffer);
1468 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001469
ager@chromium.org870a0b62008-11-04 11:43:05 +00001470 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001471 ? AllocateRawAsciiString(length)
1472 : AllocateRawTwoByteString(length);
1473 if (result->IsFailure()) return result;
1474
1475 // Copy the characters into the new object.
1476 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001477 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001478 StringHasher hasher(length);
1479 int i = 0;
1480 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001481 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001482 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001483 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001484 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001485 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001486 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001487 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001488 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001489 }
1490 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001491 return result;
1492}
1493
1494
1495Object* Heap::AllocateExternalStringFromAscii(
1496 ExternalAsciiString::Resource* resource) {
1497 Map* map;
1498 int length = resource->length();
1499 if (length <= String::kMaxShortStringSize) {
1500 map = short_external_ascii_string_map();
1501 } else if (length <= String::kMaxMediumStringSize) {
1502 map = medium_external_ascii_string_map();
1503 } else {
1504 map = long_external_ascii_string_map();
1505 }
1506
1507 Object* result = Allocate(map, NEW_SPACE);
1508 if (result->IsFailure()) return result;
1509
1510 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1511 external_string->set_length(length);
1512 external_string->set_resource(resource);
1513
1514 return result;
1515}
1516
1517
1518Object* Heap::AllocateExternalStringFromTwoByte(
1519 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001520 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001521
ager@chromium.org6f10e412009-02-13 10:11:16 +00001522 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001523 Object* result = Allocate(map, NEW_SPACE);
1524 if (result->IsFailure()) return result;
1525
1526 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1527 external_string->set_length(length);
1528 external_string->set_resource(resource);
1529
1530 return result;
1531}
1532
1533
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001534Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001535 if (code <= String::kMaxAsciiCharCode) {
1536 Object* value = Heap::single_character_string_cache()->get(code);
1537 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001538
1539 char buffer[1];
1540 buffer[0] = static_cast<char>(code);
1541 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1542
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001543 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001544 Heap::single_character_string_cache()->set(code, result);
1545 return result;
1546 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001547
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001548 Object* result = Heap::AllocateRawTwoByteString(1);
1549 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001550 String* answer = String::cast(result);
1551 answer->Set(StringShape(answer), 0, code);
1552 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553}
1554
1555
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001556Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1557 if (pretenure == NOT_TENURED) {
1558 return AllocateByteArray(length);
1559 }
1560 int size = ByteArray::SizeFor(length);
1561 AllocationSpace space =
1562 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1563
1564 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1565
1566 if (result->IsFailure()) return result;
1567
1568 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1569 reinterpret_cast<Array*>(result)->set_length(length);
1570 return result;
1571}
1572
1573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574Object* Heap::AllocateByteArray(int length) {
1575 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001576 AllocationSpace space =
1577 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001578
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001579 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001580
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001581 if (result->IsFailure()) return result;
1582
1583 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1584 reinterpret_cast<Array*>(result)->set_length(length);
1585 return result;
1586}
1587
1588
ager@chromium.org6f10e412009-02-13 10:11:16 +00001589void Heap::CreateFillerObjectAt(Address addr, int size) {
1590 if (size == 0) return;
1591 HeapObject* filler = HeapObject::FromAddress(addr);
1592 if (size == kPointerSize) {
1593 filler->set_map(Heap::one_word_filler_map());
1594 } else {
1595 filler->set_map(Heap::byte_array_map());
1596 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1597 }
1598}
1599
1600
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001601Object* Heap::CreateCode(const CodeDesc& desc,
1602 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001603 Code::Flags flags,
1604 Code** self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605 // Compute size
1606 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1607 int sinfo_size = 0;
1608 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1609 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001610 Object* result;
1611 if (obj_size > MaxHeapObjectSize()) {
1612 result = lo_space_->AllocateRawCode(obj_size);
1613 } else {
1614 result = code_space_->AllocateRaw(obj_size);
1615 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001616
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001617 if (result->IsFailure()) return result;
1618
1619 // Initialize the object
1620 HeapObject::cast(result)->set_map(code_map());
1621 Code* code = Code::cast(result);
1622 code->set_instruction_size(desc.instr_size);
1623 code->set_relocation_size(desc.reloc_size);
1624 code->set_sinfo_size(sinfo_size);
1625 code->set_flags(flags);
1626 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001627 // Allow self references to created code object.
1628 if (self_reference != NULL) {
1629 *self_reference = code;
1630 }
1631 // Migrate generated code.
1632 // The generated code can contain Object** values (typically from handles)
1633 // that are dereferenced during the copy to point directly to the actual heap
1634 // objects. These pointers can include references to the code object itself,
1635 // through the self_reference parameter.
1636 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001637 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001638 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001639
1640#ifdef DEBUG
1641 code->Verify();
1642#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643 return code;
1644}
1645
1646
1647Object* Heap::CopyCode(Code* code) {
1648 // Allocate an object the same size as the code object.
1649 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001650 Object* result;
1651 if (obj_size > MaxHeapObjectSize()) {
1652 result = lo_space_->AllocateRawCode(obj_size);
1653 } else {
1654 result = code_space_->AllocateRaw(obj_size);
1655 }
1656
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657 if (result->IsFailure()) return result;
1658
1659 // Copy code object.
1660 Address old_addr = code->address();
1661 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001662 CopyBlock(reinterpret_cast<Object**>(new_addr),
1663 reinterpret_cast<Object**>(old_addr),
1664 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665 // Relocate the copy.
1666 Code* new_code = Code::cast(result);
1667 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001668 return new_code;
1669}
1670
1671
1672Object* Heap::Allocate(Map* map, AllocationSpace space) {
1673 ASSERT(gc_state_ == NOT_IN_GC);
1674 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001675 Object* result = AllocateRaw(map->instance_size(),
1676 space,
1677 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001678 if (result->IsFailure()) return result;
1679 HeapObject::cast(result)->set_map(map);
1680 return result;
1681}
1682
1683
1684Object* Heap::InitializeFunction(JSFunction* function,
1685 SharedFunctionInfo* shared,
1686 Object* prototype) {
1687 ASSERT(!prototype->IsMap());
1688 function->initialize_properties();
1689 function->initialize_elements();
1690 function->set_shared(shared);
1691 function->set_prototype_or_initial_map(prototype);
1692 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001693 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001694 return function;
1695}
1696
1697
1698Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001699 // Allocate the prototype. Make sure to use the object function
1700 // from the function's context, since the function can be from a
1701 // different context.
1702 JSFunction* object_function =
1703 function->context()->global_context()->object_function();
1704 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705 if (prototype->IsFailure()) return prototype;
1706 // When creating the prototype for the function we must set its
1707 // constructor to the function.
1708 Object* result =
1709 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1710 function,
1711 DONT_ENUM);
1712 if (result->IsFailure()) return result;
1713 return prototype;
1714}
1715
1716
1717Object* Heap::AllocateFunction(Map* function_map,
1718 SharedFunctionInfo* shared,
1719 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001720 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001721 if (result->IsFailure()) return result;
1722 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1723}
1724
1725
1726Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001727 // To get fast allocation and map sharing for arguments objects we
1728 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001729
1730 // This calls Copy directly rather than using Heap::AllocateRaw so we
1731 // duplicate the check here.
1732 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1733
1734 JSObject* boilerplate =
1735 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001736
1737 // Make the clone.
1738 Map* map = boilerplate->map();
1739 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001740 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001741 if (result->IsFailure()) return result;
1742
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001743 // Copy the content. The arguments boilerplate doesn't have any
1744 // fields that point to new space so it's safe to skip the write
1745 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001746 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1747 reinterpret_cast<Object**>(boilerplate->address()),
1748 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001749
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001750 // Set the two properties.
1751 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001752 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001753 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1754 Smi::FromInt(length),
1755 SKIP_WRITE_BARRIER);
1756
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757 // Check the state of the object
1758 ASSERT(JSObject::cast(result)->HasFastProperties());
1759 ASSERT(JSObject::cast(result)->HasFastElements());
1760
1761 return result;
1762}
1763
1764
1765Object* Heap::AllocateInitialMap(JSFunction* fun) {
1766 ASSERT(!fun->has_initial_map());
1767
ager@chromium.org7c537e22008-10-16 08:43:32 +00001768 // First create a new map with the expected number of properties being
1769 // allocated in-object.
1770 int expected_nof_properties = fun->shared()->expected_nof_properties();
1771 int instance_size = JSObject::kHeaderSize +
1772 expected_nof_properties * kPointerSize;
1773 if (instance_size > JSObject::kMaxInstanceSize) {
1774 instance_size = JSObject::kMaxInstanceSize;
1775 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1776 kPointerSize;
1777 }
1778 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001779 if (map_obj->IsFailure()) return map_obj;
1780
1781 // Fetch or allocate prototype.
1782 Object* prototype;
1783 if (fun->has_instance_prototype()) {
1784 prototype = fun->instance_prototype();
1785 } else {
1786 prototype = AllocateFunctionPrototype(fun);
1787 if (prototype->IsFailure()) return prototype;
1788 }
1789 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001790 map->set_inobject_properties(expected_nof_properties);
1791 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001792 map->set_prototype(prototype);
1793 return map;
1794}
1795
1796
1797void Heap::InitializeJSObjectFromMap(JSObject* obj,
1798 FixedArray* properties,
1799 Map* map) {
1800 obj->set_properties(properties);
1801 obj->initialize_elements();
1802 // TODO(1240798): Initialize the object's body using valid initial values
1803 // according to the object's initial map. For example, if the map's
1804 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1805 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1806 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1807 // verification code has to cope with (temporarily) invalid objects. See
1808 // for example, JSArray::JSArrayVerify).
1809 obj->InitializeBody(map->instance_size());
1810}
1811
1812
1813Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1814 // JSFunctions should be allocated using AllocateFunction to be
1815 // properly initialized.
1816 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1817
1818 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001819 int prop_size = map->unused_property_fields() - map->inobject_properties();
1820 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001821 if (properties->IsFailure()) return properties;
1822
1823 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001824 AllocationSpace space =
1825 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001826 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1827 Object* obj = Allocate(map, space);
1828 if (obj->IsFailure()) return obj;
1829
1830 // Initialize the JSObject.
1831 InitializeJSObjectFromMap(JSObject::cast(obj),
1832 FixedArray::cast(properties),
1833 map);
1834 return obj;
1835}
1836
1837
1838Object* Heap::AllocateJSObject(JSFunction* constructor,
1839 PretenureFlag pretenure) {
1840 // Allocate the initial map if absent.
1841 if (!constructor->has_initial_map()) {
1842 Object* initial_map = AllocateInitialMap(constructor);
1843 if (initial_map->IsFailure()) return initial_map;
1844 constructor->set_initial_map(Map::cast(initial_map));
1845 Map::cast(initial_map)->set_constructor(constructor);
1846 }
1847 // Allocate the object based on the constructors initial map.
1848 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1849}
1850
1851
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001852Object* Heap::CopyJSObject(JSObject* source) {
1853 // Never used to copy functions. If functions need to be copied we
1854 // have to be careful to clear the literals array.
1855 ASSERT(!source->IsJSFunction());
1856
1857 // Make the clone.
1858 Map* map = source->map();
1859 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001860 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001861
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001862 // If we're forced to always allocate, we use the general allocation
1863 // functions which may leave us with an object in old space.
1864 if (always_allocate()) {
1865 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1866 if (clone->IsFailure()) return clone;
1867 Address clone_address = HeapObject::cast(clone)->address();
1868 CopyBlock(reinterpret_cast<Object**>(clone_address),
1869 reinterpret_cast<Object**>(source->address()),
1870 object_size);
1871 // Update write barrier for all fields that lie beyond the header.
1872 for (int offset = JSObject::kHeaderSize;
1873 offset < object_size;
1874 offset += kPointerSize) {
1875 RecordWrite(clone_address, offset);
1876 }
1877 } else {
1878 clone = new_space_.AllocateRaw(object_size);
1879 if (clone->IsFailure()) return clone;
1880 ASSERT(Heap::InNewSpace(clone));
1881 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00001882 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001883 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1884 reinterpret_cast<Object**>(source->address()),
1885 object_size);
1886 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001887
1888 FixedArray* elements = FixedArray::cast(source->elements());
1889 FixedArray* properties = FixedArray::cast(source->properties());
1890 // Update elements if necessary.
1891 if (elements->length()> 0) {
1892 Object* elem = CopyFixedArray(elements);
1893 if (elem->IsFailure()) return elem;
1894 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1895 }
1896 // Update properties if necessary.
1897 if (properties->length() > 0) {
1898 Object* prop = CopyFixedArray(properties);
1899 if (prop->IsFailure()) return prop;
1900 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1901 }
1902 // Return the new clone.
1903 return clone;
1904}
1905
1906
1907Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1908 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001909 // Allocate initial map if absent.
1910 if (!constructor->has_initial_map()) {
1911 Object* initial_map = AllocateInitialMap(constructor);
1912 if (initial_map->IsFailure()) return initial_map;
1913 constructor->set_initial_map(Map::cast(initial_map));
1914 Map::cast(initial_map)->set_constructor(constructor);
1915 }
1916
1917 Map* map = constructor->initial_map();
1918
1919 // Check that the already allocated object has the same size as
1920 // objects allocated using the constructor.
1921 ASSERT(map->instance_size() == object->map()->instance_size());
1922
1923 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001924 int prop_size = map->unused_property_fields() - map->inobject_properties();
1925 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001926 if (properties->IsFailure()) return properties;
1927
1928 // Reset the map for the object.
1929 object->set_map(constructor->initial_map());
1930
1931 // Reinitialize the object from the constructor map.
1932 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1933 return object;
1934}
1935
1936
1937Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1938 PretenureFlag pretenure) {
1939 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1940 if (result->IsFailure()) return result;
1941
1942 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001943 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001944 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001945 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001946 }
1947 return result;
1948}
1949
1950
1951Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1952 PretenureFlag pretenure) {
1953 // Count the number of characters in the UTF-8 string and check if
1954 // it is an ASCII string.
1955 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1956 decoder->Reset(string.start(), string.length());
1957 int chars = 0;
1958 bool is_ascii = true;
1959 while (decoder->has_more()) {
1960 uc32 r = decoder->GetNext();
1961 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1962 chars++;
1963 }
1964
1965 // If the string is ascii, we do not need to convert the characters
1966 // since UTF8 is backwards compatible with ascii.
1967 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1968
1969 Object* result = AllocateRawTwoByteString(chars, pretenure);
1970 if (result->IsFailure()) return result;
1971
1972 // Convert and copy the characters into the new object.
1973 String* string_result = String::cast(result);
1974 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00001975 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001976 for (int i = 0; i < chars; i++) {
1977 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001978 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001979 }
1980 return result;
1981}
1982
1983
1984Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1985 PretenureFlag pretenure) {
1986 // Check if the string is an ASCII string.
1987 int i = 0;
1988 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1989
1990 Object* result;
1991 if (i == string.length()) { // It's an ASCII string.
1992 result = AllocateRawAsciiString(string.length(), pretenure);
1993 } else { // It's not an ASCII string.
1994 result = AllocateRawTwoByteString(string.length(), pretenure);
1995 }
1996 if (result->IsFailure()) return result;
1997
1998 // Copy the characters into the new object, which may be either ASCII or
1999 // UTF-16.
2000 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002001 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002002 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002003 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002004 }
2005 return result;
2006}
2007
2008
2009Map* Heap::SymbolMapForString(String* string) {
2010 // If the string is in new space it cannot be used as a symbol.
2011 if (InNewSpace(string)) return NULL;
2012
2013 // Find the corresponding symbol map for strings.
2014 Map* map = string->map();
2015
2016 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2017 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2018 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2019
2020 if (map == short_string_map()) return short_symbol_map();
2021 if (map == medium_string_map()) return medium_symbol_map();
2022 if (map == long_string_map()) return long_symbol_map();
2023
2024 if (map == short_cons_string_map()) return short_cons_symbol_map();
2025 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2026 if (map == long_cons_string_map()) return long_cons_symbol_map();
2027
2028 if (map == short_cons_ascii_string_map()) {
2029 return short_cons_ascii_symbol_map();
2030 }
2031 if (map == medium_cons_ascii_string_map()) {
2032 return medium_cons_ascii_symbol_map();
2033 }
2034 if (map == long_cons_ascii_string_map()) {
2035 return long_cons_ascii_symbol_map();
2036 }
2037
2038 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002039 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2040 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002041
2042 if (map == short_sliced_ascii_string_map()) {
2043 return short_sliced_ascii_symbol_map();
2044 }
2045 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002046 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002047 }
2048 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002049 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002050 }
2051
ager@chromium.org6f10e412009-02-13 10:11:16 +00002052 if (map == short_external_string_map()) {
2053 return short_external_symbol_map();
2054 }
2055 if (map == medium_external_string_map()) {
2056 return medium_external_symbol_map();
2057 }
2058 if (map == long_external_string_map()) {
2059 return long_external_symbol_map();
2060 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002061
2062 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002063 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002064 }
2065 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002066 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067 }
2068 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002069 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002070 }
2071
2072 // No match found.
2073 return NULL;
2074}
2075
2076
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002077Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2078 int chars,
2079 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002080 // Ensure the chars matches the number of characters in the buffer.
2081 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2082 // Determine whether the string is ascii.
2083 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002084 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002085 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2086 }
2087 buffer->Rewind();
2088
2089 // Compute map and object size.
2090 int size;
2091 Map* map;
2092
2093 if (is_ascii) {
2094 if (chars <= String::kMaxShortStringSize) {
2095 map = short_ascii_symbol_map();
2096 } else if (chars <= String::kMaxMediumStringSize) {
2097 map = medium_ascii_symbol_map();
2098 } else {
2099 map = long_ascii_symbol_map();
2100 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002101 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002102 } else {
2103 if (chars <= String::kMaxShortStringSize) {
2104 map = short_symbol_map();
2105 } else if (chars <= String::kMaxMediumStringSize) {
2106 map = medium_symbol_map();
2107 } else {
2108 map = long_symbol_map();
2109 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002110 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002111 }
2112
2113 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002114 AllocationSpace space =
2115 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002116 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002117 if (result->IsFailure()) return result;
2118
2119 reinterpret_cast<HeapObject*>(result)->set_map(map);
2120 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002121 String* answer = String::cast(result);
2122 StringShape answer_shape(answer);
2123 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002124
ager@chromium.org870a0b62008-11-04 11:43:05 +00002125 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002126
2127 // Fill in the characters.
2128 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002129 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002130 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002131 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002132}
2133
2134
2135Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002136 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002137 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138 if (size > MaxHeapObjectSize()) {
2139 space = LO_SPACE;
2140 }
2141
2142 // Use AllocateRaw rather than Allocate because the object's size cannot be
2143 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002144 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002145 if (result->IsFailure()) return result;
2146
2147 // Determine the map based on the string's length.
2148 Map* map;
2149 if (length <= String::kMaxShortStringSize) {
2150 map = short_ascii_string_map();
2151 } else if (length <= String::kMaxMediumStringSize) {
2152 map = medium_ascii_string_map();
2153 } else {
2154 map = long_ascii_string_map();
2155 }
2156
2157 // Partially initialize the object.
2158 HeapObject::cast(result)->set_map(map);
2159 String::cast(result)->set_length(length);
2160 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2161 return result;
2162}
2163
2164
2165Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002166 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002167 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002168 if (size > MaxHeapObjectSize()) {
2169 space = LO_SPACE;
2170 }
2171
2172 // Use AllocateRaw rather than Allocate because the object's size cannot be
2173 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002174 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002175 if (result->IsFailure()) return result;
2176
2177 // Determine the map based on the string's length.
2178 Map* map;
2179 if (length <= String::kMaxShortStringSize) {
2180 map = short_string_map();
2181 } else if (length <= String::kMaxMediumStringSize) {
2182 map = medium_string_map();
2183 } else {
2184 map = long_string_map();
2185 }
2186
2187 // Partially initialize the object.
2188 HeapObject::cast(result)->set_map(map);
2189 String::cast(result)->set_length(length);
2190 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2191 return result;
2192}
2193
2194
2195Object* Heap::AllocateEmptyFixedArray() {
2196 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002197 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002198 if (result->IsFailure()) return result;
2199 // Initialize the object.
2200 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2201 reinterpret_cast<Array*>(result)->set_length(0);
2202 return result;
2203}
2204
2205
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002206Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002207 // Use the general function if we're forced to always allocate.
2208 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002209 // Allocate the raw data for a fixed array.
2210 int size = FixedArray::SizeFor(length);
2211 return (size > MaxHeapObjectSize())
2212 ? lo_space_->AllocateRawFixedArray(size)
2213 : new_space_.AllocateRaw(size);
2214}
2215
2216
2217Object* Heap::CopyFixedArray(FixedArray* src) {
2218 int len = src->length();
2219 Object* obj = AllocateRawFixedArray(len);
2220 if (obj->IsFailure()) return obj;
2221 if (Heap::InNewSpace(obj)) {
2222 HeapObject* dst = HeapObject::cast(obj);
2223 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2224 reinterpret_cast<Object**>(src->address()),
2225 FixedArray::SizeFor(len));
2226 return obj;
2227 }
2228 HeapObject::cast(obj)->set_map(src->map());
2229 FixedArray* result = FixedArray::cast(obj);
2230 result->set_length(len);
2231 // Copy the content
2232 WriteBarrierMode mode = result->GetWriteBarrierMode();
2233 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2234 return result;
2235}
2236
2237
2238Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002239 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002240 Object* result = AllocateRawFixedArray(length);
2241 if (!result->IsFailure()) {
2242 // Initialize header.
2243 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2244 FixedArray* array = FixedArray::cast(result);
2245 array->set_length(length);
2246 Object* value = undefined_value();
2247 // Initialize body.
2248 for (int index = 0; index < length; index++) {
2249 array->set(index, value, SKIP_WRITE_BARRIER);
2250 }
2251 }
2252 return result;
2253}
2254
2255
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002256Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2257 ASSERT(empty_fixed_array()->IsFixedArray());
2258 if (length == 0) return empty_fixed_array();
2259
2260 int size = FixedArray::SizeFor(length);
2261 Object* result;
2262 if (size > MaxHeapObjectSize()) {
2263 result = lo_space_->AllocateRawFixedArray(size);
2264 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002265 AllocationSpace space =
2266 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002267 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002268 }
2269 if (result->IsFailure()) return result;
2270
2271 // Initialize the object.
2272 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2273 FixedArray* array = FixedArray::cast(result);
2274 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002275 Object* value = undefined_value();
2276 for (int index = 0; index < length; index++) {
2277 array->set(index, value, SKIP_WRITE_BARRIER);
2278 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002279 return array;
2280}
2281
2282
2283Object* Heap::AllocateFixedArrayWithHoles(int length) {
2284 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002285 Object* result = AllocateRawFixedArray(length);
2286 if (!result->IsFailure()) {
2287 // Initialize header.
2288 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2289 FixedArray* array = FixedArray::cast(result);
2290 array->set_length(length);
2291 // Initialize body.
2292 Object* value = the_hole_value();
2293 for (int index = 0; index < length; index++) {
2294 array->set(index, value, SKIP_WRITE_BARRIER);
2295 }
2296 }
2297 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002298}
2299
2300
2301Object* Heap::AllocateHashTable(int length) {
2302 Object* result = Heap::AllocateFixedArray(length);
2303 if (result->IsFailure()) return result;
2304 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2305 ASSERT(result->IsDictionary());
2306 return result;
2307}
2308
2309
2310Object* Heap::AllocateGlobalContext() {
2311 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2312 if (result->IsFailure()) return result;
2313 Context* context = reinterpret_cast<Context*>(result);
2314 context->set_map(global_context_map());
2315 ASSERT(context->IsGlobalContext());
2316 ASSERT(result->IsContext());
2317 return result;
2318}
2319
2320
2321Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2322 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2323 Object* result = Heap::AllocateFixedArray(length);
2324 if (result->IsFailure()) return result;
2325 Context* context = reinterpret_cast<Context*>(result);
2326 context->set_map(context_map());
2327 context->set_closure(function);
2328 context->set_fcontext(context);
2329 context->set_previous(NULL);
2330 context->set_extension(NULL);
2331 context->set_global(function->context()->global());
2332 ASSERT(!context->IsGlobalContext());
2333 ASSERT(context->is_function_context());
2334 ASSERT(result->IsContext());
2335 return result;
2336}
2337
2338
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002339Object* Heap::AllocateWithContext(Context* previous,
2340 JSObject* extension,
2341 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002342 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2343 if (result->IsFailure()) return result;
2344 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002345 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002346 context->set_closure(previous->closure());
2347 context->set_fcontext(previous->fcontext());
2348 context->set_previous(previous);
2349 context->set_extension(extension);
2350 context->set_global(previous->global());
2351 ASSERT(!context->IsGlobalContext());
2352 ASSERT(!context->is_function_context());
2353 ASSERT(result->IsContext());
2354 return result;
2355}
2356
2357
2358Object* Heap::AllocateStruct(InstanceType type) {
2359 Map* map;
2360 switch (type) {
2361#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2362STRUCT_LIST(MAKE_CASE)
2363#undef MAKE_CASE
2364 default:
2365 UNREACHABLE();
2366 return Failure::InternalError();
2367 }
2368 int size = map->instance_size();
2369 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002370 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002371 Object* result = Heap::Allocate(map, space);
2372 if (result->IsFailure()) return result;
2373 Struct::cast(result)->InitializeBody(size);
2374 return result;
2375}
2376
2377
2378#ifdef DEBUG
2379
2380void Heap::Print() {
2381 if (!HasBeenSetup()) return;
2382 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002383 AllSpaces spaces;
2384 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002385}
2386
2387
2388void Heap::ReportCodeStatistics(const char* title) {
2389 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2390 PagedSpace::ResetCodeStatistics();
2391 // We do not look for code in new space, map space, or old space. If code
2392 // somehow ends up in those spaces, we would miss it here.
2393 code_space_->CollectCodeStatistics();
2394 lo_space_->CollectCodeStatistics();
2395 PagedSpace::ReportCodeStatistics();
2396}
2397
2398
2399// This function expects that NewSpace's allocated objects histogram is
2400// populated (via a call to CollectStatistics or else as a side effect of a
2401// just-completed scavenge collection).
2402void Heap::ReportHeapStatistics(const char* title) {
2403 USE(title);
2404 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2405 title, gc_count_);
2406 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002407 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2408 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002409
2410 PrintF("\n");
2411 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2412 GlobalHandles::PrintStats();
2413 PrintF("\n");
2414
2415 PrintF("Heap statistics : ");
2416 MemoryAllocator::ReportStatistics();
2417 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002418 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002419 PrintF("Old pointer space : ");
2420 old_pointer_space_->ReportStatistics();
2421 PrintF("Old data space : ");
2422 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002423 PrintF("Code space : ");
2424 code_space_->ReportStatistics();
2425 PrintF("Map space : ");
2426 map_space_->ReportStatistics();
2427 PrintF("Large object space : ");
2428 lo_space_->ReportStatistics();
2429 PrintF(">>>>>> ========================================= >>>>>>\n");
2430}
2431
2432#endif // DEBUG
2433
2434bool Heap::Contains(HeapObject* value) {
2435 return Contains(value->address());
2436}
2437
2438
2439bool Heap::Contains(Address addr) {
2440 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2441 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002442 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002443 old_pointer_space_->Contains(addr) ||
2444 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002445 code_space_->Contains(addr) ||
2446 map_space_->Contains(addr) ||
2447 lo_space_->SlowContains(addr));
2448}
2449
2450
2451bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2452 return InSpace(value->address(), space);
2453}
2454
2455
2456bool Heap::InSpace(Address addr, AllocationSpace space) {
2457 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2458 if (!HasBeenSetup()) return false;
2459
2460 switch (space) {
2461 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002462 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002463 case OLD_POINTER_SPACE:
2464 return old_pointer_space_->Contains(addr);
2465 case OLD_DATA_SPACE:
2466 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002467 case CODE_SPACE:
2468 return code_space_->Contains(addr);
2469 case MAP_SPACE:
2470 return map_space_->Contains(addr);
2471 case LO_SPACE:
2472 return lo_space_->SlowContains(addr);
2473 }
2474
2475 return false;
2476}
2477
2478
2479#ifdef DEBUG
2480void Heap::Verify() {
2481 ASSERT(HasBeenSetup());
2482
2483 VerifyPointersVisitor visitor;
2484 Heap::IterateRoots(&visitor);
2485
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002486 AllSpaces spaces;
2487 while (Space* space = spaces.next()) {
2488 space->Verify();
2489 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002490}
2491#endif // DEBUG
2492
2493
2494Object* Heap::LookupSymbol(Vector<const char> string) {
2495 Object* symbol = NULL;
2496 Object* new_table =
2497 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2498 if (new_table->IsFailure()) return new_table;
2499 symbol_table_ = new_table;
2500 ASSERT(symbol != NULL);
2501 return symbol;
2502}
2503
2504
2505Object* Heap::LookupSymbol(String* string) {
2506 if (string->IsSymbol()) return string;
2507 Object* symbol = NULL;
2508 Object* new_table =
2509 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2510 if (new_table->IsFailure()) return new_table;
2511 symbol_table_ = new_table;
2512 ASSERT(symbol != NULL);
2513 return symbol;
2514}
2515
2516
ager@chromium.org7c537e22008-10-16 08:43:32 +00002517bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2518 if (string->IsSymbol()) {
2519 *symbol = string;
2520 return true;
2521 }
2522 SymbolTable* table = SymbolTable::cast(symbol_table_);
2523 return table->LookupSymbolIfExists(string, symbol);
2524}
2525
2526
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002527#ifdef DEBUG
2528void Heap::ZapFromSpace() {
2529 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002530 for (Address a = new_space_.FromSpaceLow();
2531 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002532 a += kPointerSize) {
2533 Memory::Address_at(a) = kFromSpaceZapValue;
2534 }
2535}
2536#endif // DEBUG
2537
2538
2539void Heap::IterateRSetRange(Address object_start,
2540 Address object_end,
2541 Address rset_start,
2542 ObjectSlotCallback copy_object_func) {
2543 Address object_address = object_start;
2544 Address rset_address = rset_start;
2545
2546 // Loop over all the pointers in [object_start, object_end).
2547 while (object_address < object_end) {
2548 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002549 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002550 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002551 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002552 // Do not dereference pointers at or past object_end.
2553 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2554 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002555 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002556 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2557 }
2558 // If this pointer does not need to be remembered anymore, clear
2559 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002560 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002561 }
2562 object_address += kPointerSize;
2563 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002564 // Update the remembered set if it has changed.
2565 if (result_rset != rset_word) {
2566 Memory::uint32_at(rset_address) = result_rset;
2567 }
2568 } else {
2569 // No bits in the word were set. This is the common case.
2570 object_address += kPointerSize * kBitsPerInt;
2571 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002572 rset_address += kIntSize;
2573 }
2574}
2575
2576
2577void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2578 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002579 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002580
2581 PageIterator it(space, PageIterator::PAGES_IN_USE);
2582 while (it.has_next()) {
2583 Page* page = it.next();
2584 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2585 page->RSetStart(), copy_object_func);
2586 }
2587}
2588
2589
2590#ifdef DEBUG
2591#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2592#else
2593#define SYNCHRONIZE_TAG(tag)
2594#endif
2595
2596void Heap::IterateRoots(ObjectVisitor* v) {
2597 IterateStrongRoots(v);
2598 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2599 SYNCHRONIZE_TAG("symbol_table");
2600}
2601
2602
2603void Heap::IterateStrongRoots(ObjectVisitor* v) {
2604#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002605 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002606 STRONG_ROOT_LIST(ROOT_ITERATE);
2607#undef ROOT_ITERATE
2608 SYNCHRONIZE_TAG("strong_root_list");
2609
2610#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002611 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002612 STRUCT_LIST(STRUCT_MAP_ITERATE);
2613#undef STRUCT_MAP_ITERATE
2614 SYNCHRONIZE_TAG("struct_map");
2615
2616#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002617 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002618 SYMBOL_LIST(SYMBOL_ITERATE)
2619#undef SYMBOL_ITERATE
2620 SYNCHRONIZE_TAG("symbol");
2621
2622 Bootstrapper::Iterate(v);
2623 SYNCHRONIZE_TAG("bootstrapper");
2624 Top::Iterate(v);
2625 SYNCHRONIZE_TAG("top");
2626 Debug::Iterate(v);
2627 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002628 CompilationCache::Iterate(v);
2629 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002630
2631 // Iterate over local handles in handle scopes.
2632 HandleScopeImplementer::Iterate(v);
2633 SYNCHRONIZE_TAG("handlescope");
2634
2635 // Iterate over the builtin code objects and code stubs in the heap. Note
2636 // that it is not strictly necessary to iterate over code objects on
2637 // scavenge collections. We still do it here because this same function
2638 // is used by the mark-sweep collector and the deserializer.
2639 Builtins::IterateBuiltins(v);
2640 SYNCHRONIZE_TAG("builtins");
2641
2642 // Iterate over global handles.
2643 GlobalHandles::IterateRoots(v);
2644 SYNCHRONIZE_TAG("globalhandles");
2645
2646 // Iterate over pointers being held by inactive threads.
2647 ThreadManager::Iterate(v);
2648 SYNCHRONIZE_TAG("threadmanager");
2649}
2650#undef SYNCHRONIZE_TAG
2651
2652
2653// Flag is set when the heap has been configured. The heap can be repeatedly
2654// configured through the API until it is setup.
2655static bool heap_configured = false;
2656
2657// TODO(1236194): Since the heap size is configurable on the command line
2658// and through the API, we should gracefully handle the case that the heap
2659// size is not big enough to fit all the initial objects.
2660bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2661 if (HasBeenSetup()) return false;
2662
2663 if (semispace_size > 0) semispace_size_ = semispace_size;
2664 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2665
2666 // The new space size must be a power of two to support single-bit testing
2667 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002668 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002669 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2670 young_generation_size_ = 2 * semispace_size_;
2671
2672 // The old generation is paged.
2673 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2674
2675 heap_configured = true;
2676 return true;
2677}
2678
2679
kasper.lund7276f142008-07-30 08:49:36 +00002680bool Heap::ConfigureHeapDefault() {
2681 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2682}
2683
2684
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002685int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002686 return old_pointer_space_->Size()
2687 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002688 + code_space_->Size()
2689 + map_space_->Size()
2690 + lo_space_->Size();
2691}
2692
2693
kasper.lund7276f142008-07-30 08:49:36 +00002694int Heap::PromotedExternalMemorySize() {
2695 if (amount_of_external_allocated_memory_
2696 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2697 return amount_of_external_allocated_memory_
2698 - amount_of_external_allocated_memory_at_last_global_gc_;
2699}
2700
2701
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002702bool Heap::Setup(bool create_heap_objects) {
2703 // Initialize heap spaces and initial maps and objects. Whenever something
2704 // goes wrong, just return false. The caller should check the results and
2705 // call Heap::TearDown() to release allocated memory.
2706 //
2707 // If the heap is not yet configured (eg, through the API), configure it.
2708 // Configuration is based on the flags new-space-size (really the semispace
2709 // size) and old-space-size if set or the initial values of semispace_size_
2710 // and old_generation_size_ otherwise.
2711 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002712 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002713 }
2714
2715 // Setup memory allocator and allocate an initial chunk of memory. The
2716 // initial chunk is double the size of the new space to ensure that we can
2717 // find a pair of semispaces that are contiguous and aligned to their size.
2718 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2719 void* chunk
2720 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2721 if (chunk == NULL) return false;
2722
2723 // Put the initial chunk of the old space at the start of the initial
2724 // chunk, then the two new space semispaces, then the initial chunk of
2725 // code space. Align the pair of semispaces to their size, which must be
2726 // a power of 2.
2727 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002728 Address code_space_start = reinterpret_cast<Address>(chunk);
2729 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2730 Address old_space_start = new_space_start + young_generation_size_;
2731 int code_space_size = new_space_start - code_space_start;
2732 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002733
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002734 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002735 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002736
2737 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002738 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002739 old_pointer_space_ =
2740 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2741 if (old_pointer_space_ == NULL) return false;
2742 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2743 return false;
2744 }
2745 old_data_space_ =
2746 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2747 if (old_data_space_ == NULL) return false;
2748 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2749 old_space_size >> 1)) {
2750 return false;
2751 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002752
2753 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002754 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002755 code_space_ =
2756 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002757 if (code_space_ == NULL) return false;
2758 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2759
2760 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002761 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002762 if (map_space_ == NULL) return false;
2763 // Setting up a paged space without giving it a virtual memory range big
2764 // enough to hold at least a page will cause it to allocate.
2765 if (!map_space_->Setup(NULL, 0)) return false;
2766
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002767 // The large object code space may contain code or data. We set the memory
2768 // to be non-executable here for safety, but this means we need to enable it
2769 // explicitly when allocating large code objects.
2770 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002771 if (lo_space_ == NULL) return false;
2772 if (!lo_space_->Setup()) return false;
2773
2774 if (create_heap_objects) {
2775 // Create initial maps.
2776 if (!CreateInitialMaps()) return false;
2777 if (!CreateApiObjects()) return false;
2778
2779 // Create initial objects
2780 if (!CreateInitialObjects()) return false;
2781 }
2782
2783 LOG(IntEvent("heap-capacity", Capacity()));
2784 LOG(IntEvent("heap-available", Available()));
2785
2786 return true;
2787}
2788
2789
2790void Heap::TearDown() {
2791 GlobalHandles::TearDown();
2792
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002793 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002794
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002795 if (old_pointer_space_ != NULL) {
2796 old_pointer_space_->TearDown();
2797 delete old_pointer_space_;
2798 old_pointer_space_ = NULL;
2799 }
2800
2801 if (old_data_space_ != NULL) {
2802 old_data_space_->TearDown();
2803 delete old_data_space_;
2804 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002805 }
2806
2807 if (code_space_ != NULL) {
2808 code_space_->TearDown();
2809 delete code_space_;
2810 code_space_ = NULL;
2811 }
2812
2813 if (map_space_ != NULL) {
2814 map_space_->TearDown();
2815 delete map_space_;
2816 map_space_ = NULL;
2817 }
2818
2819 if (lo_space_ != NULL) {
2820 lo_space_->TearDown();
2821 delete lo_space_;
2822 lo_space_ = NULL;
2823 }
2824
2825 MemoryAllocator::TearDown();
2826}
2827
2828
2829void Heap::Shrink() {
2830 // Try to shrink map, old, and code spaces.
2831 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002832 old_pointer_space_->Shrink();
2833 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002834 code_space_->Shrink();
2835}
2836
2837
2838#ifdef DEBUG
2839
2840class PrintHandleVisitor: public ObjectVisitor {
2841 public:
2842 void VisitPointers(Object** start, Object** end) {
2843 for (Object** p = start; p < end; p++)
2844 PrintF(" handle %p to %p\n", p, *p);
2845 }
2846};
2847
2848void Heap::PrintHandles() {
2849 PrintF("Handles:\n");
2850 PrintHandleVisitor v;
2851 HandleScopeImplementer::Iterate(&v);
2852}
2853
2854#endif
2855
2856
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002857Space* AllSpaces::next() {
2858 switch (counter_++) {
2859 case NEW_SPACE:
2860 return Heap::new_space();
2861 case OLD_POINTER_SPACE:
2862 return Heap::old_pointer_space();
2863 case OLD_DATA_SPACE:
2864 return Heap::old_data_space();
2865 case CODE_SPACE:
2866 return Heap::code_space();
2867 case MAP_SPACE:
2868 return Heap::map_space();
2869 case LO_SPACE:
2870 return Heap::lo_space();
2871 default:
2872 return NULL;
2873 }
2874}
2875
2876
2877PagedSpace* PagedSpaces::next() {
2878 switch (counter_++) {
2879 case OLD_POINTER_SPACE:
2880 return Heap::old_pointer_space();
2881 case OLD_DATA_SPACE:
2882 return Heap::old_data_space();
2883 case CODE_SPACE:
2884 return Heap::code_space();
2885 case MAP_SPACE:
2886 return Heap::map_space();
2887 default:
2888 return NULL;
2889 }
2890}
2891
2892
2893
2894OldSpace* OldSpaces::next() {
2895 switch (counter_++) {
2896 case OLD_POINTER_SPACE:
2897 return Heap::old_pointer_space();
2898 case OLD_DATA_SPACE:
2899 return Heap::old_data_space();
2900 case CODE_SPACE:
2901 return Heap::code_space();
2902 default:
2903 return NULL;
2904 }
2905}
2906
2907
kasper.lund7276f142008-07-30 08:49:36 +00002908SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2909}
2910
2911
2912SpaceIterator::~SpaceIterator() {
2913 // Delete active iterator if any.
2914 delete iterator_;
2915}
2916
2917
2918bool SpaceIterator::has_next() {
2919 // Iterate until no more spaces.
2920 return current_space_ != LAST_SPACE;
2921}
2922
2923
2924ObjectIterator* SpaceIterator::next() {
2925 if (iterator_ != NULL) {
2926 delete iterator_;
2927 iterator_ = NULL;
2928 // Move to the next space
2929 current_space_++;
2930 if (current_space_ > LAST_SPACE) {
2931 return NULL;
2932 }
2933 }
2934
2935 // Return iterator for the new current space.
2936 return CreateIterator();
2937}
2938
2939
2940// Create an iterator for the space to iterate.
2941ObjectIterator* SpaceIterator::CreateIterator() {
2942 ASSERT(iterator_ == NULL);
2943
2944 switch (current_space_) {
2945 case NEW_SPACE:
2946 iterator_ = new SemiSpaceIterator(Heap::new_space());
2947 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002948 case OLD_POINTER_SPACE:
2949 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
2950 break;
2951 case OLD_DATA_SPACE:
2952 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00002953 break;
2954 case CODE_SPACE:
2955 iterator_ = new HeapObjectIterator(Heap::code_space());
2956 break;
2957 case MAP_SPACE:
2958 iterator_ = new HeapObjectIterator(Heap::map_space());
2959 break;
2960 case LO_SPACE:
2961 iterator_ = new LargeObjectIterator(Heap::lo_space());
2962 break;
2963 }
2964
2965 // Return the newly allocated iterator;
2966 ASSERT(iterator_ != NULL);
2967 return iterator_;
2968}
2969
2970
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002971HeapIterator::HeapIterator() {
2972 Init();
2973}
2974
2975
2976HeapIterator::~HeapIterator() {
2977 Shutdown();
2978}
2979
2980
2981void HeapIterator::Init() {
2982 // Start the iteration.
2983 space_iterator_ = new SpaceIterator();
2984 object_iterator_ = space_iterator_->next();
2985}
2986
2987
2988void HeapIterator::Shutdown() {
2989 // Make sure the last iterator is deallocated.
2990 delete space_iterator_;
2991 space_iterator_ = NULL;
2992 object_iterator_ = NULL;
2993}
2994
2995
2996bool HeapIterator::has_next() {
2997 // No iterator means we are done.
2998 if (object_iterator_ == NULL) return false;
2999
3000 if (object_iterator_->has_next_object()) {
3001 // If the current iterator has more objects we are fine.
3002 return true;
3003 } else {
3004 // Go though the spaces looking for one that has objects.
3005 while (space_iterator_->has_next()) {
3006 object_iterator_ = space_iterator_->next();
3007 if (object_iterator_->has_next_object()) {
3008 return true;
3009 }
3010 }
3011 }
3012 // Done with the last space.
3013 object_iterator_ = NULL;
3014 return false;
3015}
3016
3017
3018HeapObject* HeapIterator::next() {
3019 if (has_next()) {
3020 return object_iterator_->next_object();
3021 } else {
3022 return NULL;
3023 }
3024}
3025
3026
3027void HeapIterator::reset() {
3028 // Restart the iterator.
3029 Shutdown();
3030 Init();
3031}
3032
3033
3034//
3035// HeapProfiler class implementation.
3036//
3037#ifdef ENABLE_LOGGING_AND_PROFILING
3038void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3039 InstanceType type = obj->map()->instance_type();
3040 ASSERT(0 <= type && type <= LAST_TYPE);
3041 info[type].increment_number(1);
3042 info[type].increment_bytes(obj->Size());
3043}
3044#endif
3045
3046
3047#ifdef ENABLE_LOGGING_AND_PROFILING
3048void HeapProfiler::WriteSample() {
3049 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3050
3051 HistogramInfo info[LAST_TYPE+1];
3052#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3053 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3054#undef DEF_TYPE_NAME
3055
3056 HeapIterator iterator;
3057 while (iterator.has_next()) {
3058 CollectStats(iterator.next(), info);
3059 }
3060
3061 // Lump all the string types together.
3062 int string_number = 0;
3063 int string_bytes = 0;
3064#define INCREMENT_SIZE(type, size, name) \
3065 string_number += info[type].number(); \
3066 string_bytes += info[type].bytes();
3067 STRING_TYPE_LIST(INCREMENT_SIZE)
3068#undef INCREMENT_SIZE
3069 if (string_bytes > 0) {
3070 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3071 }
3072
3073 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3074 if (info[i].bytes() > 0) {
3075 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3076 info[i].bytes()));
3077 }
3078 }
3079
3080 LOG(HeapSampleEndEvent("Heap", "allocated"));
3081}
3082
3083
3084#endif
3085
3086
3087
3088#ifdef DEBUG
3089
3090static bool search_for_any_global;
3091static Object* search_target;
3092static bool found_target;
3093static List<Object*> object_stack(20);
3094
3095
3096// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3097static const int kMarkTag = 2;
3098
3099static void MarkObjectRecursively(Object** p);
3100class MarkObjectVisitor : public ObjectVisitor {
3101 public:
3102 void VisitPointers(Object** start, Object** end) {
3103 // Copy all HeapObject pointers in [start, end)
3104 for (Object** p = start; p < end; p++) {
3105 if ((*p)->IsHeapObject())
3106 MarkObjectRecursively(p);
3107 }
3108 }
3109};
3110
3111static MarkObjectVisitor mark_visitor;
3112
3113static void MarkObjectRecursively(Object** p) {
3114 if (!(*p)->IsHeapObject()) return;
3115
3116 HeapObject* obj = HeapObject::cast(*p);
3117
3118 Object* map = obj->map();
3119
3120 if (!map->IsHeapObject()) return; // visited before
3121
3122 if (found_target) return; // stop if target found
3123 object_stack.Add(obj);
3124 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3125 (!search_for_any_global && (obj == search_target))) {
3126 found_target = true;
3127 return;
3128 }
3129
3130 if (obj->IsCode()) {
3131 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3132 }
3133
3134 // not visited yet
3135 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3136
3137 Address map_addr = map_p->address();
3138
3139 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3140
3141 MarkObjectRecursively(&map);
3142
3143 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3144 &mark_visitor);
3145
3146 if (!found_target) // don't pop if found the target
3147 object_stack.RemoveLast();
3148}
3149
3150
3151static void UnmarkObjectRecursively(Object** p);
3152class UnmarkObjectVisitor : public ObjectVisitor {
3153 public:
3154 void VisitPointers(Object** start, Object** end) {
3155 // Copy all HeapObject pointers in [start, end)
3156 for (Object** p = start; p < end; p++) {
3157 if ((*p)->IsHeapObject())
3158 UnmarkObjectRecursively(p);
3159 }
3160 }
3161};
3162
3163static UnmarkObjectVisitor unmark_visitor;
3164
3165static void UnmarkObjectRecursively(Object** p) {
3166 if (!(*p)->IsHeapObject()) return;
3167
3168 HeapObject* obj = HeapObject::cast(*p);
3169
3170 Object* map = obj->map();
3171
3172 if (map->IsHeapObject()) return; // unmarked already
3173
3174 Address map_addr = reinterpret_cast<Address>(map);
3175
3176 map_addr -= kMarkTag;
3177
3178 ASSERT_TAG_ALIGNED(map_addr);
3179
3180 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3181
3182 obj->set_map(reinterpret_cast<Map*>(map_p));
3183
3184 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3185
3186 obj->IterateBody(Map::cast(map_p)->instance_type(),
3187 obj->SizeFromMap(Map::cast(map_p)),
3188 &unmark_visitor);
3189
3190 if (obj->IsCode()) {
3191 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3192 }
3193}
3194
3195
3196static void MarkRootObjectRecursively(Object** root) {
3197 if (search_for_any_global) {
3198 ASSERT(search_target == NULL);
3199 } else {
3200 ASSERT(search_target->IsHeapObject());
3201 }
3202 found_target = false;
3203 object_stack.Clear();
3204
3205 MarkObjectRecursively(root);
3206 UnmarkObjectRecursively(root);
3207
3208 if (found_target) {
3209 PrintF("=====================================\n");
3210 PrintF("==== Path to object ====\n");
3211 PrintF("=====================================\n\n");
3212
3213 ASSERT(!object_stack.is_empty());
3214 for (int i = 0; i < object_stack.length(); i++) {
3215 if (i > 0) PrintF("\n |\n |\n V\n\n");
3216 Object* obj = object_stack[i];
3217 obj->Print();
3218 }
3219 PrintF("=====================================\n");
3220 }
3221}
3222
3223
3224// Helper class for visiting HeapObjects recursively.
3225class MarkRootVisitor: public ObjectVisitor {
3226 public:
3227 void VisitPointers(Object** start, Object** end) {
3228 // Visit all HeapObject pointers in [start, end)
3229 for (Object** p = start; p < end; p++) {
3230 if ((*p)->IsHeapObject())
3231 MarkRootObjectRecursively(p);
3232 }
3233 }
3234};
3235
3236
3237// Triggers a depth-first traversal of reachable objects from roots
3238// and finds a path to a specific heap object and prints it.
3239void Heap::TracePathToObject() {
3240 search_target = NULL;
3241 search_for_any_global = false;
3242
3243 MarkRootVisitor root_visitor;
3244 IterateRoots(&root_visitor);
3245}
3246
3247
3248// Triggers a depth-first traversal of reachable objects from roots
3249// and finds a path to any global object and prints it. Useful for
3250// determining the source for leaks of global objects.
3251void Heap::TracePathToGlobal() {
3252 search_target = NULL;
3253 search_for_any_global = true;
3254
3255 MarkRootVisitor root_visitor;
3256 IterateRoots(&root_visitor);
3257}
3258#endif
3259
3260
kasper.lund7276f142008-07-30 08:49:36 +00003261GCTracer::GCTracer()
3262 : start_time_(0.0),
3263 start_size_(0.0),
3264 gc_count_(0),
3265 full_gc_count_(0),
3266 is_compacting_(false),
3267 marked_count_(0) {
3268 // These two fields reflect the state of the previous full collection.
3269 // Set them before they are changed by the collector.
3270 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3271 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3272 if (!FLAG_trace_gc) return;
3273 start_time_ = OS::TimeCurrentMillis();
3274 start_size_ = SizeOfHeapObjects();
3275}
3276
3277
3278GCTracer::~GCTracer() {
3279 if (!FLAG_trace_gc) return;
3280 // Printf ONE line iff flag is set.
3281 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3282 CollectorString(),
3283 start_size_, SizeOfHeapObjects(),
3284 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3285}
3286
3287
3288const char* GCTracer::CollectorString() {
3289 switch (collector_) {
3290 case SCAVENGER:
3291 return "Scavenge";
3292 case MARK_COMPACTOR:
3293 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3294 : "Mark-sweep";
3295 }
3296 return "Unknown GC";
3297}
3298
3299
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003300#ifdef DEBUG
3301bool Heap::GarbageCollectionGreedyCheck() {
3302 ASSERT(FLAG_gc_greedy);
3303 if (Bootstrapper::IsActive()) return true;
3304 if (disallow_allocation_failure()) return true;
3305 return CollectGarbage(0, NEW_SPACE);
3306}
3307#endif
3308
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003309} } // namespace v8::internal