blob: b0a2db4fa965b11920b64dab04c66b21c4406391 [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
ager@chromium.orga74f0da2008-12-03 16:05:52 +000087ExternalSymbolCallback Heap::global_external_symbol_callback_ = NULL;
88
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000089// Variables set based on semispace_size_ and old_generation_size_ in
90// ConfigureHeap.
91int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
92
93// Double the new space after this many scavenge collections.
94int Heap::new_space_growth_limit_ = 8;
95int Heap::scavenge_count_ = 0;
96Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
97
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000098int Heap::mc_count_ = 0;
99int Heap::gc_count_ = 0;
100
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000101int Heap::always_allocate_scope_depth_ = 0;
102
kasper.lund7276f142008-07-30 08:49:36 +0000103#ifdef DEBUG
104bool Heap::allocation_allowed_ = true;
105
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000106int Heap::allocation_timeout_ = 0;
107bool Heap::disallow_allocation_failure_ = false;
108#endif // DEBUG
109
110
111int Heap::Capacity() {
112 if (!HasBeenSetup()) return 0;
113
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000114 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000115 old_pointer_space_->Capacity() +
116 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 code_space_->Capacity() +
118 map_space_->Capacity();
119}
120
121
122int Heap::Available() {
123 if (!HasBeenSetup()) return 0;
124
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000125 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000126 old_pointer_space_->Available() +
127 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 code_space_->Available() +
129 map_space_->Available();
130}
131
132
133bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000134 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000135 old_data_space_ != NULL &&
136 code_space_ != NULL &&
137 map_space_ != NULL &&
138 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139}
140
141
142GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
143 // Is global GC requested?
144 if (space != NEW_SPACE || FLAG_gc_global) {
145 Counters::gc_compactor_caused_by_request.Increment();
146 return MARK_COMPACTOR;
147 }
148
149 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000150 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000151 Counters::gc_compactor_caused_by_promoted_data.Increment();
152 return MARK_COMPACTOR;
153 }
154
155 // Have allocation in OLD and LO failed?
156 if (old_gen_exhausted_) {
157 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
158 return MARK_COMPACTOR;
159 }
160
161 // Is there enough space left in OLD to guarantee that a scavenge can
162 // succeed?
163 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000164 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 // for object promotion. It counts only the bytes that the memory
166 // allocator has not yet allocated from the OS and assigned to any space,
167 // and does not count available bytes already in the old space or code
168 // space. Undercounting is safe---we may get an unrequested full GC when
169 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000170 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
172 return MARK_COMPACTOR;
173 }
174
175 // Default
176 return SCAVENGER;
177}
178
179
180// TODO(1238405): Combine the infrastructure for --heap-stats and
181// --log-gc to avoid the complicated preprocessor and flag testing.
182#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
183void Heap::ReportStatisticsBeforeGC() {
184 // Heap::ReportHeapStatistics will also log NewSpace statistics when
185 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
186 // following logic is used to avoid double logging.
187#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000188 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000189 if (FLAG_heap_stats) {
190 ReportHeapStatistics("Before GC");
191 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000192 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000194 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195#elif defined(DEBUG)
196 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000199 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000200 }
201#elif defined(ENABLE_LOGGING_AND_PROFILING)
202 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 new_space_.CollectStatistics();
204 new_space_.ReportStatistics();
205 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 }
207#endif
208}
209
210
211// TODO(1238405): Combine the infrastructure for --heap-stats and
212// --log-gc to avoid the complicated preprocessor and flag testing.
213void Heap::ReportStatisticsAfterGC() {
214 // Similar to the before GC, we use some complicated logic to ensure that
215 // NewSpace statistics are logged exactly once when --log-gc is turned on.
216#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
217 if (FLAG_heap_stats) {
218 ReportHeapStatistics("After GC");
219 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000220 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000221 }
222#elif defined(DEBUG)
223 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
224#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000225 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226#endif
227}
228#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
229
230
231void Heap::GarbageCollectionPrologue() {
232 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000233 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000234#ifdef DEBUG
235 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
236 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000237
238 if (FLAG_verify_heap) {
239 Verify();
240 }
241
242 if (FLAG_gc_verbose) Print();
243
244 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000245 // Not all spaces have remembered set bits that we care about.
246 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000247 map_space_->PrintRSet();
248 lo_space_->PrintRSet();
249 }
250#endif
251
252#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
253 ReportStatisticsBeforeGC();
254#endif
255}
256
257int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000258 int total = 0;
259 AllSpaces spaces;
260 while (Space* space = spaces.next()) total += space->Size();
261 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262}
263
264void Heap::GarbageCollectionEpilogue() {
265#ifdef DEBUG
266 allow_allocation(true);
267 ZapFromSpace();
268
269 if (FLAG_verify_heap) {
270 Verify();
271 }
272
273 if (FLAG_print_global_handles) GlobalHandles::Print();
274 if (FLAG_print_handles) PrintHandles();
275 if (FLAG_gc_verbose) Print();
276 if (FLAG_code_stats) ReportCodeStatistics("After GC");
277#endif
278
279 Counters::alive_after_last_gc.Set(SizeOfObjects());
280
281 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
282 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
283 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
284#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
285 ReportStatisticsAfterGC();
286#endif
287}
288
289
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000290void Heap::CollectAllGarbage() {
291 // Since we are ignoring the return value, the exact choice of space does
292 // not matter, so long as we do not specify NEW_SPACE, which would not
293 // cause a full GC.
294 CollectGarbage(0, OLD_POINTER_SPACE);
295}
296
297
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000298bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
299 // The VM is in the GC state until exiting this function.
300 VMState state(GC);
301
302#ifdef DEBUG
303 // Reset the allocation timeout to the GC interval, but make sure to
304 // allow at least a few allocations after a collection. The reason
305 // for this is that we have a lot of allocation sequences and we
306 // assume that a garbage collection will allow the subsequent
307 // allocation attempts to go through.
308 allocation_timeout_ = Max(6, FLAG_gc_interval);
309#endif
310
311 { GCTracer tracer;
312 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000313 // The GC count was incremented in the prologue. Tell the tracer about
314 // it.
315 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316
317 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000318 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319 tracer.set_collector(collector);
320
321 StatsRate* rate = (collector == SCAVENGER)
322 ? &Counters::gc_scavenger
323 : &Counters::gc_compactor;
324 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000325 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000326 rate->Stop();
327
328 GarbageCollectionEpilogue();
329 }
330
331
332#ifdef ENABLE_LOGGING_AND_PROFILING
333 if (FLAG_log_gc) HeapProfiler::WriteSample();
334#endif
335
336 switch (space) {
337 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000338 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000339 case OLD_POINTER_SPACE:
340 return old_pointer_space_->Available() >= requested_size;
341 case OLD_DATA_SPACE:
342 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343 case CODE_SPACE:
344 return code_space_->Available() >= requested_size;
345 case MAP_SPACE:
346 return map_space_->Available() >= requested_size;
347 case LO_SPACE:
348 return lo_space_->Available() >= requested_size;
349 }
350 return false;
351}
352
353
kasper.lund7276f142008-07-30 08:49:36 +0000354void Heap::PerformScavenge() {
355 GCTracer tracer;
356 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
357}
358
359
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000360void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000361 GarbageCollector collector,
362 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
364 ASSERT(!allocation_allowed_);
365 global_gc_prologue_callback_();
366 }
367
368 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000369 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000371 int old_gen_size = PromotedSpaceSize();
372 old_gen_promotion_limit_ =
373 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
374 old_gen_allocation_limit_ =
375 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 3);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000376 old_gen_exhausted_ = false;
377
378 // If we have used the mark-compact collector to collect the new
379 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000380 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000381 // case where (1) a new space collection was requested, (2) the
382 // collector selection policy selected the mark-compact collector,
383 // and (3) the mark-compact collector policy selected not to
384 // compact the new space. In that case, there is no more (usable)
385 // free space in the new space after the collection compared to
386 // before.
387 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
388 Scavenge();
389 }
390 } else {
391 Scavenge();
392 }
393 Counters::objs_since_last_young.Set(0);
394
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000395 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396
kasper.lund7276f142008-07-30 08:49:36 +0000397 if (collector == MARK_COMPACTOR) {
398 // Register the amount of external allocated memory.
399 amount_of_external_allocated_memory_at_last_global_gc_ =
400 amount_of_external_allocated_memory_;
401 }
402
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000403 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
404 ASSERT(!allocation_allowed_);
405 global_gc_epilogue_callback_();
406 }
407}
408
409
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000410void Heap::PostGarbageCollectionProcessing() {
411 // Process weak handles post gc.
412 GlobalHandles::PostGarbageCollectionProcessing();
413 // Update flat string readers.
414 FlatStringReader::PostGarbageCollectionProcessing();
415}
416
417
kasper.lund7276f142008-07-30 08:49:36 +0000418void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000420 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000421 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000422 LOG(ResourceEvent("markcompact", "begin"));
423
424 MarkCompactPrologue();
425
kasper.lund7276f142008-07-30 08:49:36 +0000426 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427
428 MarkCompactEpilogue();
429
430 LOG(ResourceEvent("markcompact", "end"));
431
432 gc_state_ = NOT_IN_GC;
433
434 Shrink();
435
436 Counters::objs_since_last_full.Set(0);
437}
438
439
440void Heap::MarkCompactPrologue() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000441 ClearKeyedLookupCache();
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000442 CompilationCache::MarkCompactPrologue();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443 RegExpImpl::OldSpaceCollectionPrologue();
444 Top::MarkCompactPrologue();
445 ThreadManager::MarkCompactPrologue();
446}
447
448
449void Heap::MarkCompactEpilogue() {
450 Top::MarkCompactEpilogue();
451 ThreadManager::MarkCompactEpilogue();
452}
453
454
455Object* Heap::FindCodeObject(Address a) {
456 Object* obj = code_space_->FindObject(a);
457 if (obj->IsFailure()) {
458 obj = lo_space_->FindObject(a);
459 }
kasper.lund7276f142008-07-30 08:49:36 +0000460 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461 return obj;
462}
463
464
465// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000466class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000467 public:
468
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000469 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470
471 void VisitPointers(Object** start, Object** end) {
472 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000473 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474 }
475
476 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000477 void ScavengePointer(Object** p) {
478 Object* object = *p;
479 if (!Heap::InNewSpace(object)) return;
480 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
481 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482 }
483};
484
485
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000486// Shared state read by the scavenge collector and set by ScavengeObject.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487static Address promoted_top = NULL;
488
489
490#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000491// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000493class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000494 public:
495 void VisitPointers(Object** start, Object**end) {
496 for (Object** current = start; current < end; current++) {
497 if ((*current)->IsHeapObject()) {
498 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
499 }
500 }
501 }
502};
503#endif
504
505void Heap::Scavenge() {
506#ifdef DEBUG
507 if (FLAG_enable_slow_asserts) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000508 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000509 HeapObjectIterator it(code_space_);
510 while (it.has_next()) {
511 HeapObject* object = it.next();
512 if (object->IsCode()) {
513 Code::cast(object)->ConvertICTargetsFromAddressToObject();
514 }
515 object->Iterate(&v);
516 if (object->IsCode()) {
517 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
518 }
519 }
520 }
521#endif
522
523 gc_state_ = SCAVENGE;
524
525 // Implements Cheney's copying algorithm
526 LOG(ResourceEvent("scavenge", "begin"));
527
528 scavenge_count_++;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000529 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000530 scavenge_count_ > new_space_growth_limit_) {
531 // Double the size of the new space, and double the limit. The next
532 // doubling attempt will occur after the current new_space_growth_limit_
533 // more collections.
534 // TODO(1240712): NewSpace::Double has a return value which is
535 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000536 new_space_.Double();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000537 new_space_growth_limit_ *= 2;
538 }
539
540 // Flip the semispaces. After flipping, to space is empty, from space has
541 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000542 new_space_.Flip();
543 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544
545 // We need to sweep newly copied objects which can be in either the to space
546 // or the old space. For to space objects, we use a mark. Newly copied
547 // objects lie between the mark and the allocation top. For objects
548 // promoted to old space, we write their addresses downward from the top of
549 // the new space. Sweeping newly promoted objects requires an allocation
550 // pointer and a mark. Note that the allocation pointer 'top' actually
551 // moves downward from the high address in the to space.
552 //
553 // There is guaranteed to be enough room at the top of the to space for the
554 // addresses of promoted objects: every object promoted frees up its size in
555 // bytes from the top of the new space, and objects are at least one pointer
556 // in size. Using the new space to record promoted addresses makes the
557 // scavenge collector agnostic to the allocation strategy (eg, linear or
558 // free-list) used in old space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000559 Address new_mark = new_space_.ToSpaceLow();
560 Address promoted_mark = new_space_.ToSpaceHigh();
561 promoted_top = new_space_.ToSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000563 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000565 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566
567 // Copy objects reachable from the old generation. By definition, there
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000568 // are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000569 IterateRSet(old_pointer_space_, &ScavengePointer);
570 IterateRSet(map_space_, &ScavengePointer);
571 lo_space_->IterateRSet(&ScavengePointer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000572
573 bool has_processed_weak_pointers = false;
574
575 while (true) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000576 ASSERT(new_mark <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000577 ASSERT(promoted_mark >= promoted_top);
578
579 // Copy objects reachable from newly copied objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000580 while (new_mark < new_space_.top() || promoted_mark > promoted_top) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581 // Sweep newly copied objects in the to space. The allocation pointer
582 // can change during sweeping.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000583 Address previous_top = new_space_.top();
584 SemiSpaceIterator new_it(new_space(), new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000585 while (new_it.has_next()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000586 new_it.next()->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587 }
588 new_mark = previous_top;
589
590 // Sweep newly copied objects in the old space. The promotion 'top'
591 // pointer could change during sweeping.
592 previous_top = promoted_top;
593 for (Address current = promoted_mark - kPointerSize;
594 current >= previous_top;
595 current -= kPointerSize) {
596 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000597 object->Iterate(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598 UpdateRSet(object);
599 }
600 promoted_mark = previous_top;
601 }
602
603 if (has_processed_weak_pointers) break; // We are done.
604 // Copy objects reachable from weak pointers.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000605 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 has_processed_weak_pointers = true;
607 }
608
609 // Set age mark.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000610 new_space_.set_age_mark(new_mark);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611
612 LOG(ResourceEvent("scavenge", "end"));
613
614 gc_state_ = NOT_IN_GC;
615}
616
617
618void Heap::ClearRSetRange(Address start, int size_in_bytes) {
619 uint32_t start_bit;
620 Address start_word_address =
621 Page::ComputeRSetBitPosition(start, 0, &start_bit);
622 uint32_t end_bit;
623 Address end_word_address =
624 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
625 0,
626 &end_bit);
627
628 // We want to clear the bits in the starting word starting with the
629 // first bit, and in the ending word up to and including the last
630 // bit. Build a pair of bitmasks to do that.
631 uint32_t start_bitmask = start_bit - 1;
632 uint32_t end_bitmask = ~((end_bit << 1) - 1);
633
634 // If the start address and end address are the same, we mask that
635 // word once, otherwise mask the starting and ending word
636 // separately and all the ones in between.
637 if (start_word_address == end_word_address) {
638 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
639 } else {
640 Memory::uint32_at(start_word_address) &= start_bitmask;
641 Memory::uint32_at(end_word_address) &= end_bitmask;
642 start_word_address += kIntSize;
643 memset(start_word_address, 0, end_word_address - start_word_address);
644 }
645}
646
647
648class UpdateRSetVisitor: public ObjectVisitor {
649 public:
650
651 void VisitPointer(Object** p) {
652 UpdateRSet(p);
653 }
654
655 void VisitPointers(Object** start, Object** end) {
656 // Update a store into slots [start, end), used (a) to update remembered
657 // set when promoting a young object to old space or (b) to rebuild
658 // remembered sets after a mark-compact collection.
659 for (Object** p = start; p < end; p++) UpdateRSet(p);
660 }
661 private:
662
663 void UpdateRSet(Object** p) {
664 // The remembered set should not be set. It should be clear for objects
665 // newly copied to old space, and it is cleared before rebuilding in the
666 // mark-compact collector.
667 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
668 if (Heap::InNewSpace(*p)) {
669 Page::SetRSet(reinterpret_cast<Address>(p), 0);
670 }
671 }
672};
673
674
675int Heap::UpdateRSet(HeapObject* obj) {
676 ASSERT(!InNewSpace(obj));
677 // Special handling of fixed arrays to iterate the body based on the start
678 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
679 // will not work because Page::SetRSet needs to have the start of the
680 // object.
681 if (obj->IsFixedArray()) {
682 FixedArray* array = FixedArray::cast(obj);
683 int length = array->length();
684 for (int i = 0; i < length; i++) {
685 int offset = FixedArray::kHeaderSize + i * kPointerSize;
686 ASSERT(!Page::IsRSetSet(obj->address(), offset));
687 if (Heap::InNewSpace(array->get(i))) {
688 Page::SetRSet(obj->address(), offset);
689 }
690 }
691 } else if (!obj->IsCode()) {
692 // Skip code object, we know it does not contain inter-generational
693 // pointers.
694 UpdateRSetVisitor v;
695 obj->Iterate(&v);
696 }
697 return obj->Size();
698}
699
700
701void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000702 // By definition, we do not care about remembered set bits in code or data
703 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704 map_space_->ClearRSet();
705 RebuildRSets(map_space_);
706
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000707 old_pointer_space_->ClearRSet();
708 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709
710 Heap::lo_space_->ClearRSet();
711 RebuildRSets(lo_space_);
712}
713
714
715void Heap::RebuildRSets(PagedSpace* space) {
716 HeapObjectIterator it(space);
717 while (it.has_next()) Heap::UpdateRSet(it.next());
718}
719
720
721void Heap::RebuildRSets(LargeObjectSpace* space) {
722 LargeObjectIterator it(space);
723 while (it.has_next()) Heap::UpdateRSet(it.next());
724}
725
726
727#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
728void Heap::RecordCopiedObject(HeapObject* obj) {
729 bool should_record = false;
730#ifdef DEBUG
731 should_record = FLAG_heap_stats;
732#endif
733#ifdef ENABLE_LOGGING_AND_PROFILING
734 should_record = should_record || FLAG_log_gc;
735#endif
736 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000737 if (new_space_.Contains(obj)) {
738 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000740 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000741 }
742 }
743}
744#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
745
746
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000747
748HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000749 HeapObject* target,
750 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000751 // Copy the content of source to target.
752 CopyBlock(reinterpret_cast<Object**>(target->address()),
753 reinterpret_cast<Object**>(source->address()),
754 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000755
kasper.lund7276f142008-07-30 08:49:36 +0000756 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000757 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758
759 // Update NewSpace stats if necessary.
760#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
761 RecordCopiedObject(target);
762#endif
763
764 return target;
765}
766
767
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000768// Inlined function.
769void Heap::ScavengeObject(HeapObject** p, HeapObject* object) {
770 ASSERT(InFromSpace(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000771
kasper.lund7276f142008-07-30 08:49:36 +0000772 // We use the first word (where the map pointer usually is) of a heap
773 // object to record the forwarding pointer. A forwarding pointer can
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000774 // point to an old space, the code space, or the to space of the new
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000776 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000777
kasper.lund7276f142008-07-30 08:49:36 +0000778 // If the first word is a forwarding address, the object has already been
779 // copied.
780 if (first_word.IsForwardingAddress()) {
781 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782 return;
783 }
784
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000785 // Call the slow part of scavenge object.
786 return ScavengeObjectSlow(p, object);
787}
788
ager@chromium.org870a0b62008-11-04 11:43:05 +0000789
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000790static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000791 // A ConsString object with Heap::empty_string() as the right side
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000792 // is a candidate for being shortcut by the scavenger.
793 ASSERT(object->map() == map);
ager@chromium.org870a0b62008-11-04 11:43:05 +0000794 if (map->instance_type() >= FIRST_NONSTRING_TYPE) return false;
ager@chromium.orgc3e50d82008-11-05 11:53:10 +0000795 return (StringShape(map).representation_tag() == kConsStringTag) &&
ager@chromium.org870a0b62008-11-04 11:43:05 +0000796 (ConsString::cast(object)->unchecked_second() == Heap::empty_string());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000797}
798
799
800void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
801 ASSERT(InFromSpace(object));
802 MapWord first_word = object->map_word();
803 ASSERT(!first_word.IsForwardingAddress());
804
805 // Optimization: Bypass flattened ConsString objects.
806 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000807 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808 *p = object;
809 // After patching *p we have to repeat the checks that object is in the
810 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000811 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000812 first_word = object->map_word();
813 if (first_word.IsForwardingAddress()) {
814 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000815 return;
816 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 }
818
kasper.lund7276f142008-07-30 08:49:36 +0000819 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820 // If the object should be promoted, we try to copy it to old space.
821 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000822 OldSpace* target_space = Heap::TargetSpace(object);
823 ASSERT(target_space == Heap::old_pointer_space_ ||
824 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000825 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826 if (!result->IsFailure()) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000827 *p = MigrateObject(object, HeapObject::cast(result), object_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000828 if (target_space == Heap::old_pointer_space_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000829 // Record the object's address at the top of the to space, to allow
830 // it to be swept by the scavenger.
831 promoted_top -= kPointerSize;
832 Memory::Object_at(promoted_top) = *p;
833 } else {
834#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000835 // Objects promoted to the data space should not have pointers to
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 // new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000837 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838 (*p)->Iterate(&v);
839#endif
840 }
841 return;
842 }
843 }
844
845 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000846 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847 // Failed allocation at this point is utterly unexpected.
848 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000849 *p = MigrateObject(object, HeapObject::cast(result), object_size);
850}
851
852
853void Heap::ScavengePointer(HeapObject** p) {
854 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000855}
856
857
858Object* Heap::AllocatePartialMap(InstanceType instance_type,
859 int instance_size) {
860 Object* result = AllocateRawMap(Map::kSize);
861 if (result->IsFailure()) return result;
862
863 // Map::cast cannot be used due to uninitialized map field.
864 reinterpret_cast<Map*>(result)->set_map(meta_map());
865 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
866 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000867 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
869 return result;
870}
871
872
873Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
874 Object* result = AllocateRawMap(Map::kSize);
875 if (result->IsFailure()) return result;
876
877 Map* map = reinterpret_cast<Map*>(result);
878 map->set_map(meta_map());
879 map->set_instance_type(instance_type);
880 map->set_prototype(null_value());
881 map->set_constructor(null_value());
882 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +0000883 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000884 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000885 map->set_code_cache(empty_fixed_array());
886 map->set_unused_property_fields(0);
887 map->set_bit_field(0);
888 return map;
889}
890
891
892bool Heap::CreateInitialMaps() {
893 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
894 if (obj->IsFailure()) return false;
895
896 // Map::cast cannot be used due to uninitialized map field.
897 meta_map_ = reinterpret_cast<Map*>(obj);
898 meta_map()->set_map(meta_map());
899
900 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
901 if (obj->IsFailure()) return false;
902 fixed_array_map_ = Map::cast(obj);
903
904 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
905 if (obj->IsFailure()) return false;
906 oddball_map_ = Map::cast(obj);
907
908 // Allocate the empty array
909 obj = AllocateEmptyFixedArray();
910 if (obj->IsFailure()) return false;
911 empty_fixed_array_ = FixedArray::cast(obj);
912
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000913 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914 if (obj->IsFailure()) return false;
915 null_value_ = obj;
916
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000917 // Allocate the empty descriptor array. AllocateMap can now be used.
918 obj = AllocateEmptyFixedArray();
919 if (obj->IsFailure()) return false;
920 // There is a check against empty_descriptor_array() in cast().
921 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000922
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000923 // Fix the instance_descriptors for the existing maps.
924 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 meta_map()->set_code_cache(empty_fixed_array());
926
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000927 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000928 fixed_array_map()->set_code_cache(empty_fixed_array());
929
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +0000930 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 oddball_map()->set_code_cache(empty_fixed_array());
932
933 // Fix prototype object for existing maps.
934 meta_map()->set_prototype(null_value());
935 meta_map()->set_constructor(null_value());
936
937 fixed_array_map()->set_prototype(null_value());
938 fixed_array_map()->set_constructor(null_value());
939 oddball_map()->set_prototype(null_value());
940 oddball_map()->set_constructor(null_value());
941
942 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
943 if (obj->IsFailure()) return false;
944 heap_number_map_ = Map::cast(obj);
945
946 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
947 if (obj->IsFailure()) return false;
948 proxy_map_ = Map::cast(obj);
949
950#define ALLOCATE_STRING_MAP(type, size, name) \
951 obj = AllocateMap(type, size); \
952 if (obj->IsFailure()) return false; \
953 name##_map_ = Map::cast(obj);
954 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
955#undef ALLOCATE_STRING_MAP
956
ager@chromium.org7c537e22008-10-16 08:43:32 +0000957 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958 if (obj->IsFailure()) return false;
959 undetectable_short_string_map_ = Map::cast(obj);
960 undetectable_short_string_map_->set_is_undetectable();
961
ager@chromium.org7c537e22008-10-16 08:43:32 +0000962 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963 if (obj->IsFailure()) return false;
964 undetectable_medium_string_map_ = Map::cast(obj);
965 undetectable_medium_string_map_->set_is_undetectable();
966
ager@chromium.org7c537e22008-10-16 08:43:32 +0000967 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000968 if (obj->IsFailure()) return false;
969 undetectable_long_string_map_ = Map::cast(obj);
970 undetectable_long_string_map_->set_is_undetectable();
971
ager@chromium.org7c537e22008-10-16 08:43:32 +0000972 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000973 if (obj->IsFailure()) return false;
974 undetectable_short_ascii_string_map_ = Map::cast(obj);
975 undetectable_short_ascii_string_map_->set_is_undetectable();
976
ager@chromium.org7c537e22008-10-16 08:43:32 +0000977 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000978 if (obj->IsFailure()) return false;
979 undetectable_medium_ascii_string_map_ = Map::cast(obj);
980 undetectable_medium_ascii_string_map_->set_is_undetectable();
981
ager@chromium.org7c537e22008-10-16 08:43:32 +0000982 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983 if (obj->IsFailure()) return false;
984 undetectable_long_ascii_string_map_ = Map::cast(obj);
985 undetectable_long_ascii_string_map_->set_is_undetectable();
986
987 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
988 if (obj->IsFailure()) return false;
989 byte_array_map_ = Map::cast(obj);
990
991 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
992 if (obj->IsFailure()) return false;
993 code_map_ = Map::cast(obj);
994
995 obj = AllocateMap(FILLER_TYPE, kPointerSize);
996 if (obj->IsFailure()) return false;
997 one_word_filler_map_ = Map::cast(obj);
998
999 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1000 if (obj->IsFailure()) return false;
1001 two_word_filler_map_ = Map::cast(obj);
1002
1003#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1004 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1005 if (obj->IsFailure()) return false; \
1006 name##_map_ = Map::cast(obj);
1007 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1008#undef ALLOCATE_STRUCT_MAP
1009
ager@chromium.org236ad962008-09-25 09:45:57 +00001010 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001011 if (obj->IsFailure()) return false;
1012 hash_table_map_ = Map::cast(obj);
1013
ager@chromium.org236ad962008-09-25 09:45:57 +00001014 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001015 if (obj->IsFailure()) return false;
1016 context_map_ = Map::cast(obj);
1017
ager@chromium.org236ad962008-09-25 09:45:57 +00001018 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001019 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001020 catch_context_map_ = Map::cast(obj);
1021
1022 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1023 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 global_context_map_ = Map::cast(obj);
1025
1026 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1027 if (obj->IsFailure()) return false;
1028 boilerplate_function_map_ = Map::cast(obj);
1029
1030 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1031 if (obj->IsFailure()) return false;
1032 shared_function_info_map_ = Map::cast(obj);
1033
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001034 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001035 return true;
1036}
1037
1038
1039Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1040 // Statically ensure that it is safe to allocate heap numbers in paged
1041 // spaces.
1042 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001043 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001044 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001045 if (result->IsFailure()) return result;
1046
1047 HeapObject::cast(result)->set_map(heap_number_map());
1048 HeapNumber::cast(result)->set_value(value);
1049 return result;
1050}
1051
1052
1053Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001054 // Use general version, if we're forced to always allocate.
1055 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001056 // This version of AllocateHeapNumber is optimized for
1057 // allocation in new space.
1058 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1059 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001060 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061 if (result->IsFailure()) return result;
1062 HeapObject::cast(result)->set_map(heap_number_map());
1063 HeapNumber::cast(result)->set_value(value);
1064 return result;
1065}
1066
1067
1068Object* Heap::CreateOddball(Map* map,
1069 const char* to_string,
1070 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001071 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001072 if (result->IsFailure()) return result;
1073 return Oddball::cast(result)->Initialize(to_string, to_number);
1074}
1075
1076
1077bool Heap::CreateApiObjects() {
1078 Object* obj;
1079
1080 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1081 if (obj->IsFailure()) return false;
1082 neander_map_ = Map::cast(obj);
1083
1084 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1085 if (obj->IsFailure()) return false;
1086 Object* elements = AllocateFixedArray(2);
1087 if (elements->IsFailure()) return false;
1088 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1089 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1090 message_listeners_ = JSObject::cast(obj);
1091
1092 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1093 if (obj->IsFailure()) return false;
1094 elements = AllocateFixedArray(2);
1095 if (elements->IsFailure()) return false;
1096 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1097 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1098 debug_event_listeners_ = JSObject::cast(obj);
1099
1100 return true;
1101}
1102
1103void Heap::CreateFixedStubs() {
1104 // Here we create roots for fixed stubs. They are needed at GC
1105 // for cooking and uncooking (check out frames.cc).
1106 // The eliminates the need for doing dictionary lookup in the
1107 // stub cache for these stubs.
1108 HandleScope scope;
1109 {
1110 CEntryStub stub;
1111 c_entry_code_ = *stub.GetCode();
1112 }
1113 {
1114 CEntryDebugBreakStub stub;
1115 c_entry_debug_break_code_ = *stub.GetCode();
1116 }
1117 {
1118 JSEntryStub stub;
1119 js_entry_code_ = *stub.GetCode();
1120 }
1121 {
1122 JSConstructEntryStub stub;
1123 js_construct_entry_code_ = *stub.GetCode();
1124 }
1125}
1126
1127
1128bool Heap::CreateInitialObjects() {
1129 Object* obj;
1130
1131 // The -0 value must be set before NumberFromDouble works.
1132 obj = AllocateHeapNumber(-0.0, TENURED);
1133 if (obj->IsFailure()) return false;
1134 minus_zero_value_ = obj;
1135 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1136
1137 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1138 if (obj->IsFailure()) return false;
1139 nan_value_ = obj;
1140
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001141 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001142 if (obj->IsFailure()) return false;
1143 undefined_value_ = obj;
1144 ASSERT(!InNewSpace(undefined_value()));
1145
1146 // Allocate initial symbol table.
1147 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1148 if (obj->IsFailure()) return false;
1149 symbol_table_ = obj;
1150
1151 // Assign the print strings for oddballs after creating symboltable.
1152 Object* symbol = LookupAsciiSymbol("undefined");
1153 if (symbol->IsFailure()) return false;
1154 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1155 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1156
1157 // Assign the print strings for oddballs after creating symboltable.
1158 symbol = LookupAsciiSymbol("null");
1159 if (symbol->IsFailure()) return false;
1160 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1161 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1162
1163 // Allocate the null_value
1164 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1165 if (obj->IsFailure()) return false;
1166
1167 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1168 if (obj->IsFailure()) return false;
1169 true_value_ = obj;
1170
1171 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1172 if (obj->IsFailure()) return false;
1173 false_value_ = obj;
1174
1175 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1176 if (obj->IsFailure()) return false;
1177 the_hole_value_ = obj;
1178
1179 // Allocate the empty string.
1180 obj = AllocateRawAsciiString(0, TENURED);
1181 if (obj->IsFailure()) return false;
1182 empty_string_ = String::cast(obj);
1183
1184#define SYMBOL_INITIALIZE(name, string) \
1185 obj = LookupAsciiSymbol(string); \
1186 if (obj->IsFailure()) return false; \
1187 (name##_) = String::cast(obj);
1188 SYMBOL_LIST(SYMBOL_INITIALIZE)
1189#undef SYMBOL_INITIALIZE
1190
1191 // Allocate the proxy for __proto__.
1192 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1193 if (obj->IsFailure()) return false;
1194 prototype_accessors_ = Proxy::cast(obj);
1195
1196 // Allocate the code_stubs dictionary.
1197 obj = Dictionary::Allocate(4);
1198 if (obj->IsFailure()) return false;
1199 code_stubs_ = Dictionary::cast(obj);
1200
1201 // Allocate the non_monomorphic_cache used in stub-cache.cc
1202 obj = Dictionary::Allocate(4);
1203 if (obj->IsFailure()) return false;
1204 non_monomorphic_cache_ = Dictionary::cast(obj);
1205
1206 CreateFixedStubs();
1207
1208 // Allocate the number->string conversion cache
1209 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1210 if (obj->IsFailure()) return false;
1211 number_string_cache_ = FixedArray::cast(obj);
1212
1213 // Allocate cache for single character strings.
1214 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1215 if (obj->IsFailure()) return false;
1216 single_character_string_cache_ = FixedArray::cast(obj);
1217
1218 // Allocate cache for external strings pointing to native source code.
1219 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1220 if (obj->IsFailure()) return false;
1221 natives_source_cache_ = FixedArray::cast(obj);
1222
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001223 // Initialize keyed lookup cache.
1224 ClearKeyedLookupCache();
1225
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001226 // Initialize compilation cache.
1227 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001228
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229 return true;
1230}
1231
1232
1233static inline int double_get_hash(double d) {
1234 DoubleRepresentation rep(d);
1235 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1236 (Heap::kNumberStringCacheSize - 1));
1237}
1238
1239
1240static inline int smi_get_hash(Smi* smi) {
1241 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1242}
1243
1244
1245
1246Object* Heap::GetNumberStringCache(Object* number) {
1247 int hash;
1248 if (number->IsSmi()) {
1249 hash = smi_get_hash(Smi::cast(number));
1250 } else {
1251 hash = double_get_hash(number->Number());
1252 }
1253 Object* key = number_string_cache_->get(hash * 2);
1254 if (key == number) {
1255 return String::cast(number_string_cache_->get(hash * 2 + 1));
1256 } else if (key->IsHeapNumber() &&
1257 number->IsHeapNumber() &&
1258 key->Number() == number->Number()) {
1259 return String::cast(number_string_cache_->get(hash * 2 + 1));
1260 }
1261 return undefined_value();
1262}
1263
1264
1265void Heap::SetNumberStringCache(Object* number, String* string) {
1266 int hash;
1267 if (number->IsSmi()) {
1268 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001269 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001270 } else {
1271 hash = double_get_hash(number->Number());
1272 number_string_cache_->set(hash * 2, number);
1273 }
1274 number_string_cache_->set(hash * 2 + 1, string);
1275}
1276
1277
1278Object* Heap::SmiOrNumberFromDouble(double value,
1279 bool new_object,
1280 PretenureFlag pretenure) {
1281 // We need to distinguish the minus zero value and this cannot be
1282 // done after conversion to int. Doing this by comparing bit
1283 // patterns is faster than using fpclassify() et al.
1284 static const DoubleRepresentation plus_zero(0.0);
1285 static const DoubleRepresentation minus_zero(-0.0);
1286 static const DoubleRepresentation nan(OS::nan_value());
1287 ASSERT(minus_zero_value_ != NULL);
1288 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1289
1290 DoubleRepresentation rep(value);
1291 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1292 if (rep.bits == minus_zero.bits) {
1293 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1294 : minus_zero_value_;
1295 }
1296 if (rep.bits == nan.bits) {
1297 return new_object
1298 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1299 : nan_value_;
1300 }
1301
1302 // Try to represent the value as a tagged small integer.
1303 int int_value = FastD2I(value);
1304 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1305 return Smi::FromInt(int_value);
1306 }
1307
1308 // Materialize the value in the heap.
1309 return AllocateHeapNumber(value, pretenure);
1310}
1311
1312
1313Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1314 return SmiOrNumberFromDouble(value,
1315 true /* number object must be new */,
1316 pretenure);
1317}
1318
1319
1320Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1321 return SmiOrNumberFromDouble(value,
1322 false /* use preallocated NaN, -0.0 */,
1323 pretenure);
1324}
1325
1326
1327Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1328 // Statically ensure that it is safe to allocate proxies in paged spaces.
1329 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001330 AllocationSpace space =
1331 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001332 Object* result = Allocate(proxy_map(), space);
1333 if (result->IsFailure()) return result;
1334
1335 Proxy::cast(result)->set_proxy(proxy);
1336 return result;
1337}
1338
1339
1340Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1341 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1342 if (result->IsFailure()) return result;
1343
1344 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1345 share->set_name(name);
1346 Code* illegal = Builtins::builtin(Builtins::Illegal);
1347 share->set_code(illegal);
1348 share->set_expected_nof_properties(0);
1349 share->set_length(0);
1350 share->set_formal_parameter_count(0);
1351 share->set_instance_class_name(Object_symbol());
1352 share->set_function_data(undefined_value());
1353 share->set_lazy_load_data(undefined_value());
1354 share->set_script(undefined_value());
1355 share->set_start_position_and_type(0);
1356 share->set_debug_info(undefined_value());
1357 return result;
1358}
1359
1360
ager@chromium.org870a0b62008-11-04 11:43:05 +00001361Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001362 String* second) {
1363 StringShape first_shape(first);
1364 StringShape second_shape(second);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001365 int first_length = first->length(first_shape);
1366 int second_length = second->length(second_shape);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001367 int length = first_length + second_length;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001368 bool is_ascii = first_shape.IsAsciiRepresentation()
1369 && second_shape.IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001370
1371 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001372 if (length < String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001373 ASSERT(first->IsFlat(first_shape));
1374 ASSERT(second->IsFlat(second_shape));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001375 if (is_ascii) {
1376 Object* result = AllocateRawAsciiString(length);
1377 if (result->IsFailure()) return result;
1378 // Copy the characters into the new object.
1379 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001380 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1381 String::WriteToFlat(second,
1382 second_shape,
1383 dest + first_length,
1384 0,
1385 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001386 return result;
1387 } else {
1388 Object* result = AllocateRawTwoByteString(length);
1389 if (result->IsFailure()) return result;
1390 // Copy the characters into the new object.
1391 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001392 String::WriteToFlat(first, first_shape, dest, 0, first_length);
1393 String::WriteToFlat(second,
1394 second_shape,
1395 dest + first_length,
1396 0,
1397 second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001398 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001400 }
1401
1402 Map* map;
1403 if (length <= String::kMaxShortStringSize) {
1404 map = is_ascii ? short_cons_ascii_string_map()
1405 : short_cons_string_map();
1406 } else if (length <= String::kMaxMediumStringSize) {
1407 map = is_ascii ? medium_cons_ascii_string_map()
1408 : medium_cons_string_map();
1409 } else {
1410 map = is_ascii ? long_cons_ascii_string_map()
1411 : long_cons_string_map();
1412 }
1413
1414 Object* result = Allocate(map, NEW_SPACE);
1415 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001416 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001418 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1419 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 return result;
1422}
1423
1424
ager@chromium.org870a0b62008-11-04 11:43:05 +00001425Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001426 int start,
1427 int end) {
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001428 StringShape buffer_shape(buffer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001429 int length = end - start;
1430
1431 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001432 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001433 return Heap::AllocateSubString(buffer, buffer_shape, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001434 }
1435
1436 Map* map;
1437 if (length <= String::kMaxShortStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001438 map = buffer_shape.IsAsciiRepresentation() ?
1439 short_sliced_ascii_string_map() :
1440 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001442 map = buffer_shape.IsAsciiRepresentation() ?
1443 medium_sliced_ascii_string_map() :
1444 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001445 } else {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001446 map = buffer_shape.IsAsciiRepresentation() ?
1447 long_sliced_ascii_string_map() :
1448 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001449 }
1450
1451 Object* result = Allocate(map, NEW_SPACE);
1452 if (result->IsFailure()) return result;
1453
1454 SlicedString* sliced_string = SlicedString::cast(result);
1455 sliced_string->set_buffer(buffer);
1456 sliced_string->set_start(start);
1457 sliced_string->set_length(length);
1458
1459 return result;
1460}
1461
1462
ager@chromium.org870a0b62008-11-04 11:43:05 +00001463Object* Heap::AllocateSubString(String* buffer,
1464 StringShape buffer_shape,
1465 int start,
1466 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467 int length = end - start;
1468
ager@chromium.org7c537e22008-10-16 08:43:32 +00001469 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001470 return Heap::LookupSingleCharacterStringFromCode(
1471 buffer->Get(buffer_shape, start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001472 }
1473
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001474 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.org870a0b62008-11-04 11:43:05 +00001475 if (!buffer->IsFlat(buffer_shape)) {
1476 buffer->TryFlatten(buffer_shape);
1477 buffer_shape = StringShape(buffer);
1478 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001479
ager@chromium.org870a0b62008-11-04 11:43:05 +00001480 Object* result = buffer_shape.IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001481 ? AllocateRawAsciiString(length)
1482 : AllocateRawTwoByteString(length);
1483 if (result->IsFailure()) return result;
1484
1485 // Copy the characters into the new object.
1486 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001487 StringShape result_shape(string_result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001488 StringHasher hasher(length);
1489 int i = 0;
1490 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001491 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001492 hasher.AddCharacter(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001493 string_result->Set(result_shape, i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001495 for (; i < length; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001496 uc32 c = buffer->Get(buffer_shape, start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001497 hasher.AddCharacterNoIndex(c);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001498 string_result->Set(result_shape, i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001499 }
1500 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001501 return result;
1502}
1503
1504
1505Object* Heap::AllocateExternalStringFromAscii(
1506 ExternalAsciiString::Resource* resource) {
1507 Map* map;
1508 int length = resource->length();
1509 if (length <= String::kMaxShortStringSize) {
1510 map = short_external_ascii_string_map();
1511 } else if (length <= String::kMaxMediumStringSize) {
1512 map = medium_external_ascii_string_map();
1513 } else {
1514 map = long_external_ascii_string_map();
1515 }
1516
1517 Object* result = Allocate(map, NEW_SPACE);
1518 if (result->IsFailure()) return result;
1519
1520 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1521 external_string->set_length(length);
1522 external_string->set_resource(resource);
1523
1524 return result;
1525}
1526
1527
1528Object* Heap::AllocateExternalStringFromTwoByte(
1529 ExternalTwoByteString::Resource* resource) {
1530 Map* map;
1531 int length = resource->length();
1532 if (length <= String::kMaxShortStringSize) {
1533 map = short_external_string_map();
1534 } else if (length <= String::kMaxMediumStringSize) {
1535 map = medium_external_string_map();
1536 } else {
1537 map = long_external_string_map();
1538 }
1539
1540 Object* result = Allocate(map, NEW_SPACE);
1541 if (result->IsFailure()) return result;
1542
1543 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1544 external_string->set_length(length);
1545 external_string->set_resource(resource);
1546
1547 return result;
1548}
1549
1550
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001551Object* Heap::AllocateExternalSymbolFromTwoByte(
1552 ExternalTwoByteString::Resource* resource) {
1553 Map* map;
1554 int length = resource->length();
1555 if (length <= String::kMaxShortStringSize) {
1556 map = short_external_symbol_map();
1557 } else if (length <= String::kMaxMediumStringSize) {
1558 map = medium_external_symbol_map();
1559 } else {
1560 map = long_external_symbol_map();
1561 }
1562
1563 Object* result = Allocate(map, OLD_DATA_SPACE);
1564 if (result->IsFailure()) return result;
1565
1566 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1567 external_string->set_length(length);
1568 external_string->set_resource(resource);
1569
1570 return result;
1571}
1572
1573
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001574Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575 if (code <= String::kMaxAsciiCharCode) {
1576 Object* value = Heap::single_character_string_cache()->get(code);
1577 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001578
1579 char buffer[1];
1580 buffer[0] = static_cast<char>(code);
1581 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1582
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 Heap::single_character_string_cache()->set(code, result);
1585 return result;
1586 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001587
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001588 Object* result = Heap::AllocateRawTwoByteString(1);
1589 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001590 String* answer = String::cast(result);
1591 answer->Set(StringShape(answer), 0, code);
1592 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001593}
1594
1595
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001596Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1597 if (pretenure == NOT_TENURED) {
1598 return AllocateByteArray(length);
1599 }
1600 int size = ByteArray::SizeFor(length);
1601 AllocationSpace space =
1602 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1603
1604 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1605
1606 if (result->IsFailure()) return result;
1607
1608 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1609 reinterpret_cast<Array*>(result)->set_length(length);
1610 return result;
1611}
1612
1613
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614Object* Heap::AllocateByteArray(int length) {
1615 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001616 AllocationSpace space =
1617 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001619 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001620
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621 if (result->IsFailure()) return result;
1622
1623 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1624 reinterpret_cast<Array*>(result)->set_length(length);
1625 return result;
1626}
1627
1628
1629Object* Heap::CreateCode(const CodeDesc& desc,
1630 ScopeInfo<>* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001631 Code::Flags flags,
1632 Code** self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 // Compute size
1634 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1635 int sinfo_size = 0;
1636 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1637 int obj_size = Code::SizeFor(body_size, sinfo_size);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001638 Object* result;
1639 if (obj_size > MaxHeapObjectSize()) {
1640 result = lo_space_->AllocateRawCode(obj_size);
1641 } else {
1642 result = code_space_->AllocateRaw(obj_size);
1643 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001644
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001645 if (result->IsFailure()) return result;
1646
1647 // Initialize the object
1648 HeapObject::cast(result)->set_map(code_map());
1649 Code* code = Code::cast(result);
1650 code->set_instruction_size(desc.instr_size);
1651 code->set_relocation_size(desc.reloc_size);
1652 code->set_sinfo_size(sinfo_size);
1653 code->set_flags(flags);
1654 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001655 // Allow self references to created code object.
1656 if (self_reference != NULL) {
1657 *self_reference = code;
1658 }
1659 // Migrate generated code.
1660 // The generated code can contain Object** values (typically from handles)
1661 // that are dereferenced during the copy to point directly to the actual heap
1662 // objects. These pointers can include references to the code object itself,
1663 // through the self_reference parameter.
1664 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001666 LOG(CodeAllocateEvent(code, desc.origin));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001667
1668#ifdef DEBUG
1669 code->Verify();
1670#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001671 return code;
1672}
1673
1674
1675Object* Heap::CopyCode(Code* code) {
1676 // Allocate an object the same size as the code object.
1677 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001678 Object* result;
1679 if (obj_size > MaxHeapObjectSize()) {
1680 result = lo_space_->AllocateRawCode(obj_size);
1681 } else {
1682 result = code_space_->AllocateRaw(obj_size);
1683 }
1684
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001685 if (result->IsFailure()) return result;
1686
1687 // Copy code object.
1688 Address old_addr = code->address();
1689 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001690 CopyBlock(reinterpret_cast<Object**>(new_addr),
1691 reinterpret_cast<Object**>(old_addr),
1692 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001693 // Relocate the copy.
1694 Code* new_code = Code::cast(result);
1695 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001696 return new_code;
1697}
1698
1699
1700Object* Heap::Allocate(Map* map, AllocationSpace space) {
1701 ASSERT(gc_state_ == NOT_IN_GC);
1702 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001703 Object* result = AllocateRaw(map->instance_size(),
1704 space,
1705 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 if (result->IsFailure()) return result;
1707 HeapObject::cast(result)->set_map(map);
1708 return result;
1709}
1710
1711
1712Object* Heap::InitializeFunction(JSFunction* function,
1713 SharedFunctionInfo* shared,
1714 Object* prototype) {
1715 ASSERT(!prototype->IsMap());
1716 function->initialize_properties();
1717 function->initialize_elements();
1718 function->set_shared(shared);
1719 function->set_prototype_or_initial_map(prototype);
1720 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001721 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 return function;
1723}
1724
1725
1726Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001727 // Allocate the prototype. Make sure to use the object function
1728 // from the function's context, since the function can be from a
1729 // different context.
1730 JSFunction* object_function =
1731 function->context()->global_context()->object_function();
1732 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001733 if (prototype->IsFailure()) return prototype;
1734 // When creating the prototype for the function we must set its
1735 // constructor to the function.
1736 Object* result =
1737 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1738 function,
1739 DONT_ENUM);
1740 if (result->IsFailure()) return result;
1741 return prototype;
1742}
1743
1744
1745Object* Heap::AllocateFunction(Map* function_map,
1746 SharedFunctionInfo* shared,
1747 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001748 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001749 if (result->IsFailure()) return result;
1750 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1751}
1752
1753
1754Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001755 // To get fast allocation and map sharing for arguments objects we
1756 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757
1758 // This calls Copy directly rather than using Heap::AllocateRaw so we
1759 // duplicate the check here.
1760 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1761
1762 JSObject* boilerplate =
1763 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001764
1765 // Make the clone.
1766 Map* map = boilerplate->map();
1767 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001768 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001769 if (result->IsFailure()) return result;
1770
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001771 // Copy the content. The arguments boilerplate doesn't have any
1772 // fields that point to new space so it's safe to skip the write
1773 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001774 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1775 reinterpret_cast<Object**>(boilerplate->address()),
1776 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001778 // Set the two properties.
1779 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001780 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001781 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1782 Smi::FromInt(length),
1783 SKIP_WRITE_BARRIER);
1784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001785 // Check the state of the object
1786 ASSERT(JSObject::cast(result)->HasFastProperties());
1787 ASSERT(JSObject::cast(result)->HasFastElements());
1788
1789 return result;
1790}
1791
1792
1793Object* Heap::AllocateInitialMap(JSFunction* fun) {
1794 ASSERT(!fun->has_initial_map());
1795
ager@chromium.org7c537e22008-10-16 08:43:32 +00001796 // First create a new map with the expected number of properties being
1797 // allocated in-object.
1798 int expected_nof_properties = fun->shared()->expected_nof_properties();
1799 int instance_size = JSObject::kHeaderSize +
1800 expected_nof_properties * kPointerSize;
1801 if (instance_size > JSObject::kMaxInstanceSize) {
1802 instance_size = JSObject::kMaxInstanceSize;
1803 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1804 kPointerSize;
1805 }
1806 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001807 if (map_obj->IsFailure()) return map_obj;
1808
1809 // Fetch or allocate prototype.
1810 Object* prototype;
1811 if (fun->has_instance_prototype()) {
1812 prototype = fun->instance_prototype();
1813 } else {
1814 prototype = AllocateFunctionPrototype(fun);
1815 if (prototype->IsFailure()) return prototype;
1816 }
1817 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001818 map->set_inobject_properties(expected_nof_properties);
1819 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001820 map->set_prototype(prototype);
1821 return map;
1822}
1823
1824
1825void Heap::InitializeJSObjectFromMap(JSObject* obj,
1826 FixedArray* properties,
1827 Map* map) {
1828 obj->set_properties(properties);
1829 obj->initialize_elements();
1830 // TODO(1240798): Initialize the object's body using valid initial values
1831 // according to the object's initial map. For example, if the map's
1832 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1833 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1834 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1835 // verification code has to cope with (temporarily) invalid objects. See
1836 // for example, JSArray::JSArrayVerify).
1837 obj->InitializeBody(map->instance_size());
1838}
1839
1840
1841Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1842 // JSFunctions should be allocated using AllocateFunction to be
1843 // properly initialized.
1844 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1845
1846 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001847 int prop_size = map->unused_property_fields() - map->inobject_properties();
1848 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001849 if (properties->IsFailure()) return properties;
1850
1851 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001852 AllocationSpace space =
1853 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1855 Object* obj = Allocate(map, space);
1856 if (obj->IsFailure()) return obj;
1857
1858 // Initialize the JSObject.
1859 InitializeJSObjectFromMap(JSObject::cast(obj),
1860 FixedArray::cast(properties),
1861 map);
1862 return obj;
1863}
1864
1865
1866Object* Heap::AllocateJSObject(JSFunction* constructor,
1867 PretenureFlag pretenure) {
1868 // Allocate the initial map if absent.
1869 if (!constructor->has_initial_map()) {
1870 Object* initial_map = AllocateInitialMap(constructor);
1871 if (initial_map->IsFailure()) return initial_map;
1872 constructor->set_initial_map(Map::cast(initial_map));
1873 Map::cast(initial_map)->set_constructor(constructor);
1874 }
1875 // Allocate the object based on the constructors initial map.
1876 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1877}
1878
1879
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001880Object* Heap::CopyJSObject(JSObject* source) {
1881 // Never used to copy functions. If functions need to be copied we
1882 // have to be careful to clear the literals array.
1883 ASSERT(!source->IsJSFunction());
1884
1885 // Make the clone.
1886 Map* map = source->map();
1887 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001888 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001889
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001890 // If we're forced to always allocate, we use the general allocation
1891 // functions which may leave us with an object in old space.
1892 if (always_allocate()) {
1893 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
1894 if (clone->IsFailure()) return clone;
1895 Address clone_address = HeapObject::cast(clone)->address();
1896 CopyBlock(reinterpret_cast<Object**>(clone_address),
1897 reinterpret_cast<Object**>(source->address()),
1898 object_size);
1899 // Update write barrier for all fields that lie beyond the header.
1900 for (int offset = JSObject::kHeaderSize;
1901 offset < object_size;
1902 offset += kPointerSize) {
1903 RecordWrite(clone_address, offset);
1904 }
1905 } else {
1906 clone = new_space_.AllocateRaw(object_size);
1907 if (clone->IsFailure()) return clone;
1908 ASSERT(Heap::InNewSpace(clone));
1909 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00001910 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001911 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
1912 reinterpret_cast<Object**>(source->address()),
1913 object_size);
1914 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001915
1916 FixedArray* elements = FixedArray::cast(source->elements());
1917 FixedArray* properties = FixedArray::cast(source->properties());
1918 // Update elements if necessary.
1919 if (elements->length()> 0) {
1920 Object* elem = CopyFixedArray(elements);
1921 if (elem->IsFailure()) return elem;
1922 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
1923 }
1924 // Update properties if necessary.
1925 if (properties->length() > 0) {
1926 Object* prop = CopyFixedArray(properties);
1927 if (prop->IsFailure()) return prop;
1928 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
1929 }
1930 // Return the new clone.
1931 return clone;
1932}
1933
1934
1935Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
1936 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001937 // Allocate initial map if absent.
1938 if (!constructor->has_initial_map()) {
1939 Object* initial_map = AllocateInitialMap(constructor);
1940 if (initial_map->IsFailure()) return initial_map;
1941 constructor->set_initial_map(Map::cast(initial_map));
1942 Map::cast(initial_map)->set_constructor(constructor);
1943 }
1944
1945 Map* map = constructor->initial_map();
1946
1947 // Check that the already allocated object has the same size as
1948 // objects allocated using the constructor.
1949 ASSERT(map->instance_size() == object->map()->instance_size());
1950
1951 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001952 int prop_size = map->unused_property_fields() - map->inobject_properties();
1953 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001954 if (properties->IsFailure()) return properties;
1955
1956 // Reset the map for the object.
1957 object->set_map(constructor->initial_map());
1958
1959 // Reinitialize the object from the constructor map.
1960 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1961 return object;
1962}
1963
1964
1965Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1966 PretenureFlag pretenure) {
1967 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1968 if (result->IsFailure()) return result;
1969
1970 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001971 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001972 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00001973 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001974 }
1975 return result;
1976}
1977
1978
1979Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1980 PretenureFlag pretenure) {
1981 // Count the number of characters in the UTF-8 string and check if
1982 // it is an ASCII string.
1983 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1984 decoder->Reset(string.start(), string.length());
1985 int chars = 0;
1986 bool is_ascii = true;
1987 while (decoder->has_more()) {
1988 uc32 r = decoder->GetNext();
1989 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1990 chars++;
1991 }
1992
1993 // If the string is ascii, we do not need to convert the characters
1994 // since UTF8 is backwards compatible with ascii.
1995 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1996
1997 Object* result = AllocateRawTwoByteString(chars, pretenure);
1998 if (result->IsFailure()) return result;
1999
2000 // Convert and copy the characters into the new object.
2001 String* string_result = String::cast(result);
2002 decoder->Reset(string.start(), string.length());
ager@chromium.org870a0b62008-11-04 11:43:05 +00002003 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002004 for (int i = 0; i < chars; i++) {
2005 uc32 r = decoder->GetNext();
ager@chromium.org870a0b62008-11-04 11:43:05 +00002006 string_result->Set(result_shape, i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002007 }
2008 return result;
2009}
2010
2011
2012Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2013 PretenureFlag pretenure) {
2014 // Check if the string is an ASCII string.
2015 int i = 0;
2016 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2017
2018 Object* result;
2019 if (i == string.length()) { // It's an ASCII string.
2020 result = AllocateRawAsciiString(string.length(), pretenure);
2021 } else { // It's not an ASCII string.
2022 result = AllocateRawTwoByteString(string.length(), pretenure);
2023 }
2024 if (result->IsFailure()) return result;
2025
2026 // Copy the characters into the new object, which may be either ASCII or
2027 // UTF-16.
2028 String* string_result = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002029 StringShape result_shape(string_result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002030 for (int i = 0; i < string.length(); i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002031 string_result->Set(result_shape, i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002032 }
2033 return result;
2034}
2035
2036
2037Map* Heap::SymbolMapForString(String* string) {
2038 // If the string is in new space it cannot be used as a symbol.
2039 if (InNewSpace(string)) return NULL;
2040
2041 // Find the corresponding symbol map for strings.
2042 Map* map = string->map();
2043
2044 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2045 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2046 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2047
2048 if (map == short_string_map()) return short_symbol_map();
2049 if (map == medium_string_map()) return medium_symbol_map();
2050 if (map == long_string_map()) return long_symbol_map();
2051
2052 if (map == short_cons_string_map()) return short_cons_symbol_map();
2053 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2054 if (map == long_cons_string_map()) return long_cons_symbol_map();
2055
2056 if (map == short_cons_ascii_string_map()) {
2057 return short_cons_ascii_symbol_map();
2058 }
2059 if (map == medium_cons_ascii_string_map()) {
2060 return medium_cons_ascii_symbol_map();
2061 }
2062 if (map == long_cons_ascii_string_map()) {
2063 return long_cons_ascii_symbol_map();
2064 }
2065
2066 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002067 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2068 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002069
2070 if (map == short_sliced_ascii_string_map()) {
2071 return short_sliced_ascii_symbol_map();
2072 }
2073 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002074 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002075 }
2076 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002077 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002078 }
2079
2080 if (map == short_external_string_map()) return short_external_string_map();
2081 if (map == medium_external_string_map()) return medium_external_string_map();
2082 if (map == long_external_string_map()) return long_external_string_map();
2083
2084 if (map == short_external_ascii_string_map()) {
2085 return short_external_ascii_string_map();
2086 }
2087 if (map == medium_external_ascii_string_map()) {
2088 return medium_external_ascii_string_map();
2089 }
2090 if (map == long_external_ascii_string_map()) {
2091 return long_external_ascii_string_map();
2092 }
2093
2094 // No match found.
2095 return NULL;
2096}
2097
2098
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002099Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2100 int chars,
2101 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002102 // Ensure the chars matches the number of characters in the buffer.
2103 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2104 // Determine whether the string is ascii.
2105 bool is_ascii = true;
2106 while (buffer->has_more()) {
2107 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2108 }
2109 buffer->Rewind();
2110
2111 // Compute map and object size.
2112 int size;
2113 Map* map;
2114
2115 if (is_ascii) {
2116 if (chars <= String::kMaxShortStringSize) {
2117 map = short_ascii_symbol_map();
2118 } else if (chars <= String::kMaxMediumStringSize) {
2119 map = medium_ascii_symbol_map();
2120 } else {
2121 map = long_ascii_symbol_map();
2122 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002123 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002124 } else {
2125 if (chars <= String::kMaxShortStringSize) {
2126 map = short_symbol_map();
2127 } else if (chars <= String::kMaxMediumStringSize) {
2128 map = medium_symbol_map();
2129 } else {
2130 map = long_symbol_map();
2131 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002132 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002133 }
2134
2135 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002136 AllocationSpace space =
2137 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002138 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002139 if (result->IsFailure()) return result;
2140
2141 reinterpret_cast<HeapObject*>(result)->set_map(map);
2142 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002143 String* answer = String::cast(result);
2144 StringShape answer_shape(answer);
2145 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002146
ager@chromium.org870a0b62008-11-04 11:43:05 +00002147 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002148
2149 // Fill in the characters.
2150 for (int i = 0; i < chars; i++) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002151 answer->Set(answer_shape, i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002152 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002153 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002154}
2155
2156
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002157// External string resource that only contains a length field. These
2158// are used temporarily when allocating external symbols.
2159class DummyExternalStringResource
2160 : public v8::String::ExternalStringResource {
2161 public:
2162 explicit DummyExternalStringResource(size_t length) : length_(length) { }
2163
2164 virtual const uint16_t* data() const {
2165 UNREACHABLE();
2166 return NULL;
2167 }
2168
2169 virtual size_t length() const { return length_; }
2170 private:
2171 size_t length_;
2172};
2173
2174
2175Object* Heap::AllocateExternalSymbol(Vector<const char> string, int chars) {
2176 // Attempt to allocate the resulting external string first. Use a
2177 // dummy string resource that has the correct length so that we only
2178 // have to patch the external string resource after the callback.
2179 DummyExternalStringResource dummy_resource(chars);
2180 Object* obj = AllocateExternalSymbolFromTwoByte(&dummy_resource);
2181 if (obj->IsFailure()) return obj;
2182 // Perform callback.
2183 v8::String::ExternalStringResource* resource =
2184 global_external_symbol_callback_(string.start(), string.length());
2185 // Patch the resource pointer of the result.
2186 ExternalTwoByteString* result = ExternalTwoByteString::cast(obj);
2187 result->set_resource(resource);
2188 // Force hash code to be computed.
2189 result->Hash();
2190 ASSERT(result->IsEqualTo(string));
2191 return result;
2192}
2193
2194
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002195Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002196 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002197 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002198 if (size > MaxHeapObjectSize()) {
2199 space = LO_SPACE;
2200 }
2201
2202 // Use AllocateRaw rather than Allocate because the object's size cannot be
2203 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002204 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002205 if (result->IsFailure()) return result;
2206
2207 // Determine the map based on the string's length.
2208 Map* map;
2209 if (length <= String::kMaxShortStringSize) {
2210 map = short_ascii_string_map();
2211 } else if (length <= String::kMaxMediumStringSize) {
2212 map = medium_ascii_string_map();
2213 } else {
2214 map = long_ascii_string_map();
2215 }
2216
2217 // Partially initialize the object.
2218 HeapObject::cast(result)->set_map(map);
2219 String::cast(result)->set_length(length);
2220 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2221 return result;
2222}
2223
2224
2225Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002226 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002227 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002228 if (size > MaxHeapObjectSize()) {
2229 space = LO_SPACE;
2230 }
2231
2232 // Use AllocateRaw rather than Allocate because the object's size cannot be
2233 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002234 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002235 if (result->IsFailure()) return result;
2236
2237 // Determine the map based on the string's length.
2238 Map* map;
2239 if (length <= String::kMaxShortStringSize) {
2240 map = short_string_map();
2241 } else if (length <= String::kMaxMediumStringSize) {
2242 map = medium_string_map();
2243 } else {
2244 map = long_string_map();
2245 }
2246
2247 // Partially initialize the object.
2248 HeapObject::cast(result)->set_map(map);
2249 String::cast(result)->set_length(length);
2250 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2251 return result;
2252}
2253
2254
2255Object* Heap::AllocateEmptyFixedArray() {
2256 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002257 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002258 if (result->IsFailure()) return result;
2259 // Initialize the object.
2260 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2261 reinterpret_cast<Array*>(result)->set_length(0);
2262 return result;
2263}
2264
2265
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002266Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002267 // Use the general function if we're forced to always allocate.
2268 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002269 // Allocate the raw data for a fixed array.
2270 int size = FixedArray::SizeFor(length);
2271 return (size > MaxHeapObjectSize())
2272 ? lo_space_->AllocateRawFixedArray(size)
2273 : new_space_.AllocateRaw(size);
2274}
2275
2276
2277Object* Heap::CopyFixedArray(FixedArray* src) {
2278 int len = src->length();
2279 Object* obj = AllocateRawFixedArray(len);
2280 if (obj->IsFailure()) return obj;
2281 if (Heap::InNewSpace(obj)) {
2282 HeapObject* dst = HeapObject::cast(obj);
2283 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2284 reinterpret_cast<Object**>(src->address()),
2285 FixedArray::SizeFor(len));
2286 return obj;
2287 }
2288 HeapObject::cast(obj)->set_map(src->map());
2289 FixedArray* result = FixedArray::cast(obj);
2290 result->set_length(len);
2291 // Copy the content
2292 WriteBarrierMode mode = result->GetWriteBarrierMode();
2293 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2294 return result;
2295}
2296
2297
2298Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002299 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002300 Object* result = AllocateRawFixedArray(length);
2301 if (!result->IsFailure()) {
2302 // Initialize header.
2303 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2304 FixedArray* array = FixedArray::cast(result);
2305 array->set_length(length);
2306 Object* value = undefined_value();
2307 // Initialize body.
2308 for (int index = 0; index < length; index++) {
2309 array->set(index, value, SKIP_WRITE_BARRIER);
2310 }
2311 }
2312 return result;
2313}
2314
2315
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002316Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2317 ASSERT(empty_fixed_array()->IsFixedArray());
2318 if (length == 0) return empty_fixed_array();
2319
2320 int size = FixedArray::SizeFor(length);
2321 Object* result;
2322 if (size > MaxHeapObjectSize()) {
2323 result = lo_space_->AllocateRawFixedArray(size);
2324 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002325 AllocationSpace space =
2326 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002327 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002328 }
2329 if (result->IsFailure()) return result;
2330
2331 // Initialize the object.
2332 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2333 FixedArray* array = FixedArray::cast(result);
2334 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002335 Object* value = undefined_value();
2336 for (int index = 0; index < length; index++) {
2337 array->set(index, value, SKIP_WRITE_BARRIER);
2338 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002339 return array;
2340}
2341
2342
2343Object* Heap::AllocateFixedArrayWithHoles(int length) {
2344 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002345 Object* result = AllocateRawFixedArray(length);
2346 if (!result->IsFailure()) {
2347 // Initialize header.
2348 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2349 FixedArray* array = FixedArray::cast(result);
2350 array->set_length(length);
2351 // Initialize body.
2352 Object* value = the_hole_value();
2353 for (int index = 0; index < length; index++) {
2354 array->set(index, value, SKIP_WRITE_BARRIER);
2355 }
2356 }
2357 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002358}
2359
2360
2361Object* Heap::AllocateHashTable(int length) {
2362 Object* result = Heap::AllocateFixedArray(length);
2363 if (result->IsFailure()) return result;
2364 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2365 ASSERT(result->IsDictionary());
2366 return result;
2367}
2368
2369
2370Object* Heap::AllocateGlobalContext() {
2371 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2372 if (result->IsFailure()) return result;
2373 Context* context = reinterpret_cast<Context*>(result);
2374 context->set_map(global_context_map());
2375 ASSERT(context->IsGlobalContext());
2376 ASSERT(result->IsContext());
2377 return result;
2378}
2379
2380
2381Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2382 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2383 Object* result = Heap::AllocateFixedArray(length);
2384 if (result->IsFailure()) return result;
2385 Context* context = reinterpret_cast<Context*>(result);
2386 context->set_map(context_map());
2387 context->set_closure(function);
2388 context->set_fcontext(context);
2389 context->set_previous(NULL);
2390 context->set_extension(NULL);
2391 context->set_global(function->context()->global());
2392 ASSERT(!context->IsGlobalContext());
2393 ASSERT(context->is_function_context());
2394 ASSERT(result->IsContext());
2395 return result;
2396}
2397
2398
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002399Object* Heap::AllocateWithContext(Context* previous,
2400 JSObject* extension,
2401 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002402 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2403 if (result->IsFailure()) return result;
2404 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002405 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002406 context->set_closure(previous->closure());
2407 context->set_fcontext(previous->fcontext());
2408 context->set_previous(previous);
2409 context->set_extension(extension);
2410 context->set_global(previous->global());
2411 ASSERT(!context->IsGlobalContext());
2412 ASSERT(!context->is_function_context());
2413 ASSERT(result->IsContext());
2414 return result;
2415}
2416
2417
2418Object* Heap::AllocateStruct(InstanceType type) {
2419 Map* map;
2420 switch (type) {
2421#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2422STRUCT_LIST(MAKE_CASE)
2423#undef MAKE_CASE
2424 default:
2425 UNREACHABLE();
2426 return Failure::InternalError();
2427 }
2428 int size = map->instance_size();
2429 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002430 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002431 Object* result = Heap::Allocate(map, space);
2432 if (result->IsFailure()) return result;
2433 Struct::cast(result)->InitializeBody(size);
2434 return result;
2435}
2436
2437
2438#ifdef DEBUG
2439
2440void Heap::Print() {
2441 if (!HasBeenSetup()) return;
2442 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002443 AllSpaces spaces;
2444 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002445}
2446
2447
2448void Heap::ReportCodeStatistics(const char* title) {
2449 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2450 PagedSpace::ResetCodeStatistics();
2451 // We do not look for code in new space, map space, or old space. If code
2452 // somehow ends up in those spaces, we would miss it here.
2453 code_space_->CollectCodeStatistics();
2454 lo_space_->CollectCodeStatistics();
2455 PagedSpace::ReportCodeStatistics();
2456}
2457
2458
2459// This function expects that NewSpace's allocated objects histogram is
2460// populated (via a call to CollectStatistics or else as a side effect of a
2461// just-completed scavenge collection).
2462void Heap::ReportHeapStatistics(const char* title) {
2463 USE(title);
2464 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2465 title, gc_count_);
2466 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002467 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2468 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002469
2470 PrintF("\n");
2471 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2472 GlobalHandles::PrintStats();
2473 PrintF("\n");
2474
2475 PrintF("Heap statistics : ");
2476 MemoryAllocator::ReportStatistics();
2477 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002478 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002479 PrintF("Old pointer space : ");
2480 old_pointer_space_->ReportStatistics();
2481 PrintF("Old data space : ");
2482 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002483 PrintF("Code space : ");
2484 code_space_->ReportStatistics();
2485 PrintF("Map space : ");
2486 map_space_->ReportStatistics();
2487 PrintF("Large object space : ");
2488 lo_space_->ReportStatistics();
2489 PrintF(">>>>>> ========================================= >>>>>>\n");
2490}
2491
2492#endif // DEBUG
2493
2494bool Heap::Contains(HeapObject* value) {
2495 return Contains(value->address());
2496}
2497
2498
2499bool Heap::Contains(Address addr) {
2500 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2501 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002502 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002503 old_pointer_space_->Contains(addr) ||
2504 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002505 code_space_->Contains(addr) ||
2506 map_space_->Contains(addr) ||
2507 lo_space_->SlowContains(addr));
2508}
2509
2510
2511bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2512 return InSpace(value->address(), space);
2513}
2514
2515
2516bool Heap::InSpace(Address addr, AllocationSpace space) {
2517 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2518 if (!HasBeenSetup()) return false;
2519
2520 switch (space) {
2521 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002522 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002523 case OLD_POINTER_SPACE:
2524 return old_pointer_space_->Contains(addr);
2525 case OLD_DATA_SPACE:
2526 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002527 case CODE_SPACE:
2528 return code_space_->Contains(addr);
2529 case MAP_SPACE:
2530 return map_space_->Contains(addr);
2531 case LO_SPACE:
2532 return lo_space_->SlowContains(addr);
2533 }
2534
2535 return false;
2536}
2537
2538
2539#ifdef DEBUG
2540void Heap::Verify() {
2541 ASSERT(HasBeenSetup());
2542
2543 VerifyPointersVisitor visitor;
2544 Heap::IterateRoots(&visitor);
2545
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002546 AllSpaces spaces;
2547 while (Space* space = spaces.next()) {
2548 space->Verify();
2549 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002550}
2551#endif // DEBUG
2552
2553
2554Object* Heap::LookupSymbol(Vector<const char> string) {
2555 Object* symbol = NULL;
2556 Object* new_table =
2557 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2558 if (new_table->IsFailure()) return new_table;
2559 symbol_table_ = new_table;
2560 ASSERT(symbol != NULL);
2561 return symbol;
2562}
2563
2564
2565Object* Heap::LookupSymbol(String* string) {
2566 if (string->IsSymbol()) return string;
2567 Object* symbol = NULL;
2568 Object* new_table =
2569 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2570 if (new_table->IsFailure()) return new_table;
2571 symbol_table_ = new_table;
2572 ASSERT(symbol != NULL);
2573 return symbol;
2574}
2575
2576
ager@chromium.org7c537e22008-10-16 08:43:32 +00002577bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2578 if (string->IsSymbol()) {
2579 *symbol = string;
2580 return true;
2581 }
2582 SymbolTable* table = SymbolTable::cast(symbol_table_);
2583 return table->LookupSymbolIfExists(string, symbol);
2584}
2585
2586
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002587#ifdef DEBUG
2588void Heap::ZapFromSpace() {
2589 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002590 for (Address a = new_space_.FromSpaceLow();
2591 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002592 a += kPointerSize) {
2593 Memory::Address_at(a) = kFromSpaceZapValue;
2594 }
2595}
2596#endif // DEBUG
2597
2598
2599void Heap::IterateRSetRange(Address object_start,
2600 Address object_end,
2601 Address rset_start,
2602 ObjectSlotCallback copy_object_func) {
2603 Address object_address = object_start;
2604 Address rset_address = rset_start;
2605
2606 // Loop over all the pointers in [object_start, object_end).
2607 while (object_address < object_end) {
2608 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002609 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002610 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002611 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002612 // Do not dereference pointers at or past object_end.
2613 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2614 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002615 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002616 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2617 }
2618 // If this pointer does not need to be remembered anymore, clear
2619 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002620 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002621 }
2622 object_address += kPointerSize;
2623 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002624 // Update the remembered set if it has changed.
2625 if (result_rset != rset_word) {
2626 Memory::uint32_at(rset_address) = result_rset;
2627 }
2628 } else {
2629 // No bits in the word were set. This is the common case.
2630 object_address += kPointerSize * kBitsPerInt;
2631 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002632 rset_address += kIntSize;
2633 }
2634}
2635
2636
2637void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2638 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002639 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002640
2641 PageIterator it(space, PageIterator::PAGES_IN_USE);
2642 while (it.has_next()) {
2643 Page* page = it.next();
2644 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2645 page->RSetStart(), copy_object_func);
2646 }
2647}
2648
2649
2650#ifdef DEBUG
2651#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2652#else
2653#define SYNCHRONIZE_TAG(tag)
2654#endif
2655
2656void Heap::IterateRoots(ObjectVisitor* v) {
2657 IterateStrongRoots(v);
2658 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2659 SYNCHRONIZE_TAG("symbol_table");
2660}
2661
2662
2663void Heap::IterateStrongRoots(ObjectVisitor* v) {
2664#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002665 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002666 STRONG_ROOT_LIST(ROOT_ITERATE);
2667#undef ROOT_ITERATE
2668 SYNCHRONIZE_TAG("strong_root_list");
2669
2670#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002671 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002672 STRUCT_LIST(STRUCT_MAP_ITERATE);
2673#undef STRUCT_MAP_ITERATE
2674 SYNCHRONIZE_TAG("struct_map");
2675
2676#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002677 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002678 SYMBOL_LIST(SYMBOL_ITERATE)
2679#undef SYMBOL_ITERATE
2680 SYNCHRONIZE_TAG("symbol");
2681
2682 Bootstrapper::Iterate(v);
2683 SYNCHRONIZE_TAG("bootstrapper");
2684 Top::Iterate(v);
2685 SYNCHRONIZE_TAG("top");
2686 Debug::Iterate(v);
2687 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002688 CompilationCache::Iterate(v);
2689 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002690
2691 // Iterate over local handles in handle scopes.
2692 HandleScopeImplementer::Iterate(v);
2693 SYNCHRONIZE_TAG("handlescope");
2694
2695 // Iterate over the builtin code objects and code stubs in the heap. Note
2696 // that it is not strictly necessary to iterate over code objects on
2697 // scavenge collections. We still do it here because this same function
2698 // is used by the mark-sweep collector and the deserializer.
2699 Builtins::IterateBuiltins(v);
2700 SYNCHRONIZE_TAG("builtins");
2701
2702 // Iterate over global handles.
2703 GlobalHandles::IterateRoots(v);
2704 SYNCHRONIZE_TAG("globalhandles");
2705
2706 // Iterate over pointers being held by inactive threads.
2707 ThreadManager::Iterate(v);
2708 SYNCHRONIZE_TAG("threadmanager");
2709}
2710#undef SYNCHRONIZE_TAG
2711
2712
2713// Flag is set when the heap has been configured. The heap can be repeatedly
2714// configured through the API until it is setup.
2715static bool heap_configured = false;
2716
2717// TODO(1236194): Since the heap size is configurable on the command line
2718// and through the API, we should gracefully handle the case that the heap
2719// size is not big enough to fit all the initial objects.
2720bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2721 if (HasBeenSetup()) return false;
2722
2723 if (semispace_size > 0) semispace_size_ = semispace_size;
2724 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2725
2726 // The new space size must be a power of two to support single-bit testing
2727 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002728 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002729 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2730 young_generation_size_ = 2 * semispace_size_;
2731
2732 // The old generation is paged.
2733 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2734
2735 heap_configured = true;
2736 return true;
2737}
2738
2739
kasper.lund7276f142008-07-30 08:49:36 +00002740bool Heap::ConfigureHeapDefault() {
2741 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2742}
2743
2744
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002745int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002746 return old_pointer_space_->Size()
2747 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002748 + code_space_->Size()
2749 + map_space_->Size()
2750 + lo_space_->Size();
2751}
2752
2753
kasper.lund7276f142008-07-30 08:49:36 +00002754int Heap::PromotedExternalMemorySize() {
2755 if (amount_of_external_allocated_memory_
2756 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2757 return amount_of_external_allocated_memory_
2758 - amount_of_external_allocated_memory_at_last_global_gc_;
2759}
2760
2761
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002762bool Heap::Setup(bool create_heap_objects) {
2763 // Initialize heap spaces and initial maps and objects. Whenever something
2764 // goes wrong, just return false. The caller should check the results and
2765 // call Heap::TearDown() to release allocated memory.
2766 //
2767 // If the heap is not yet configured (eg, through the API), configure it.
2768 // Configuration is based on the flags new-space-size (really the semispace
2769 // size) and old-space-size if set or the initial values of semispace_size_
2770 // and old_generation_size_ otherwise.
2771 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002772 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002773 }
2774
2775 // Setup memory allocator and allocate an initial chunk of memory. The
2776 // initial chunk is double the size of the new space to ensure that we can
2777 // find a pair of semispaces that are contiguous and aligned to their size.
2778 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2779 void* chunk
2780 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2781 if (chunk == NULL) return false;
2782
2783 // Put the initial chunk of the old space at the start of the initial
2784 // chunk, then the two new space semispaces, then the initial chunk of
2785 // code space. Align the pair of semispaces to their size, which must be
2786 // a power of 2.
2787 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002788 Address code_space_start = reinterpret_cast<Address>(chunk);
2789 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2790 Address old_space_start = new_space_start + young_generation_size_;
2791 int code_space_size = new_space_start - code_space_start;
2792 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002793
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002794 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002795 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002796
2797 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002798 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002799 old_pointer_space_ =
2800 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2801 if (old_pointer_space_ == NULL) return false;
2802 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2803 return false;
2804 }
2805 old_data_space_ =
2806 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2807 if (old_data_space_ == NULL) return false;
2808 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2809 old_space_size >> 1)) {
2810 return false;
2811 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002812
2813 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002814 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002815 code_space_ =
2816 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002817 if (code_space_ == NULL) return false;
2818 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2819
2820 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002821 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002822 if (map_space_ == NULL) return false;
2823 // Setting up a paged space without giving it a virtual memory range big
2824 // enough to hold at least a page will cause it to allocate.
2825 if (!map_space_->Setup(NULL, 0)) return false;
2826
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002827 // The large object code space may contain code or data. We set the memory
2828 // to be non-executable here for safety, but this means we need to enable it
2829 // explicitly when allocating large code objects.
2830 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002831 if (lo_space_ == NULL) return false;
2832 if (!lo_space_->Setup()) return false;
2833
2834 if (create_heap_objects) {
2835 // Create initial maps.
2836 if (!CreateInitialMaps()) return false;
2837 if (!CreateApiObjects()) return false;
2838
2839 // Create initial objects
2840 if (!CreateInitialObjects()) return false;
2841 }
2842
2843 LOG(IntEvent("heap-capacity", Capacity()));
2844 LOG(IntEvent("heap-available", Available()));
2845
2846 return true;
2847}
2848
2849
2850void Heap::TearDown() {
2851 GlobalHandles::TearDown();
2852
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002853 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002854
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002855 if (old_pointer_space_ != NULL) {
2856 old_pointer_space_->TearDown();
2857 delete old_pointer_space_;
2858 old_pointer_space_ = NULL;
2859 }
2860
2861 if (old_data_space_ != NULL) {
2862 old_data_space_->TearDown();
2863 delete old_data_space_;
2864 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002865 }
2866
2867 if (code_space_ != NULL) {
2868 code_space_->TearDown();
2869 delete code_space_;
2870 code_space_ = NULL;
2871 }
2872
2873 if (map_space_ != NULL) {
2874 map_space_->TearDown();
2875 delete map_space_;
2876 map_space_ = NULL;
2877 }
2878
2879 if (lo_space_ != NULL) {
2880 lo_space_->TearDown();
2881 delete lo_space_;
2882 lo_space_ = NULL;
2883 }
2884
2885 MemoryAllocator::TearDown();
2886}
2887
2888
2889void Heap::Shrink() {
2890 // Try to shrink map, old, and code spaces.
2891 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002892 old_pointer_space_->Shrink();
2893 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002894 code_space_->Shrink();
2895}
2896
2897
2898#ifdef DEBUG
2899
2900class PrintHandleVisitor: public ObjectVisitor {
2901 public:
2902 void VisitPointers(Object** start, Object** end) {
2903 for (Object** p = start; p < end; p++)
2904 PrintF(" handle %p to %p\n", p, *p);
2905 }
2906};
2907
2908void Heap::PrintHandles() {
2909 PrintF("Handles:\n");
2910 PrintHandleVisitor v;
2911 HandleScopeImplementer::Iterate(&v);
2912}
2913
2914#endif
2915
2916
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002917Space* AllSpaces::next() {
2918 switch (counter_++) {
2919 case NEW_SPACE:
2920 return Heap::new_space();
2921 case OLD_POINTER_SPACE:
2922 return Heap::old_pointer_space();
2923 case OLD_DATA_SPACE:
2924 return Heap::old_data_space();
2925 case CODE_SPACE:
2926 return Heap::code_space();
2927 case MAP_SPACE:
2928 return Heap::map_space();
2929 case LO_SPACE:
2930 return Heap::lo_space();
2931 default:
2932 return NULL;
2933 }
2934}
2935
2936
2937PagedSpace* PagedSpaces::next() {
2938 switch (counter_++) {
2939 case OLD_POINTER_SPACE:
2940 return Heap::old_pointer_space();
2941 case OLD_DATA_SPACE:
2942 return Heap::old_data_space();
2943 case CODE_SPACE:
2944 return Heap::code_space();
2945 case MAP_SPACE:
2946 return Heap::map_space();
2947 default:
2948 return NULL;
2949 }
2950}
2951
2952
2953
2954OldSpace* OldSpaces::next() {
2955 switch (counter_++) {
2956 case OLD_POINTER_SPACE:
2957 return Heap::old_pointer_space();
2958 case OLD_DATA_SPACE:
2959 return Heap::old_data_space();
2960 case CODE_SPACE:
2961 return Heap::code_space();
2962 default:
2963 return NULL;
2964 }
2965}
2966
2967
kasper.lund7276f142008-07-30 08:49:36 +00002968SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2969}
2970
2971
2972SpaceIterator::~SpaceIterator() {
2973 // Delete active iterator if any.
2974 delete iterator_;
2975}
2976
2977
2978bool SpaceIterator::has_next() {
2979 // Iterate until no more spaces.
2980 return current_space_ != LAST_SPACE;
2981}
2982
2983
2984ObjectIterator* SpaceIterator::next() {
2985 if (iterator_ != NULL) {
2986 delete iterator_;
2987 iterator_ = NULL;
2988 // Move to the next space
2989 current_space_++;
2990 if (current_space_ > LAST_SPACE) {
2991 return NULL;
2992 }
2993 }
2994
2995 // Return iterator for the new current space.
2996 return CreateIterator();
2997}
2998
2999
3000// Create an iterator for the space to iterate.
3001ObjectIterator* SpaceIterator::CreateIterator() {
3002 ASSERT(iterator_ == NULL);
3003
3004 switch (current_space_) {
3005 case NEW_SPACE:
3006 iterator_ = new SemiSpaceIterator(Heap::new_space());
3007 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003008 case OLD_POINTER_SPACE:
3009 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3010 break;
3011 case OLD_DATA_SPACE:
3012 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003013 break;
3014 case CODE_SPACE:
3015 iterator_ = new HeapObjectIterator(Heap::code_space());
3016 break;
3017 case MAP_SPACE:
3018 iterator_ = new HeapObjectIterator(Heap::map_space());
3019 break;
3020 case LO_SPACE:
3021 iterator_ = new LargeObjectIterator(Heap::lo_space());
3022 break;
3023 }
3024
3025 // Return the newly allocated iterator;
3026 ASSERT(iterator_ != NULL);
3027 return iterator_;
3028}
3029
3030
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003031HeapIterator::HeapIterator() {
3032 Init();
3033}
3034
3035
3036HeapIterator::~HeapIterator() {
3037 Shutdown();
3038}
3039
3040
3041void HeapIterator::Init() {
3042 // Start the iteration.
3043 space_iterator_ = new SpaceIterator();
3044 object_iterator_ = space_iterator_->next();
3045}
3046
3047
3048void HeapIterator::Shutdown() {
3049 // Make sure the last iterator is deallocated.
3050 delete space_iterator_;
3051 space_iterator_ = NULL;
3052 object_iterator_ = NULL;
3053}
3054
3055
3056bool HeapIterator::has_next() {
3057 // No iterator means we are done.
3058 if (object_iterator_ == NULL) return false;
3059
3060 if (object_iterator_->has_next_object()) {
3061 // If the current iterator has more objects we are fine.
3062 return true;
3063 } else {
3064 // Go though the spaces looking for one that has objects.
3065 while (space_iterator_->has_next()) {
3066 object_iterator_ = space_iterator_->next();
3067 if (object_iterator_->has_next_object()) {
3068 return true;
3069 }
3070 }
3071 }
3072 // Done with the last space.
3073 object_iterator_ = NULL;
3074 return false;
3075}
3076
3077
3078HeapObject* HeapIterator::next() {
3079 if (has_next()) {
3080 return object_iterator_->next_object();
3081 } else {
3082 return NULL;
3083 }
3084}
3085
3086
3087void HeapIterator::reset() {
3088 // Restart the iterator.
3089 Shutdown();
3090 Init();
3091}
3092
3093
3094//
3095// HeapProfiler class implementation.
3096//
3097#ifdef ENABLE_LOGGING_AND_PROFILING
3098void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3099 InstanceType type = obj->map()->instance_type();
3100 ASSERT(0 <= type && type <= LAST_TYPE);
3101 info[type].increment_number(1);
3102 info[type].increment_bytes(obj->Size());
3103}
3104#endif
3105
3106
3107#ifdef ENABLE_LOGGING_AND_PROFILING
3108void HeapProfiler::WriteSample() {
3109 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3110
3111 HistogramInfo info[LAST_TYPE+1];
3112#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3113 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3114#undef DEF_TYPE_NAME
3115
3116 HeapIterator iterator;
3117 while (iterator.has_next()) {
3118 CollectStats(iterator.next(), info);
3119 }
3120
3121 // Lump all the string types together.
3122 int string_number = 0;
3123 int string_bytes = 0;
3124#define INCREMENT_SIZE(type, size, name) \
3125 string_number += info[type].number(); \
3126 string_bytes += info[type].bytes();
3127 STRING_TYPE_LIST(INCREMENT_SIZE)
3128#undef INCREMENT_SIZE
3129 if (string_bytes > 0) {
3130 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3131 }
3132
3133 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3134 if (info[i].bytes() > 0) {
3135 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3136 info[i].bytes()));
3137 }
3138 }
3139
3140 LOG(HeapSampleEndEvent("Heap", "allocated"));
3141}
3142
3143
3144#endif
3145
3146
3147
3148#ifdef DEBUG
3149
3150static bool search_for_any_global;
3151static Object* search_target;
3152static bool found_target;
3153static List<Object*> object_stack(20);
3154
3155
3156// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3157static const int kMarkTag = 2;
3158
3159static void MarkObjectRecursively(Object** p);
3160class MarkObjectVisitor : public ObjectVisitor {
3161 public:
3162 void VisitPointers(Object** start, Object** end) {
3163 // Copy all HeapObject pointers in [start, end)
3164 for (Object** p = start; p < end; p++) {
3165 if ((*p)->IsHeapObject())
3166 MarkObjectRecursively(p);
3167 }
3168 }
3169};
3170
3171static MarkObjectVisitor mark_visitor;
3172
3173static void MarkObjectRecursively(Object** p) {
3174 if (!(*p)->IsHeapObject()) return;
3175
3176 HeapObject* obj = HeapObject::cast(*p);
3177
3178 Object* map = obj->map();
3179
3180 if (!map->IsHeapObject()) return; // visited before
3181
3182 if (found_target) return; // stop if target found
3183 object_stack.Add(obj);
3184 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3185 (!search_for_any_global && (obj == search_target))) {
3186 found_target = true;
3187 return;
3188 }
3189
3190 if (obj->IsCode()) {
3191 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3192 }
3193
3194 // not visited yet
3195 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3196
3197 Address map_addr = map_p->address();
3198
3199 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3200
3201 MarkObjectRecursively(&map);
3202
3203 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3204 &mark_visitor);
3205
3206 if (!found_target) // don't pop if found the target
3207 object_stack.RemoveLast();
3208}
3209
3210
3211static void UnmarkObjectRecursively(Object** p);
3212class UnmarkObjectVisitor : public ObjectVisitor {
3213 public:
3214 void VisitPointers(Object** start, Object** end) {
3215 // Copy all HeapObject pointers in [start, end)
3216 for (Object** p = start; p < end; p++) {
3217 if ((*p)->IsHeapObject())
3218 UnmarkObjectRecursively(p);
3219 }
3220 }
3221};
3222
3223static UnmarkObjectVisitor unmark_visitor;
3224
3225static void UnmarkObjectRecursively(Object** p) {
3226 if (!(*p)->IsHeapObject()) return;
3227
3228 HeapObject* obj = HeapObject::cast(*p);
3229
3230 Object* map = obj->map();
3231
3232 if (map->IsHeapObject()) return; // unmarked already
3233
3234 Address map_addr = reinterpret_cast<Address>(map);
3235
3236 map_addr -= kMarkTag;
3237
3238 ASSERT_TAG_ALIGNED(map_addr);
3239
3240 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3241
3242 obj->set_map(reinterpret_cast<Map*>(map_p));
3243
3244 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3245
3246 obj->IterateBody(Map::cast(map_p)->instance_type(),
3247 obj->SizeFromMap(Map::cast(map_p)),
3248 &unmark_visitor);
3249
3250 if (obj->IsCode()) {
3251 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3252 }
3253}
3254
3255
3256static void MarkRootObjectRecursively(Object** root) {
3257 if (search_for_any_global) {
3258 ASSERT(search_target == NULL);
3259 } else {
3260 ASSERT(search_target->IsHeapObject());
3261 }
3262 found_target = false;
3263 object_stack.Clear();
3264
3265 MarkObjectRecursively(root);
3266 UnmarkObjectRecursively(root);
3267
3268 if (found_target) {
3269 PrintF("=====================================\n");
3270 PrintF("==== Path to object ====\n");
3271 PrintF("=====================================\n\n");
3272
3273 ASSERT(!object_stack.is_empty());
3274 for (int i = 0; i < object_stack.length(); i++) {
3275 if (i > 0) PrintF("\n |\n |\n V\n\n");
3276 Object* obj = object_stack[i];
3277 obj->Print();
3278 }
3279 PrintF("=====================================\n");
3280 }
3281}
3282
3283
3284// Helper class for visiting HeapObjects recursively.
3285class MarkRootVisitor: public ObjectVisitor {
3286 public:
3287 void VisitPointers(Object** start, Object** end) {
3288 // Visit all HeapObject pointers in [start, end)
3289 for (Object** p = start; p < end; p++) {
3290 if ((*p)->IsHeapObject())
3291 MarkRootObjectRecursively(p);
3292 }
3293 }
3294};
3295
3296
3297// Triggers a depth-first traversal of reachable objects from roots
3298// and finds a path to a specific heap object and prints it.
3299void Heap::TracePathToObject() {
3300 search_target = NULL;
3301 search_for_any_global = false;
3302
3303 MarkRootVisitor root_visitor;
3304 IterateRoots(&root_visitor);
3305}
3306
3307
3308// Triggers a depth-first traversal of reachable objects from roots
3309// and finds a path to any global object and prints it. Useful for
3310// determining the source for leaks of global objects.
3311void Heap::TracePathToGlobal() {
3312 search_target = NULL;
3313 search_for_any_global = true;
3314
3315 MarkRootVisitor root_visitor;
3316 IterateRoots(&root_visitor);
3317}
3318#endif
3319
3320
kasper.lund7276f142008-07-30 08:49:36 +00003321GCTracer::GCTracer()
3322 : start_time_(0.0),
3323 start_size_(0.0),
3324 gc_count_(0),
3325 full_gc_count_(0),
3326 is_compacting_(false),
3327 marked_count_(0) {
3328 // These two fields reflect the state of the previous full collection.
3329 // Set them before they are changed by the collector.
3330 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3331 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3332 if (!FLAG_trace_gc) return;
3333 start_time_ = OS::TimeCurrentMillis();
3334 start_size_ = SizeOfHeapObjects();
3335}
3336
3337
3338GCTracer::~GCTracer() {
3339 if (!FLAG_trace_gc) return;
3340 // Printf ONE line iff flag is set.
3341 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3342 CollectorString(),
3343 start_size_, SizeOfHeapObjects(),
3344 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3345}
3346
3347
3348const char* GCTracer::CollectorString() {
3349 switch (collector_) {
3350 case SCAVENGER:
3351 return "Scavenge";
3352 case MARK_COMPACTOR:
3353 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3354 : "Mark-sweep";
3355 }
3356 return "Unknown GC";
3357}
3358
3359
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003360#ifdef DEBUG
3361bool Heap::GarbageCollectionGreedyCheck() {
3362 ASSERT(FLAG_gc_greedy);
3363 if (Bootstrapper::IsActive()) return true;
3364 if (disallow_allocation_failure()) return true;
3365 return CollectGarbage(0, NEW_SPACE);
3366}
3367#endif
3368
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003369} } // namespace v8::internal