blob: 1658c6bf07f6d319b91351a09fb4cbdb639275a0 [file] [log] [blame]
ager@chromium.org71daaf62009-04-01 07:22:49 +00001// Copyright 2009 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"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "mark-compact.h"
38#include "natives.h"
39#include "scanner.h"
40#include "scopeinfo.h"
41#include "v8threads.h"
42
kasperl@chromium.org71affb52009-05-26 05:44:31 +000043namespace v8 {
44namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046
ager@chromium.org3b45ab52009-03-19 22:21:34 +000047String* Heap::hidden_symbol_;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000048Object* Heap::roots_[Heap::kRootListLength];
49
ager@chromium.org3b45ab52009-03-19 22:21:34 +000050
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000051NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000052OldSpace* Heap::old_pointer_space_ = NULL;
53OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000054OldSpace* Heap::code_space_ = NULL;
55MapSpace* Heap::map_space_ = NULL;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +000056CellSpace* Heap::cell_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057LargeObjectSpace* Heap::lo_space_ = NULL;
58
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000059static const int kMinimumPromotionLimit = 2*MB;
60static const int kMinimumAllocationLimit = 8*MB;
61
62int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
63int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
64
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065int Heap::old_gen_exhausted_ = false;
66
kasper.lund7276f142008-07-30 08:49:36 +000067int Heap::amount_of_external_allocated_memory_ = 0;
68int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
69
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000070// semispace_size_ should be a power of 2 and old_generation_size_ should be
71// a multiple of Page::kPageSize.
kasperl@chromium.orge959c182009-07-27 08:59:04 +000072#if defined(ANDROID)
ager@chromium.orgeadaf222009-06-16 09:43:10 +000073int Heap::semispace_size_ = 512*KB;
74int Heap::old_generation_size_ = 128*MB;
75int Heap::initial_semispace_size_ = 128*KB;
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +000076#elif defined(V8_TARGET_ARCH_X64)
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000077int Heap::semispace_size_ = 8*MB;
78int Heap::old_generation_size_ = 1*GB;
79int Heap::initial_semispace_size_ = 1*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000080#else
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +000081int Heap::semispace_size_ = 4*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082int Heap::old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000083int Heap::initial_semispace_size_ = 512*KB;
84#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000085
86GCCallback Heap::global_gc_prologue_callback_ = NULL;
87GCCallback Heap::global_gc_epilogue_callback_ = NULL;
88
89// Variables set based on semispace_size_ and old_generation_size_ in
90// ConfigureHeap.
91int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
ager@chromium.orgeadaf222009-06-16 09:43:10 +000092int Heap::survived_since_last_expansion_ = 0;
kasperl@chromium.orge959c182009-07-27 08:59:04 +000093int Heap::external_allocation_limit_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000094
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000095Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097int Heap::mc_count_ = 0;
98int Heap::gc_count_ = 0;
99
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000100int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000101bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000102
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() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000118 map_space_->Capacity() +
119 cell_space_->Capacity();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000120}
121
122
123int Heap::Available() {
124 if (!HasBeenSetup()) return 0;
125
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000126 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000127 old_pointer_space_->Available() +
128 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129 code_space_->Available() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000130 map_space_->Available() +
131 cell_space_->Available();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000132}
133
134
135bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000136 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000137 old_data_space_ != NULL &&
138 code_space_ != NULL &&
139 map_space_ != NULL &&
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000140 cell_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000141 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142}
143
144
145GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
146 // Is global GC requested?
147 if (space != NEW_SPACE || FLAG_gc_global) {
148 Counters::gc_compactor_caused_by_request.Increment();
149 return MARK_COMPACTOR;
150 }
151
152 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000153 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000154 Counters::gc_compactor_caused_by_promoted_data.Increment();
155 return MARK_COMPACTOR;
156 }
157
158 // Have allocation in OLD and LO failed?
159 if (old_gen_exhausted_) {
160 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
161 return MARK_COMPACTOR;
162 }
163
164 // Is there enough space left in OLD to guarantee that a scavenge can
165 // succeed?
166 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000167 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000168 // for object promotion. It counts only the bytes that the memory
169 // allocator has not yet allocated from the OS and assigned to any space,
170 // and does not count available bytes already in the old space or code
171 // space. Undercounting is safe---we may get an unrequested full GC when
172 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000173 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000174 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
175 return MARK_COMPACTOR;
176 }
177
178 // Default
179 return SCAVENGER;
180}
181
182
183// TODO(1238405): Combine the infrastructure for --heap-stats and
184// --log-gc to avoid the complicated preprocessor and flag testing.
185#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
186void Heap::ReportStatisticsBeforeGC() {
187 // Heap::ReportHeapStatistics will also log NewSpace statistics when
188 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
189 // following logic is used to avoid double logging.
190#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000191 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000192 if (FLAG_heap_stats) {
193 ReportHeapStatistics("Before GC");
194 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000195 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000196 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000197 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198#elif defined(DEBUG)
199 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000200 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000201 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000202 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000203 }
204#elif defined(ENABLE_LOGGING_AND_PROFILING)
205 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000206 new_space_.CollectStatistics();
207 new_space_.ReportStatistics();
208 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000209 }
210#endif
211}
212
213
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000214#if defined(ENABLE_LOGGING_AND_PROFILING)
215void Heap::PrintShortHeapStatistics() {
216 if (!FLAG_trace_gc_verbose) return;
217 PrintF("Memory allocator, used: %8d, available: %8d\n",
218 MemoryAllocator::Size(), MemoryAllocator::Available());
219 PrintF("New space, used: %8d, available: %8d\n",
220 Heap::new_space_.Size(), new_space_.Available());
221 PrintF("Old pointers, used: %8d, available: %8d\n",
222 old_pointer_space_->Size(), old_pointer_space_->Available());
223 PrintF("Old data space, used: %8d, available: %8d\n",
224 old_data_space_->Size(), old_data_space_->Available());
225 PrintF("Code space, used: %8d, available: %8d\n",
226 code_space_->Size(), code_space_->Available());
227 PrintF("Map space, used: %8d, available: %8d\n",
228 map_space_->Size(), map_space_->Available());
229 PrintF("Large object space, used: %8d, avaialble: %8d\n",
230 lo_space_->Size(), lo_space_->Available());
231}
232#endif
233
234
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000235// TODO(1238405): Combine the infrastructure for --heap-stats and
236// --log-gc to avoid the complicated preprocessor and flag testing.
237void Heap::ReportStatisticsAfterGC() {
238 // Similar to the before GC, we use some complicated logic to ensure that
239 // NewSpace statistics are logged exactly once when --log-gc is turned on.
240#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
241 if (FLAG_heap_stats) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000242 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000243 ReportHeapStatistics("After GC");
244 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000245 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 }
247#elif defined(DEBUG)
248 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
249#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000250 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000251#endif
252}
253#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
254
255
256void Heap::GarbageCollectionPrologue() {
kasper.lund7276f142008-07-30 08:49:36 +0000257 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000258#ifdef DEBUG
259 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
260 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261
262 if (FLAG_verify_heap) {
263 Verify();
264 }
265
266 if (FLAG_gc_verbose) Print();
267
268 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000269 // Not all spaces have remembered set bits that we care about.
270 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000271 map_space_->PrintRSet();
272 lo_space_->PrintRSet();
273 }
274#endif
275
276#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
277 ReportStatisticsBeforeGC();
278#endif
279}
280
281int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000282 int total = 0;
283 AllSpaces spaces;
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000284 while (Space* space = spaces.next()) {
285 total += space->Size();
286 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000287 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000288}
289
290void Heap::GarbageCollectionEpilogue() {
291#ifdef DEBUG
292 allow_allocation(true);
293 ZapFromSpace();
294
295 if (FLAG_verify_heap) {
296 Verify();
297 }
298
299 if (FLAG_print_global_handles) GlobalHandles::Print();
300 if (FLAG_print_handles) PrintHandles();
301 if (FLAG_gc_verbose) Print();
302 if (FLAG_code_stats) ReportCodeStatistics("After GC");
303#endif
304
305 Counters::alive_after_last_gc.Set(SizeOfObjects());
306
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000307 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
308 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
310 ReportStatisticsAfterGC();
311#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000312#ifdef ENABLE_DEBUGGER_SUPPORT
313 Debug::AfterGarbageCollection();
314#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000315}
316
317
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000318void Heap::CollectAllGarbage(bool force_compaction) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000319 // Since we are ignoring the return value, the exact choice of space does
320 // not matter, so long as we do not specify NEW_SPACE, which would not
321 // cause a full GC.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000322 MarkCompactCollector::SetForceCompaction(force_compaction);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000323 CollectGarbage(0, OLD_POINTER_SPACE);
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000324 MarkCompactCollector::SetForceCompaction(false);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000325}
326
327
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000328void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000329 // If the garbage collector interface is exposed through the global
330 // gc() function, we avoid being clever about forcing GCs when
331 // contexts are disposed and leave it to the embedder to make
332 // informed decisions about when to force a collection.
333 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000334 HistogramTimerScope scope(&Counters::gc_context);
ager@chromium.orgab99eea2009-08-25 07:05:41 +0000335 CollectAllGarbage(false);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000336 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000337 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000338}
339
340
341void Heap::NotifyContextDisposed() {
342 context_disposed_pending_ = true;
343}
344
345
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000346bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
347 // The VM is in the GC state until exiting this function.
348 VMState state(GC);
349
350#ifdef DEBUG
351 // Reset the allocation timeout to the GC interval, but make sure to
352 // allow at least a few allocations after a collection. The reason
353 // for this is that we have a lot of allocation sequences and we
354 // assume that a garbage collection will allow the subsequent
355 // allocation attempts to go through.
356 allocation_timeout_ = Max(6, FLAG_gc_interval);
357#endif
358
359 { GCTracer tracer;
360 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000361 // The GC count was incremented in the prologue. Tell the tracer about
362 // it.
363 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000364
365 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000366 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000367 tracer.set_collector(collector);
368
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000369 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000370 ? &Counters::gc_scavenger
371 : &Counters::gc_compactor;
372 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000373 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000374 rate->Stop();
375
376 GarbageCollectionEpilogue();
377 }
378
379
380#ifdef ENABLE_LOGGING_AND_PROFILING
381 if (FLAG_log_gc) HeapProfiler::WriteSample();
382#endif
383
384 switch (space) {
385 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000386 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000387 case OLD_POINTER_SPACE:
388 return old_pointer_space_->Available() >= requested_size;
389 case OLD_DATA_SPACE:
390 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000391 case CODE_SPACE:
392 return code_space_->Available() >= requested_size;
393 case MAP_SPACE:
394 return map_space_->Available() >= requested_size;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000395 case CELL_SPACE:
396 return cell_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000397 case LO_SPACE:
398 return lo_space_->Available() >= requested_size;
399 }
400 return false;
401}
402
403
kasper.lund7276f142008-07-30 08:49:36 +0000404void Heap::PerformScavenge() {
405 GCTracer tracer;
406 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
407}
408
409
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000410#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000411// Helper class for verifying the symbol table.
412class SymbolTableVerifier : public ObjectVisitor {
413 public:
414 SymbolTableVerifier() { }
415 void VisitPointers(Object** start, Object** end) {
416 // Visit all HeapObject pointers in [start, end).
417 for (Object** p = start; p < end; p++) {
418 if ((*p)->IsHeapObject()) {
419 // Check that the symbol is actually a symbol.
420 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000421 }
422 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000423 }
424};
425#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000426
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000427
428static void VerifySymbolTable() {
429#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000430 SymbolTableVerifier verifier;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000431 Heap::symbol_table()->IterateElements(&verifier);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000432#endif // DEBUG
433}
434
435
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000436void Heap::EnsureFromSpaceIsCommitted() {
437 if (new_space_.CommitFromSpaceIfNeeded()) return;
438
439 // Committing memory to from space failed.
440 // Try shrinking and try again.
441 Shrink();
442 if (new_space_.CommitFromSpaceIfNeeded()) return;
443
444 // Committing memory to from space failed again.
445 // Memory is exhausted and we will die.
446 V8::FatalProcessOutOfMemory("Committing semi space failed.");
447}
448
449
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000451 GarbageCollector collector,
452 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000453 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000454 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
455 ASSERT(!allocation_allowed_);
456 global_gc_prologue_callback_();
457 }
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000458 EnsureFromSpaceIsCommitted();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000459 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000460 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000462 int old_gen_size = PromotedSpaceSize();
463 old_gen_promotion_limit_ =
464 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
465 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000466 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000467 old_gen_exhausted_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468 }
ager@chromium.org439e85a2009-08-26 13:15:29 +0000469 Scavenge();
470
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000471 Counters::objs_since_last_young.Set(0);
472
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000473 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474
kasper.lund7276f142008-07-30 08:49:36 +0000475 if (collector == MARK_COMPACTOR) {
476 // Register the amount of external allocated memory.
477 amount_of_external_allocated_memory_at_last_global_gc_ =
478 amount_of_external_allocated_memory_;
479 }
480
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000481 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
482 ASSERT(!allocation_allowed_);
483 global_gc_epilogue_callback_();
484 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000485 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000486}
487
488
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000489void Heap::PostGarbageCollectionProcessing() {
490 // Process weak handles post gc.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000491 {
492 DisableAssertNoAllocation allow_allocation;
493 GlobalHandles::PostGarbageCollectionProcessing();
494 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000495 // Update flat string readers.
496 FlatStringReader::PostGarbageCollectionProcessing();
497}
498
499
kasper.lund7276f142008-07-30 08:49:36 +0000500void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000501 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000502 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000503 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000504 LOG(ResourceEvent("markcompact", "begin"));
505
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000506 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000508 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000509
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000510 MarkCompactPrologue(is_compacting);
511
512 MarkCompactCollector::CollectGarbage();
513
514 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515
516 LOG(ResourceEvent("markcompact", "end"));
517
518 gc_state_ = NOT_IN_GC;
519
520 Shrink();
521
522 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000523 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524}
525
526
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000527void Heap::MarkCompactPrologue(bool is_compacting) {
528 // At any old GC clear the keyed lookup cache to enable collection of unused
529 // maps.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000530 KeyedLookupCache::Clear();
531 ContextSlotCache::Clear();
532 DescriptorLookupCache::Clear();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000533
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000534 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000535
536 Top::MarkCompactPrologue(is_compacting);
537 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000538}
539
540
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000541void Heap::MarkCompactEpilogue(bool is_compacting) {
542 Top::MarkCompactEpilogue(is_compacting);
543 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544}
545
546
547Object* Heap::FindCodeObject(Address a) {
548 Object* obj = code_space_->FindObject(a);
549 if (obj->IsFailure()) {
550 obj = lo_space_->FindObject(a);
551 }
kasper.lund7276f142008-07-30 08:49:36 +0000552 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000553 return obj;
554}
555
556
557// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000558class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000559 public:
560
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000561 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562
563 void VisitPointers(Object** start, Object** end) {
564 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000565 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566 }
567
568 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000569 void ScavengePointer(Object** p) {
570 Object* object = *p;
571 if (!Heap::InNewSpace(object)) return;
572 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
573 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000574 }
575};
576
577
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000578// A queue of pointers and maps of to-be-promoted objects during a
579// scavenge collection.
580class PromotionQueue {
581 public:
582 void Initialize(Address start_address) {
583 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
584 }
585
586 bool is_empty() { return front_ <= rear_; }
587
588 void insert(HeapObject* object, Map* map) {
589 *(--rear_) = object;
590 *(--rear_) = map;
591 // Assert no overflow into live objects.
592 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
593 }
594
595 void remove(HeapObject** object, Map** map) {
596 *object = *(--front_);
597 *map = Map::cast(*(--front_));
598 // Assert no underflow.
599 ASSERT(front_ >= rear_);
600 }
601
602 private:
603 // The front of the queue is higher in memory than the rear.
604 HeapObject** front_;
605 HeapObject** rear_;
606};
607
608
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000609// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000610static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611
612
613#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000614// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000615// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000616class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000617 public:
618 void VisitPointers(Object** start, Object**end) {
619 for (Object** current = start; current < end; current++) {
620 if ((*current)->IsHeapObject()) {
621 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
622 }
623 }
624 }
625};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000626
627
628static void VerifyNonPointerSpacePointers() {
629 // Verify that there are no pointers to new space in spaces where we
630 // do not expect them.
631 VerifyNonPointerSpacePointersVisitor v;
632 HeapObjectIterator code_it(Heap::code_space());
633 while (code_it.has_next()) {
634 HeapObject* object = code_it.next();
635 if (object->IsCode()) {
636 Code::cast(object)->ConvertICTargetsFromAddressToObject();
637 object->Iterate(&v);
638 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
639 } else {
640 // If we find non-code objects in code space (e.g., free list
641 // nodes) we want to verify them as well.
642 object->Iterate(&v);
643 }
644 }
645
646 HeapObjectIterator data_it(Heap::old_data_space());
647 while (data_it.has_next()) data_it.next()->Iterate(&v);
648}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000649#endif
650
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000651
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652void Heap::Scavenge() {
653#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000654 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000655#endif
656
657 gc_state_ = SCAVENGE;
658
659 // Implements Cheney's copying algorithm
660 LOG(ResourceEvent("scavenge", "begin"));
661
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000662 // Clear descriptor cache.
663 DescriptorLookupCache::Clear();
664
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000665 // Used for updating survived_since_last_expansion_ at function end.
666 int survived_watermark = PromotedSpaceSize();
667
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000668 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000669 survived_since_last_expansion_ > new_space_.Capacity()) {
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000670 // Grow the size of new space if there is room to grow and enough
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000671 // data has survived scavenge since the last expansion.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000672 new_space_.Grow();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000673 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000674 }
675
676 // Flip the semispaces. After flipping, to space is empty, from space has
677 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000678 new_space_.Flip();
679 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000681 // We need to sweep newly copied objects which can be either in the
682 // to space or promoted to the old generation. For to-space
683 // objects, we treat the bottom of the to space as a queue. Newly
684 // copied and unswept objects lie between a 'front' mark and the
685 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000686 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000687 // Promoted objects can go into various old-generation spaces, and
688 // can be allocated internally in the spaces (from the free list).
689 // We treat the top of the to space as a queue of addresses of
690 // promoted objects. The addresses of newly promoted and unswept
691 // objects lie between a 'front' mark and a 'rear' mark that is
692 // updated as a side effect of promoting an object.
693 //
694 // There is guaranteed to be enough room at the top of the to space
695 // for the addresses of promoted objects: every object promoted
696 // frees up its size in bytes from the top of the new space, and
697 // objects are at least one pointer in size.
698 Address new_space_front = new_space_.ToSpaceLow();
699 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000700
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000701 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000703 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000705 // Copy objects reachable from weak pointers.
706 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
707
708 // Copy objects reachable from the old generation. By definition,
709 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000710 IterateRSet(old_pointer_space_, &ScavengePointer);
711 IterateRSet(map_space_, &ScavengePointer);
712 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000713
714 // Copy objects reachable from cells by scavenging cell values directly.
715 HeapObjectIterator cell_iterator(cell_space_);
716 while (cell_iterator.has_next()) {
717 HeapObject* cell = cell_iterator.next();
718 if (cell->IsJSGlobalPropertyCell()) {
719 Address value_address =
720 reinterpret_cast<Address>(cell) +
721 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
722 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
723 }
724 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000725
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000726 do {
727 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000728
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000729 // The addresses new_space_front and new_space_.top() define a
730 // queue of unprocessed copied objects. Process them until the
731 // queue is empty.
732 while (new_space_front < new_space_.top()) {
733 HeapObject* object = HeapObject::FromAddress(new_space_front);
734 object->Iterate(&scavenge_visitor);
735 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000736 }
737
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000738 // Promote and process all the to-be-promoted objects.
739 while (!promotion_queue.is_empty()) {
740 HeapObject* source;
741 Map* map;
742 promotion_queue.remove(&source, &map);
743 // Copy the from-space object to its new location (given by the
744 // forwarding address) and fix its map.
745 HeapObject* target = source->map_word().ToForwardingAddress();
746 CopyBlock(reinterpret_cast<Object**>(target->address()),
747 reinterpret_cast<Object**>(source->address()),
748 source->SizeFromMap(map));
749 target->set_map(map);
750
751#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
752 // Update NewSpace stats if necessary.
753 RecordCopiedObject(target);
754#endif
755 // Visit the newly copied object for pointers to new space.
756 target->Iterate(&scavenge_visitor);
757 UpdateRSet(target);
758 }
759
760 // Take another spin if there are now unswept objects in new space
761 // (there are currently no more unswept promoted objects).
762 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000763
764 // Set age mark.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000765 new_space_.set_age_mark(new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000767 // Update how much has survived scavenge.
768 survived_since_last_expansion_ +=
769 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
770
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000771 LOG(ResourceEvent("scavenge", "end"));
772
773 gc_state_ = NOT_IN_GC;
774}
775
776
777void Heap::ClearRSetRange(Address start, int size_in_bytes) {
778 uint32_t start_bit;
779 Address start_word_address =
780 Page::ComputeRSetBitPosition(start, 0, &start_bit);
781 uint32_t end_bit;
782 Address end_word_address =
783 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
784 0,
785 &end_bit);
786
787 // We want to clear the bits in the starting word starting with the
788 // first bit, and in the ending word up to and including the last
789 // bit. Build a pair of bitmasks to do that.
790 uint32_t start_bitmask = start_bit - 1;
791 uint32_t end_bitmask = ~((end_bit << 1) - 1);
792
793 // If the start address and end address are the same, we mask that
794 // word once, otherwise mask the starting and ending word
795 // separately and all the ones in between.
796 if (start_word_address == end_word_address) {
797 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
798 } else {
799 Memory::uint32_at(start_word_address) &= start_bitmask;
800 Memory::uint32_at(end_word_address) &= end_bitmask;
801 start_word_address += kIntSize;
802 memset(start_word_address, 0, end_word_address - start_word_address);
803 }
804}
805
806
807class UpdateRSetVisitor: public ObjectVisitor {
808 public:
809
810 void VisitPointer(Object** p) {
811 UpdateRSet(p);
812 }
813
814 void VisitPointers(Object** start, Object** end) {
815 // Update a store into slots [start, end), used (a) to update remembered
816 // set when promoting a young object to old space or (b) to rebuild
817 // remembered sets after a mark-compact collection.
818 for (Object** p = start; p < end; p++) UpdateRSet(p);
819 }
820 private:
821
822 void UpdateRSet(Object** p) {
823 // The remembered set should not be set. It should be clear for objects
824 // newly copied to old space, and it is cleared before rebuilding in the
825 // mark-compact collector.
826 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
827 if (Heap::InNewSpace(*p)) {
828 Page::SetRSet(reinterpret_cast<Address>(p), 0);
829 }
830 }
831};
832
833
834int Heap::UpdateRSet(HeapObject* obj) {
835 ASSERT(!InNewSpace(obj));
836 // Special handling of fixed arrays to iterate the body based on the start
837 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
838 // will not work because Page::SetRSet needs to have the start of the
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +0000839 // object for large object pages.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000840 if (obj->IsFixedArray()) {
841 FixedArray* array = FixedArray::cast(obj);
842 int length = array->length();
843 for (int i = 0; i < length; i++) {
844 int offset = FixedArray::kHeaderSize + i * kPointerSize;
845 ASSERT(!Page::IsRSetSet(obj->address(), offset));
846 if (Heap::InNewSpace(array->get(i))) {
847 Page::SetRSet(obj->address(), offset);
848 }
849 }
850 } else if (!obj->IsCode()) {
851 // Skip code object, we know it does not contain inter-generational
852 // pointers.
853 UpdateRSetVisitor v;
854 obj->Iterate(&v);
855 }
856 return obj->Size();
857}
858
859
860void Heap::RebuildRSets() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000861 // By definition, we do not care about remembered set bits in code,
862 // data, or cell spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 map_space_->ClearRSet();
864 RebuildRSets(map_space_);
865
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000866 old_pointer_space_->ClearRSet();
867 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868
869 Heap::lo_space_->ClearRSet();
870 RebuildRSets(lo_space_);
871}
872
873
874void Heap::RebuildRSets(PagedSpace* space) {
875 HeapObjectIterator it(space);
876 while (it.has_next()) Heap::UpdateRSet(it.next());
877}
878
879
880void Heap::RebuildRSets(LargeObjectSpace* space) {
881 LargeObjectIterator it(space);
882 while (it.has_next()) Heap::UpdateRSet(it.next());
883}
884
885
886#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
887void Heap::RecordCopiedObject(HeapObject* obj) {
888 bool should_record = false;
889#ifdef DEBUG
890 should_record = FLAG_heap_stats;
891#endif
892#ifdef ENABLE_LOGGING_AND_PROFILING
893 should_record = should_record || FLAG_log_gc;
894#endif
895 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000896 if (new_space_.Contains(obj)) {
897 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000899 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900 }
901 }
902}
903#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
904
905
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000906
907HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000908 HeapObject* target,
909 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000910 // Copy the content of source to target.
911 CopyBlock(reinterpret_cast<Object**>(target->address()),
912 reinterpret_cast<Object**>(source->address()),
913 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914
kasper.lund7276f142008-07-30 08:49:36 +0000915 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000916 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000918#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000919 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000920 RecordCopiedObject(target);
921#endif
922
923 return target;
924}
925
926
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000927static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000928 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000929 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000930 InstanceType type = map->instance_type();
931 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
932 ASSERT(object->IsString() && !object->IsSymbol());
933 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000934}
935
936
937void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
938 ASSERT(InFromSpace(object));
939 MapWord first_word = object->map_word();
940 ASSERT(!first_word.IsForwardingAddress());
941
942 // Optimization: Bypass flattened ConsString objects.
943 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000944 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000945 *p = object;
946 // After patching *p we have to repeat the checks that object is in the
947 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000948 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000949 first_word = object->map_word();
950 if (first_word.IsForwardingAddress()) {
951 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000952 return;
953 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000954 }
955
kasper.lund7276f142008-07-30 08:49:36 +0000956 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000957 // We rely on live objects in new space to be at least two pointers,
958 // so we can store the from-space address and map pointer of promoted
959 // objects in the to space.
960 ASSERT(object_size >= 2 * kPointerSize);
961
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000962 // If the object should be promoted, we try to copy it to old space.
963 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000964 Object* result;
965 if (object_size > MaxObjectSizeInPagedSpace()) {
966 result = lo_space_->AllocateRawFixedArray(object_size);
967 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000968 // Save the from-space object pointer and its map pointer at the
969 // top of the to space to be swept and copied later. Write the
970 // forwarding address over the map word of the from-space
971 // object.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000972 HeapObject* target = HeapObject::cast(result);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000973 promotion_queue.insert(object, first_word.ToMap());
974 object->set_map_word(MapWord::FromForwardingAddress(target));
975
976 // Give the space allocated for the result a proper map by
977 // treating it as a free list node (not linked into the free
978 // list).
979 FreeListNode* node = FreeListNode::FromAddress(target->address());
980 node->set_size(object_size);
981
982 *p = target;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000983 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000984 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000985 } else {
986 OldSpace* target_space = Heap::TargetSpace(object);
987 ASSERT(target_space == Heap::old_pointer_space_ ||
988 target_space == Heap::old_data_space_);
989 result = target_space->AllocateRaw(object_size);
990 if (!result->IsFailure()) {
991 HeapObject* target = HeapObject::cast(result);
992 if (target_space == Heap::old_pointer_space_) {
993 // Save the from-space object pointer and its map pointer at the
994 // top of the to space to be swept and copied later. Write the
995 // forwarding address over the map word of the from-space
996 // object.
997 promotion_queue.insert(object, first_word.ToMap());
998 object->set_map_word(MapWord::FromForwardingAddress(target));
999
1000 // Give the space allocated for the result a proper map by
1001 // treating it as a free list node (not linked into the free
1002 // list).
1003 FreeListNode* node = FreeListNode::FromAddress(target->address());
1004 node->set_size(object_size);
1005
1006 *p = target;
1007 } else {
1008 // Objects promoted to the data space can be copied immediately
1009 // and not revisited---we will never sweep that space for
1010 // pointers and the copied objects do not contain pointers to
1011 // new space objects.
1012 *p = MigrateObject(object, target, object_size);
1013#ifdef DEBUG
1014 VerifyNonPointerSpacePointersVisitor v;
1015 (*p)->Iterate(&v);
1016#endif
1017 }
1018 return;
1019 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001020 }
1021 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001023 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 // Failed allocation at this point is utterly unexpected.
1025 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001026 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1027}
1028
1029
1030void Heap::ScavengePointer(HeapObject** p) {
1031 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001032}
1033
1034
1035Object* Heap::AllocatePartialMap(InstanceType instance_type,
1036 int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001037 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001038 if (result->IsFailure()) return result;
1039
1040 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001041 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001042 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1043 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001044 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001045 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1046 return result;
1047}
1048
1049
1050Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001051 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001052 if (result->IsFailure()) return result;
1053
1054 Map* map = reinterpret_cast<Map*>(result);
1055 map->set_map(meta_map());
1056 map->set_instance_type(instance_type);
1057 map->set_prototype(null_value());
1058 map->set_constructor(null_value());
1059 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001060 map->set_inobject_properties(0);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001061 map->set_pre_allocated_property_fields(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001062 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001063 map->set_code_cache(empty_fixed_array());
1064 map->set_unused_property_fields(0);
1065 map->set_bit_field(0);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001066 map->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067 return map;
1068}
1069
1070
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001071const Heap::StringTypeTable Heap::string_type_table[] = {
1072#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1073 {type, size, k##camel_name##MapRootIndex},
1074 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1075#undef STRING_TYPE_ELEMENT
1076};
1077
1078
1079const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1080#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1081 {contents, k##name##RootIndex},
1082 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1083#undef CONSTANT_SYMBOL_ELEMENT
1084};
1085
1086
1087const Heap::StructTable Heap::struct_table[] = {
1088#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1089 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1090 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1091#undef STRUCT_TABLE_ELEMENT
1092};
1093
1094
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001095bool Heap::CreateInitialMaps() {
1096 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1097 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001098 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001099 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1100 set_meta_map(new_meta_map);
1101 new_meta_map->set_map(new_meta_map);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001102
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001103 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001104 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001105 set_fixed_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001106
1107 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1108 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001109 set_oddball_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001110
1111 // Allocate the empty array
1112 obj = AllocateEmptyFixedArray();
1113 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001114 set_empty_fixed_array(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001115
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001116 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001117 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001118 set_null_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001119
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001120 // Allocate the empty descriptor array.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001121 obj = AllocateEmptyFixedArray();
1122 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001123 set_empty_descriptor_array(DescriptorArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001124
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001125 // Fix the instance_descriptors for the existing maps.
1126 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001127 meta_map()->set_code_cache(empty_fixed_array());
1128
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001129 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001130 fixed_array_map()->set_code_cache(empty_fixed_array());
1131
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001132 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001133 oddball_map()->set_code_cache(empty_fixed_array());
1134
1135 // Fix prototype object for existing maps.
1136 meta_map()->set_prototype(null_value());
1137 meta_map()->set_constructor(null_value());
1138
1139 fixed_array_map()->set_prototype(null_value());
1140 fixed_array_map()->set_constructor(null_value());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001141
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001142 oddball_map()->set_prototype(null_value());
1143 oddball_map()->set_constructor(null_value());
1144
1145 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1146 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001147 set_heap_number_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001148
1149 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1150 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001151 set_proxy_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001153 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1154 const StringTypeTable& entry = string_type_table[i];
1155 obj = AllocateMap(entry.type, entry.size);
1156 if (obj->IsFailure()) return false;
1157 roots_[entry.index] = Map::cast(obj);
1158 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001159
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001160 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001161 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001162 set_undetectable_short_string_map(Map::cast(obj));
1163 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001164
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001165 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001166 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001167 set_undetectable_medium_string_map(Map::cast(obj));
1168 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001169
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001170 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001171 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001172 set_undetectable_long_string_map(Map::cast(obj));
1173 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001174
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001175 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001176 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001177 set_undetectable_short_ascii_string_map(Map::cast(obj));
1178 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001179
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001180 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001181 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001182 set_undetectable_medium_ascii_string_map(Map::cast(obj));
1183 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001184
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001185 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001186 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001187 set_undetectable_long_ascii_string_map(Map::cast(obj));
1188 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001189
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001190 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001191 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001192 set_byte_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001193
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001194 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1195 if (obj->IsFailure()) return false;
1196 set_pixel_array_map(Map::cast(obj));
1197
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001198 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1199 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001200 set_code_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001201
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001202 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1203 JSGlobalPropertyCell::kSize);
1204 if (obj->IsFailure()) return false;
1205 set_global_property_cell_map(Map::cast(obj));
1206
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001207 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1208 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001209 set_one_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001210
1211 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1212 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001213 set_two_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001214
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001215 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1216 const StructTable& entry = struct_table[i];
1217 obj = AllocateMap(entry.type, entry.size);
1218 if (obj->IsFailure()) return false;
1219 roots_[entry.index] = Map::cast(obj);
1220 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001221
ager@chromium.org236ad962008-09-25 09:45:57 +00001222 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001223 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001224 set_hash_table_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001225
ager@chromium.org236ad962008-09-25 09:45:57 +00001226 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001227 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001228 set_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229
ager@chromium.org236ad962008-09-25 09:45:57 +00001230 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001231 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001232 set_catch_context_map(Map::cast(obj));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001233
1234 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1235 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001236 set_global_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001237
1238 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1239 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001240 set_boilerplate_function_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001241
1242 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1243 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001244 set_shared_function_info_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001245
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001246 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001247 return true;
1248}
1249
1250
1251Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1252 // Statically ensure that it is safe to allocate heap numbers in paged
1253 // spaces.
1254 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001255 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001256 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001257 if (result->IsFailure()) return result;
1258
1259 HeapObject::cast(result)->set_map(heap_number_map());
1260 HeapNumber::cast(result)->set_value(value);
1261 return result;
1262}
1263
1264
1265Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001266 // Use general version, if we're forced to always allocate.
1267 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001268 // This version of AllocateHeapNumber is optimized for
1269 // allocation in new space.
1270 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1271 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001272 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001273 if (result->IsFailure()) return result;
1274 HeapObject::cast(result)->set_map(heap_number_map());
1275 HeapNumber::cast(result)->set_value(value);
1276 return result;
1277}
1278
1279
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001280Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001281 Object* result = AllocateRawCell();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001282 if (result->IsFailure()) return result;
1283 HeapObject::cast(result)->set_map(global_property_cell_map());
1284 JSGlobalPropertyCell::cast(result)->set_value(value);
1285 return result;
1286}
1287
1288
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001289Object* Heap::CreateOddball(Map* map,
1290 const char* to_string,
1291 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001292 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001293 if (result->IsFailure()) return result;
1294 return Oddball::cast(result)->Initialize(to_string, to_number);
1295}
1296
1297
1298bool Heap::CreateApiObjects() {
1299 Object* obj;
1300
1301 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1302 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001303 set_neander_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001304
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001305 obj = Heap::AllocateJSObjectFromMap(neander_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001306 if (obj->IsFailure()) return false;
1307 Object* elements = AllocateFixedArray(2);
1308 if (elements->IsFailure()) return false;
1309 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1310 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001311 set_message_listeners(JSObject::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001312
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001313 return true;
1314}
1315
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001316
1317void Heap::CreateCEntryStub() {
1318 CEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001319 set_c_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001320}
1321
1322
1323void Heap::CreateCEntryDebugBreakStub() {
1324 CEntryDebugBreakStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001325 set_c_entry_debug_break_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001326}
1327
1328
1329void Heap::CreateJSEntryStub() {
1330 JSEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001331 set_js_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001332}
1333
1334
1335void Heap::CreateJSConstructEntryStub() {
1336 JSConstructEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001337 set_js_construct_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001338}
1339
1340
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001341void Heap::CreateFixedStubs() {
1342 // Here we create roots for fixed stubs. They are needed at GC
1343 // for cooking and uncooking (check out frames.cc).
1344 // The eliminates the need for doing dictionary lookup in the
1345 // stub cache for these stubs.
1346 HandleScope scope;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001347 // gcc-4.4 has problem generating correct code of following snippet:
1348 // { CEntryStub stub;
1349 // c_entry_code_ = *stub.GetCode();
1350 // }
1351 // { CEntryDebugBreakStub stub;
1352 // c_entry_debug_break_code_ = *stub.GetCode();
1353 // }
1354 // To workaround the problem, make separate functions without inlining.
1355 Heap::CreateCEntryStub();
1356 Heap::CreateCEntryDebugBreakStub();
1357 Heap::CreateJSEntryStub();
1358 Heap::CreateJSConstructEntryStub();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001359}
1360
1361
1362bool Heap::CreateInitialObjects() {
1363 Object* obj;
1364
1365 // The -0 value must be set before NumberFromDouble works.
1366 obj = AllocateHeapNumber(-0.0, TENURED);
1367 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001368 set_minus_zero_value(obj);
1369 ASSERT(signbit(minus_zero_value()->Number()) != 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001370
1371 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1372 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001373 set_nan_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001375 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001376 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001377 set_undefined_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001378 ASSERT(!InNewSpace(undefined_value()));
1379
1380 // Allocate initial symbol table.
1381 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1382 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001383 // Don't use set_symbol_table() due to asserts.
1384 roots_[kSymbolTableRootIndex] = obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001385
1386 // Assign the print strings for oddballs after creating symboltable.
1387 Object* symbol = LookupAsciiSymbol("undefined");
1388 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001389 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1390 Oddball::cast(undefined_value())->set_to_number(nan_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001391
1392 // Assign the print strings for oddballs after creating symboltable.
1393 symbol = LookupAsciiSymbol("null");
1394 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001395 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1396 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001397
1398 // Allocate the null_value
1399 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1400 if (obj->IsFailure()) return false;
1401
1402 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1403 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001404 set_true_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405
1406 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1407 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001408 set_false_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001409
1410 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1411 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001412 set_the_hole_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001413
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001414 obj = CreateOddball(
1415 oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
1416 if (obj->IsFailure()) return false;
1417 set_no_interceptor_result_sentinel(obj);
1418
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001419 obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
1420 if (obj->IsFailure()) return false;
1421 set_termination_exception(obj);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001422
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001423 // Allocate the empty string.
1424 obj = AllocateRawAsciiString(0, TENURED);
1425 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001426 set_empty_string(String::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001427
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001428 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1429 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1430 if (obj->IsFailure()) return false;
1431 roots_[constant_symbol_table[i].index] = String::cast(obj);
1432 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001433
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001434 // Allocate the hidden symbol which is used to identify the hidden properties
1435 // in JSObjects. The hash code has a special value so that it will not match
1436 // the empty string when searching for the property. It cannot be part of the
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001437 // loop above because it needs to be allocated manually with the special
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001438 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1439 // that it will always be at the first entry in property descriptors.
1440 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1441 if (obj->IsFailure()) return false;
1442 hidden_symbol_ = String::cast(obj);
1443
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001444 // Allocate the proxy for __proto__.
1445 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1446 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001447 set_prototype_accessors(Proxy::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001448
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001449 // Allocate the code_stubs dictionary. The initial size is set to avoid
1450 // expanding the dictionary during bootstrapping.
1451 obj = NumberDictionary::Allocate(128);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001452 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001453 set_code_stubs(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001454
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001455 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1456 // is set to avoid expanding the dictionary during bootstrapping.
1457 obj = NumberDictionary::Allocate(64);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001458 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001459 set_non_monomorphic_cache(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001460
1461 CreateFixedStubs();
1462
1463 // Allocate the number->string conversion cache
1464 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1465 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001466 set_number_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001467
1468 // Allocate cache for single character strings.
1469 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1470 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001471 set_single_character_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001472
1473 // Allocate cache for external strings pointing to native source code.
1474 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1475 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001476 set_natives_source_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001477
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001478 // Handling of script id generation is in Factory::NewScript.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001479 set_last_script_id(undefined_value());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001480
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001481 // Initialize keyed lookup cache.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001482 KeyedLookupCache::Clear();
1483
1484 // Initialize context slot cache.
1485 ContextSlotCache::Clear();
1486
1487 // Initialize descriptor cache.
1488 DescriptorLookupCache::Clear();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001489
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001490 // Initialize compilation cache.
1491 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001492
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001493 return true;
1494}
1495
1496
1497static inline int double_get_hash(double d) {
1498 DoubleRepresentation rep(d);
1499 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1500 (Heap::kNumberStringCacheSize - 1));
1501}
1502
1503
1504static inline int smi_get_hash(Smi* smi) {
1505 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1506}
1507
1508
1509
1510Object* Heap::GetNumberStringCache(Object* number) {
1511 int hash;
1512 if (number->IsSmi()) {
1513 hash = smi_get_hash(Smi::cast(number));
1514 } else {
1515 hash = double_get_hash(number->Number());
1516 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001517 Object* key = number_string_cache()->get(hash * 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001518 if (key == number) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001519 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001520 } else if (key->IsHeapNumber() &&
1521 number->IsHeapNumber() &&
1522 key->Number() == number->Number()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001523 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001524 }
1525 return undefined_value();
1526}
1527
1528
1529void Heap::SetNumberStringCache(Object* number, String* string) {
1530 int hash;
1531 if (number->IsSmi()) {
1532 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001533 number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001534 } else {
1535 hash = double_get_hash(number->Number());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001536 number_string_cache()->set(hash * 2, number);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001537 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001538 number_string_cache()->set(hash * 2 + 1, string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539}
1540
1541
1542Object* Heap::SmiOrNumberFromDouble(double value,
1543 bool new_object,
1544 PretenureFlag pretenure) {
1545 // We need to distinguish the minus zero value and this cannot be
1546 // done after conversion to int. Doing this by comparing bit
1547 // patterns is faster than using fpclassify() et al.
1548 static const DoubleRepresentation plus_zero(0.0);
1549 static const DoubleRepresentation minus_zero(-0.0);
1550 static const DoubleRepresentation nan(OS::nan_value());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001551 ASSERT(minus_zero_value() != NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001552 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1553
1554 DoubleRepresentation rep(value);
1555 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1556 if (rep.bits == minus_zero.bits) {
1557 return new_object ? AllocateHeapNumber(-0.0, pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001558 : minus_zero_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559 }
1560 if (rep.bits == nan.bits) {
1561 return new_object
1562 ? AllocateHeapNumber(OS::nan_value(), pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001563 : nan_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001564 }
1565
1566 // Try to represent the value as a tagged small integer.
1567 int int_value = FastD2I(value);
1568 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1569 return Smi::FromInt(int_value);
1570 }
1571
1572 // Materialize the value in the heap.
1573 return AllocateHeapNumber(value, pretenure);
1574}
1575
1576
1577Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1578 return SmiOrNumberFromDouble(value,
1579 true /* number object must be new */,
1580 pretenure);
1581}
1582
1583
1584Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1585 return SmiOrNumberFromDouble(value,
1586 false /* use preallocated NaN, -0.0 */,
1587 pretenure);
1588}
1589
1590
1591Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1592 // Statically ensure that it is safe to allocate proxies in paged spaces.
1593 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001594 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001595 Object* result = Allocate(proxy_map(), space);
1596 if (result->IsFailure()) return result;
1597
1598 Proxy::cast(result)->set_proxy(proxy);
1599 return result;
1600}
1601
1602
1603Object* Heap::AllocateSharedFunctionInfo(Object* name) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001604 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605 if (result->IsFailure()) return result;
1606
1607 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1608 share->set_name(name);
1609 Code* illegal = Builtins::builtin(Builtins::Illegal);
1610 share->set_code(illegal);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001611 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1612 share->set_construct_stub(construct_stub);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001613 share->set_expected_nof_properties(0);
1614 share->set_length(0);
1615 share->set_formal_parameter_count(0);
1616 share->set_instance_class_name(Object_symbol());
1617 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618 share->set_script(undefined_value());
1619 share->set_start_position_and_type(0);
1620 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001621 share->set_inferred_name(empty_string());
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001622 share->set_compiler_hints(0);
1623 share->set_this_property_assignments_count(0);
1624 share->set_this_property_assignments(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001625 return result;
1626}
1627
1628
ager@chromium.org3e875802009-06-29 08:26:34 +00001629Object* Heap::AllocateConsString(String* first, String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001630 int first_length = first->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001631 if (first_length == 0) return second;
1632
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001633 int second_length = second->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001634 if (second_length == 0) return first;
1635
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001636 int length = first_length + second_length;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001637 bool is_ascii = first->IsAsciiRepresentation()
1638 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001639
ager@chromium.org3e875802009-06-29 08:26:34 +00001640 // Make sure that an out of memory exception is thrown if the length
1641 // of the new cons string is too large to fit in a Smi.
1642 if (length > Smi::kMaxValue || length < -0) {
1643 Top::context()->mark_out_of_memory();
1644 return Failure::OutOfMemoryException();
1645 }
1646
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001647 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001648 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001649 ASSERT(first->IsFlat());
1650 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001651 if (is_ascii) {
1652 Object* result = AllocateRawAsciiString(length);
1653 if (result->IsFailure()) return result;
1654 // Copy the characters into the new object.
1655 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org3e875802009-06-29 08:26:34 +00001656 // Copy first part.
1657 char* src = SeqAsciiString::cast(first)->GetChars();
1658 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1659 // Copy second part.
1660 src = SeqAsciiString::cast(second)->GetChars();
1661 for (int i = 0; i < second_length; i++) *dest++ = src[i];
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001662 return result;
1663 } else {
1664 Object* result = AllocateRawTwoByteString(length);
1665 if (result->IsFailure()) return result;
1666 // Copy the characters into the new object.
1667 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001668 String::WriteToFlat(first, dest, 0, first_length);
1669 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001670 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001671 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001672 }
1673
1674 Map* map;
1675 if (length <= String::kMaxShortStringSize) {
1676 map = is_ascii ? short_cons_ascii_string_map()
1677 : short_cons_string_map();
1678 } else if (length <= String::kMaxMediumStringSize) {
1679 map = is_ascii ? medium_cons_ascii_string_map()
1680 : medium_cons_string_map();
1681 } else {
1682 map = is_ascii ? long_cons_ascii_string_map()
1683 : long_cons_string_map();
1684 }
1685
1686 Object* result = Allocate(map, NEW_SPACE);
1687 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001688 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001689 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001690 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1691 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001692 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001693 return result;
1694}
1695
1696
ager@chromium.org870a0b62008-11-04 11:43:05 +00001697Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001698 int start,
1699 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001700 int length = end - start;
1701
1702 // If the resulting string is small make a sub string.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001703 if (length <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001704 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705 }
1706
1707 Map* map;
1708 if (length <= String::kMaxShortStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001709 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001710 short_sliced_ascii_string_map() :
1711 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001713 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001714 medium_sliced_ascii_string_map() :
1715 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001716 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001717 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001718 long_sliced_ascii_string_map() :
1719 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720 }
1721
1722 Object* result = Allocate(map, NEW_SPACE);
1723 if (result->IsFailure()) return result;
1724
1725 SlicedString* sliced_string = SlicedString::cast(result);
1726 sliced_string->set_buffer(buffer);
1727 sliced_string->set_start(start);
1728 sliced_string->set_length(length);
1729
1730 return result;
1731}
1732
1733
ager@chromium.org870a0b62008-11-04 11:43:05 +00001734Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001735 int start,
1736 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001737 int length = end - start;
1738
ager@chromium.org7c537e22008-10-16 08:43:32 +00001739 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001740 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001741 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001742 }
1743
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001744 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001745 if (!buffer->IsFlat()) {
1746 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001747 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001748
ager@chromium.org5ec48922009-05-05 07:25:34 +00001749 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001750 ? AllocateRawAsciiString(length)
1751 : AllocateRawTwoByteString(length);
1752 if (result->IsFailure()) return result;
1753
1754 // Copy the characters into the new object.
1755 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001756 StringHasher hasher(length);
1757 int i = 0;
1758 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001759 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001760 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001761 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001762 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001763 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001764 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001765 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001766 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001767 }
1768 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001769 return result;
1770}
1771
1772
1773Object* Heap::AllocateExternalStringFromAscii(
1774 ExternalAsciiString::Resource* resource) {
1775 Map* map;
1776 int length = resource->length();
1777 if (length <= String::kMaxShortStringSize) {
1778 map = short_external_ascii_string_map();
1779 } else if (length <= String::kMaxMediumStringSize) {
1780 map = medium_external_ascii_string_map();
1781 } else {
1782 map = long_external_ascii_string_map();
1783 }
1784
1785 Object* result = Allocate(map, NEW_SPACE);
1786 if (result->IsFailure()) return result;
1787
1788 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1789 external_string->set_length(length);
1790 external_string->set_resource(resource);
1791
1792 return result;
1793}
1794
1795
1796Object* Heap::AllocateExternalStringFromTwoByte(
1797 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001798 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001799
ager@chromium.org6f10e412009-02-13 10:11:16 +00001800 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001801 Object* result = Allocate(map, NEW_SPACE);
1802 if (result->IsFailure()) return result;
1803
1804 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1805 external_string->set_length(length);
1806 external_string->set_resource(resource);
1807
1808 return result;
1809}
1810
1811
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001812Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001813 if (code <= String::kMaxAsciiCharCode) {
1814 Object* value = Heap::single_character_string_cache()->get(code);
1815 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001816
1817 char buffer[1];
1818 buffer[0] = static_cast<char>(code);
1819 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1820
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001821 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001822 Heap::single_character_string_cache()->set(code, result);
1823 return result;
1824 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001825
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001826 Object* result = Heap::AllocateRawTwoByteString(1);
1827 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001828 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001829 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001830 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001831}
1832
1833
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001834Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1835 if (pretenure == NOT_TENURED) {
1836 return AllocateByteArray(length);
1837 }
1838 int size = ByteArray::SizeFor(length);
1839 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001840 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001841
1842 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1843
1844 if (result->IsFailure()) return result;
1845
1846 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1847 reinterpret_cast<Array*>(result)->set_length(length);
1848 return result;
1849}
1850
1851
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001852Object* Heap::AllocateByteArray(int length) {
1853 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001854 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001855 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001856
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001857 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001858
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 if (result->IsFailure()) return result;
1860
1861 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1862 reinterpret_cast<Array*>(result)->set_length(length);
1863 return result;
1864}
1865
1866
ager@chromium.org6f10e412009-02-13 10:11:16 +00001867void Heap::CreateFillerObjectAt(Address addr, int size) {
1868 if (size == 0) return;
1869 HeapObject* filler = HeapObject::FromAddress(addr);
1870 if (size == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001871 filler->set_map(Heap::one_pointer_filler_map());
ager@chromium.org6f10e412009-02-13 10:11:16 +00001872 } else {
1873 filler->set_map(Heap::byte_array_map());
1874 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1875 }
1876}
1877
1878
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001879Object* Heap::AllocatePixelArray(int length,
1880 uint8_t* external_pointer,
1881 PretenureFlag pretenure) {
1882 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1883
1884 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
1885
1886 if (result->IsFailure()) return result;
1887
1888 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
1889 reinterpret_cast<PixelArray*>(result)->set_length(length);
1890 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
1891
1892 return result;
1893}
1894
1895
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001896Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001897 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001898 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001899 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001900 // Compute size
1901 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1902 int sinfo_size = 0;
1903 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1904 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001905 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001906 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001907 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001908 result = lo_space_->AllocateRawCode(obj_size);
1909 } else {
1910 result = code_space_->AllocateRaw(obj_size);
1911 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001912
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001913 if (result->IsFailure()) return result;
1914
1915 // Initialize the object
1916 HeapObject::cast(result)->set_map(code_map());
1917 Code* code = Code::cast(result);
1918 code->set_instruction_size(desc.instr_size);
1919 code->set_relocation_size(desc.reloc_size);
1920 code->set_sinfo_size(sinfo_size);
1921 code->set_flags(flags);
1922 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001923 // Allow self references to created code object by patching the handle to
1924 // point to the newly allocated Code object.
1925 if (!self_reference.is_null()) {
1926 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001927 }
1928 // Migrate generated code.
1929 // The generated code can contain Object** values (typically from handles)
1930 // that are dereferenced during the copy to point directly to the actual heap
1931 // objects. These pointers can include references to the code object itself,
1932 // through the self_reference parameter.
1933 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001934 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1935
1936#ifdef DEBUG
1937 code->Verify();
1938#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001939 return code;
1940}
1941
1942
1943Object* Heap::CopyCode(Code* code) {
1944 // Allocate an object the same size as the code object.
1945 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001946 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001947 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001948 result = lo_space_->AllocateRawCode(obj_size);
1949 } else {
1950 result = code_space_->AllocateRaw(obj_size);
1951 }
1952
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001953 if (result->IsFailure()) return result;
1954
1955 // Copy code object.
1956 Address old_addr = code->address();
1957 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001958 CopyBlock(reinterpret_cast<Object**>(new_addr),
1959 reinterpret_cast<Object**>(old_addr),
1960 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001961 // Relocate the copy.
1962 Code* new_code = Code::cast(result);
1963 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001964 return new_code;
1965}
1966
1967
1968Object* Heap::Allocate(Map* map, AllocationSpace space) {
1969 ASSERT(gc_state_ == NOT_IN_GC);
1970 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001971 Object* result = AllocateRaw(map->instance_size(),
1972 space,
1973 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001974 if (result->IsFailure()) return result;
1975 HeapObject::cast(result)->set_map(map);
1976 return result;
1977}
1978
1979
1980Object* Heap::InitializeFunction(JSFunction* function,
1981 SharedFunctionInfo* shared,
1982 Object* prototype) {
1983 ASSERT(!prototype->IsMap());
1984 function->initialize_properties();
1985 function->initialize_elements();
1986 function->set_shared(shared);
1987 function->set_prototype_or_initial_map(prototype);
1988 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001989 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001990 return function;
1991}
1992
1993
1994Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001995 // Allocate the prototype. Make sure to use the object function
1996 // from the function's context, since the function can be from a
1997 // different context.
1998 JSFunction* object_function =
1999 function->context()->global_context()->object_function();
2000 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002001 if (prototype->IsFailure()) return prototype;
2002 // When creating the prototype for the function we must set its
2003 // constructor to the function.
2004 Object* result =
2005 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2006 function,
2007 DONT_ENUM);
2008 if (result->IsFailure()) return result;
2009 return prototype;
2010}
2011
2012
2013Object* Heap::AllocateFunction(Map* function_map,
2014 SharedFunctionInfo* shared,
2015 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002016 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002017 if (result->IsFailure()) return result;
2018 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2019}
2020
2021
2022Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002023 // To get fast allocation and map sharing for arguments objects we
2024 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002025
2026 // This calls Copy directly rather than using Heap::AllocateRaw so we
2027 // duplicate the check here.
2028 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2029
2030 JSObject* boilerplate =
2031 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002032
2033 // Make the clone.
2034 Map* map = boilerplate->map();
2035 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002036 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002037 if (result->IsFailure()) return result;
2038
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002039 // Copy the content. The arguments boilerplate doesn't have any
2040 // fields that point to new space so it's safe to skip the write
2041 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002042 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2043 reinterpret_cast<Object**>(boilerplate->address()),
2044 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002045
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002046 // Set the two properties.
2047 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002048 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002049 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2050 Smi::FromInt(length),
2051 SKIP_WRITE_BARRIER);
2052
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002053 // Check the state of the object
2054 ASSERT(JSObject::cast(result)->HasFastProperties());
2055 ASSERT(JSObject::cast(result)->HasFastElements());
2056
2057 return result;
2058}
2059
2060
2061Object* Heap::AllocateInitialMap(JSFunction* fun) {
2062 ASSERT(!fun->has_initial_map());
2063
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002064 // First create a new map with the size and number of in-object properties
2065 // suggested by the function.
2066 int instance_size = fun->shared()->CalculateInstanceSize();
2067 int in_object_properties = fun->shared()->CalculateInObjectProperties();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002068 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002069 if (map_obj->IsFailure()) return map_obj;
2070
2071 // Fetch or allocate prototype.
2072 Object* prototype;
2073 if (fun->has_instance_prototype()) {
2074 prototype = fun->instance_prototype();
2075 } else {
2076 prototype = AllocateFunctionPrototype(fun);
2077 if (prototype->IsFailure()) return prototype;
2078 }
2079 Map* map = Map::cast(map_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002080 map->set_inobject_properties(in_object_properties);
2081 map->set_unused_property_fields(in_object_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002082 map->set_prototype(prototype);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002083
2084 // If the function has only simple this property assignments add field
2085 // descriptors for these to the initial map as the object cannot be
2086 // constructed without having these properties.
2087 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
2088 if (fun->shared()->has_only_this_property_assignments() &&
2089 fun->shared()->this_property_assignments_count() > 0) {
2090 int count = fun->shared()->this_property_assignments_count();
2091 if (count > in_object_properties) {
2092 count = in_object_properties;
2093 }
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00002094 Object* descriptors_obj = DescriptorArray::Allocate(count);
2095 if (descriptors_obj->IsFailure()) return descriptors_obj;
2096 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002097 for (int i = 0; i < count; i++) {
2098 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2099 ASSERT(name->IsSymbol());
2100 FieldDescriptor field(name, i, NONE);
2101 descriptors->Set(i, &field);
2102 }
2103 descriptors->Sort();
2104 map->set_instance_descriptors(descriptors);
2105 map->set_pre_allocated_property_fields(count);
2106 map->set_unused_property_fields(in_object_properties - count);
2107 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002108 return map;
2109}
2110
2111
2112void Heap::InitializeJSObjectFromMap(JSObject* obj,
2113 FixedArray* properties,
2114 Map* map) {
2115 obj->set_properties(properties);
2116 obj->initialize_elements();
2117 // TODO(1240798): Initialize the object's body using valid initial values
2118 // according to the object's initial map. For example, if the map's
2119 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2120 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2121 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2122 // verification code has to cope with (temporarily) invalid objects. See
2123 // for example, JSArray::JSArrayVerify).
2124 obj->InitializeBody(map->instance_size());
2125}
2126
2127
2128Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2129 // JSFunctions should be allocated using AllocateFunction to be
2130 // properly initialized.
2131 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2132
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002133 // Both types of globla objects should be allocated using
2134 // AllocateGloblaObject to be properly initialized.
2135 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2136 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2137
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138 // Allocate the backing storage for the properties.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002139 int prop_size =
2140 map->pre_allocated_property_fields() +
2141 map->unused_property_fields() -
2142 map->inobject_properties();
2143 ASSERT(prop_size >= 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002144 Object* properties = AllocateFixedArray(prop_size, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002145 if (properties->IsFailure()) return properties;
2146
2147 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002148 AllocationSpace space =
2149 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002150 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002151 Object* obj = Allocate(map, space);
2152 if (obj->IsFailure()) return obj;
2153
2154 // Initialize the JSObject.
2155 InitializeJSObjectFromMap(JSObject::cast(obj),
2156 FixedArray::cast(properties),
2157 map);
2158 return obj;
2159}
2160
2161
2162Object* Heap::AllocateJSObject(JSFunction* constructor,
2163 PretenureFlag pretenure) {
2164 // Allocate the initial map if absent.
2165 if (!constructor->has_initial_map()) {
2166 Object* initial_map = AllocateInitialMap(constructor);
2167 if (initial_map->IsFailure()) return initial_map;
2168 constructor->set_initial_map(Map::cast(initial_map));
2169 Map::cast(initial_map)->set_constructor(constructor);
2170 }
2171 // Allocate the object based on the constructors initial map.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002172 Object* result =
2173 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2174 // Make sure result is NOT a global object if valid.
2175 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2176 return result;
2177}
2178
2179
2180Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2181 ASSERT(constructor->has_initial_map());
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002182 Map* map = constructor->initial_map();
2183
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002184 // Make sure no field properties are described in the initial map.
2185 // This guarantees us that normalizing the properties does not
2186 // require us to change property values to JSGlobalPropertyCells.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002187 ASSERT(map->NextFreePropertyIndex() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002188
2189 // Make sure we don't have a ton of pre-allocated slots in the
2190 // global objects. They will be unused once we normalize the object.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002191 ASSERT(map->unused_property_fields() == 0);
2192 ASSERT(map->inobject_properties() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002193
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002194 // Initial size of the backing store to avoid resize of the storage during
2195 // bootstrapping. The size differs between the JS global object ad the
2196 // builtins object.
2197 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002198
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002199 // Allocate a dictionary object for backing storage.
2200 Object* obj =
2201 StringDictionary::Allocate(
2202 map->NumberOfDescribedProperties() * 2 + initial_size);
2203 if (obj->IsFailure()) return obj;
2204 StringDictionary* dictionary = StringDictionary::cast(obj);
2205
2206 // The global object might be created from an object template with accessors.
2207 // Fill these accessors into the dictionary.
2208 DescriptorArray* descs = map->instance_descriptors();
2209 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2210 PropertyDetails details = descs->GetDetails(i);
2211 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2212 PropertyDetails d =
2213 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2214 Object* value = descs->GetCallbacksObject(i);
2215 value = Heap::AllocateJSGlobalPropertyCell(value);
2216 if (value->IsFailure()) return value;
2217
2218 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2219 if (result->IsFailure()) return result;
2220 dictionary = StringDictionary::cast(result);
2221 }
2222
2223 // Allocate the global object and initialize it with the backing store.
2224 obj = Allocate(map, OLD_POINTER_SPACE);
2225 if (obj->IsFailure()) return obj;
2226 JSObject* global = JSObject::cast(obj);
2227 InitializeJSObjectFromMap(global, dictionary, map);
2228
2229 // Create a new map for the global object.
2230 obj = map->CopyDropDescriptors();
2231 if (obj->IsFailure()) return obj;
2232 Map* new_map = Map::cast(obj);
2233
2234 // Setup the global object as a normalized object.
2235 global->set_map(new_map);
2236 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2237 global->set_properties(dictionary);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002238
2239 // Make sure result is a global object with properties in dictionary.
2240 ASSERT(global->IsGlobalObject());
2241 ASSERT(!global->HasFastProperties());
2242 return global;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002243}
2244
2245
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002246Object* Heap::CopyJSObject(JSObject* source) {
2247 // Never used to copy functions. If functions need to be copied we
2248 // have to be careful to clear the literals array.
2249 ASSERT(!source->IsJSFunction());
2250
2251 // Make the clone.
2252 Map* map = source->map();
2253 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002254 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002255
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002256 // If we're forced to always allocate, we use the general allocation
2257 // functions which may leave us with an object in old space.
2258 if (always_allocate()) {
2259 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2260 if (clone->IsFailure()) return clone;
2261 Address clone_address = HeapObject::cast(clone)->address();
2262 CopyBlock(reinterpret_cast<Object**>(clone_address),
2263 reinterpret_cast<Object**>(source->address()),
2264 object_size);
2265 // Update write barrier for all fields that lie beyond the header.
2266 for (int offset = JSObject::kHeaderSize;
2267 offset < object_size;
2268 offset += kPointerSize) {
2269 RecordWrite(clone_address, offset);
2270 }
2271 } else {
2272 clone = new_space_.AllocateRaw(object_size);
2273 if (clone->IsFailure()) return clone;
2274 ASSERT(Heap::InNewSpace(clone));
2275 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002276 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002277 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2278 reinterpret_cast<Object**>(source->address()),
2279 object_size);
2280 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002281
2282 FixedArray* elements = FixedArray::cast(source->elements());
2283 FixedArray* properties = FixedArray::cast(source->properties());
2284 // Update elements if necessary.
2285 if (elements->length()> 0) {
2286 Object* elem = CopyFixedArray(elements);
2287 if (elem->IsFailure()) return elem;
2288 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2289 }
2290 // Update properties if necessary.
2291 if (properties->length() > 0) {
2292 Object* prop = CopyFixedArray(properties);
2293 if (prop->IsFailure()) return prop;
2294 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2295 }
2296 // Return the new clone.
2297 return clone;
2298}
2299
2300
2301Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2302 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002303 // Allocate initial map if absent.
2304 if (!constructor->has_initial_map()) {
2305 Object* initial_map = AllocateInitialMap(constructor);
2306 if (initial_map->IsFailure()) return initial_map;
2307 constructor->set_initial_map(Map::cast(initial_map));
2308 Map::cast(initial_map)->set_constructor(constructor);
2309 }
2310
2311 Map* map = constructor->initial_map();
2312
2313 // Check that the already allocated object has the same size as
2314 // objects allocated using the constructor.
2315 ASSERT(map->instance_size() == object->map()->instance_size());
2316
2317 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002318 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002319 Object* properties = AllocateFixedArray(prop_size, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002320 if (properties->IsFailure()) return properties;
2321
2322 // Reset the map for the object.
2323 object->set_map(constructor->initial_map());
2324
2325 // Reinitialize the object from the constructor map.
2326 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2327 return object;
2328}
2329
2330
2331Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2332 PretenureFlag pretenure) {
2333 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2334 if (result->IsFailure()) return result;
2335
2336 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002337 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002338 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002339 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002340 }
2341 return result;
2342}
2343
2344
2345Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2346 PretenureFlag pretenure) {
2347 // Count the number of characters in the UTF-8 string and check if
2348 // it is an ASCII string.
2349 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2350 decoder->Reset(string.start(), string.length());
2351 int chars = 0;
2352 bool is_ascii = true;
2353 while (decoder->has_more()) {
2354 uc32 r = decoder->GetNext();
2355 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2356 chars++;
2357 }
2358
2359 // If the string is ascii, we do not need to convert the characters
2360 // since UTF8 is backwards compatible with ascii.
2361 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2362
2363 Object* result = AllocateRawTwoByteString(chars, pretenure);
2364 if (result->IsFailure()) return result;
2365
2366 // Convert and copy the characters into the new object.
2367 String* string_result = String::cast(result);
2368 decoder->Reset(string.start(), string.length());
2369 for (int i = 0; i < chars; i++) {
2370 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002371 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002372 }
2373 return result;
2374}
2375
2376
2377Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2378 PretenureFlag pretenure) {
2379 // Check if the string is an ASCII string.
2380 int i = 0;
2381 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2382
2383 Object* result;
2384 if (i == string.length()) { // It's an ASCII string.
2385 result = AllocateRawAsciiString(string.length(), pretenure);
2386 } else { // It's not an ASCII string.
2387 result = AllocateRawTwoByteString(string.length(), pretenure);
2388 }
2389 if (result->IsFailure()) return result;
2390
2391 // Copy the characters into the new object, which may be either ASCII or
2392 // UTF-16.
2393 String* string_result = String::cast(result);
2394 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002395 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002396 }
2397 return result;
2398}
2399
2400
2401Map* Heap::SymbolMapForString(String* string) {
2402 // If the string is in new space it cannot be used as a symbol.
2403 if (InNewSpace(string)) return NULL;
2404
2405 // Find the corresponding symbol map for strings.
2406 Map* map = string->map();
2407
2408 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2409 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2410 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2411
2412 if (map == short_string_map()) return short_symbol_map();
2413 if (map == medium_string_map()) return medium_symbol_map();
2414 if (map == long_string_map()) return long_symbol_map();
2415
2416 if (map == short_cons_string_map()) return short_cons_symbol_map();
2417 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2418 if (map == long_cons_string_map()) return long_cons_symbol_map();
2419
2420 if (map == short_cons_ascii_string_map()) {
2421 return short_cons_ascii_symbol_map();
2422 }
2423 if (map == medium_cons_ascii_string_map()) {
2424 return medium_cons_ascii_symbol_map();
2425 }
2426 if (map == long_cons_ascii_string_map()) {
2427 return long_cons_ascii_symbol_map();
2428 }
2429
2430 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002431 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2432 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002433
2434 if (map == short_sliced_ascii_string_map()) {
2435 return short_sliced_ascii_symbol_map();
2436 }
2437 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002438 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002439 }
2440 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002441 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002442 }
2443
ager@chromium.org6f10e412009-02-13 10:11:16 +00002444 if (map == short_external_string_map()) {
2445 return short_external_symbol_map();
2446 }
2447 if (map == medium_external_string_map()) {
2448 return medium_external_symbol_map();
2449 }
2450 if (map == long_external_string_map()) {
2451 return long_external_symbol_map();
2452 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002453
2454 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002455 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002456 }
2457 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002458 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002459 }
2460 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002461 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002462 }
2463
2464 // No match found.
2465 return NULL;
2466}
2467
2468
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002469Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2470 int chars,
2471 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002472 // Ensure the chars matches the number of characters in the buffer.
2473 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2474 // Determine whether the string is ascii.
2475 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002476 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002477 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2478 }
2479 buffer->Rewind();
2480
2481 // Compute map and object size.
2482 int size;
2483 Map* map;
2484
2485 if (is_ascii) {
2486 if (chars <= String::kMaxShortStringSize) {
2487 map = short_ascii_symbol_map();
2488 } else if (chars <= String::kMaxMediumStringSize) {
2489 map = medium_ascii_symbol_map();
2490 } else {
2491 map = long_ascii_symbol_map();
2492 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002493 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002494 } else {
2495 if (chars <= String::kMaxShortStringSize) {
2496 map = short_symbol_map();
2497 } else if (chars <= String::kMaxMediumStringSize) {
2498 map = medium_symbol_map();
2499 } else {
2500 map = long_symbol_map();
2501 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002502 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002503 }
2504
2505 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002506 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002507 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002508 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002509 if (result->IsFailure()) return result;
2510
2511 reinterpret_cast<HeapObject*>(result)->set_map(map);
2512 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002513 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002514 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002515
ager@chromium.org870a0b62008-11-04 11:43:05 +00002516 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002517
2518 // Fill in the characters.
2519 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002520 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002521 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002522 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002523}
2524
2525
2526Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002527 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002528 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002529
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002530 Object* result = Failure::OutOfMemoryException();
2531 if (space == NEW_SPACE) {
2532 result = size <= kMaxObjectSizeInNewSpace
2533 ? new_space_.AllocateRaw(size)
2534 : lo_space_->AllocateRawFixedArray(size);
2535 } else {
2536 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2537 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2538 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002539 if (result->IsFailure()) return result;
2540
2541 // Determine the map based on the string's length.
2542 Map* map;
2543 if (length <= String::kMaxShortStringSize) {
2544 map = short_ascii_string_map();
2545 } else if (length <= String::kMaxMediumStringSize) {
2546 map = medium_ascii_string_map();
2547 } else {
2548 map = long_ascii_string_map();
2549 }
2550
2551 // Partially initialize the object.
2552 HeapObject::cast(result)->set_map(map);
2553 String::cast(result)->set_length(length);
2554 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2555 return result;
2556}
2557
2558
2559Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002560 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002561 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002562
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002563 Object* result = Failure::OutOfMemoryException();
2564 if (space == NEW_SPACE) {
2565 result = size <= kMaxObjectSizeInNewSpace
2566 ? new_space_.AllocateRaw(size)
2567 : lo_space_->AllocateRawFixedArray(size);
2568 } else {
2569 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2570 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2571 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002572 if (result->IsFailure()) return result;
2573
2574 // Determine the map based on the string's length.
2575 Map* map;
2576 if (length <= String::kMaxShortStringSize) {
2577 map = short_string_map();
2578 } else if (length <= String::kMaxMediumStringSize) {
2579 map = medium_string_map();
2580 } else {
2581 map = long_string_map();
2582 }
2583
2584 // Partially initialize the object.
2585 HeapObject::cast(result)->set_map(map);
2586 String::cast(result)->set_length(length);
2587 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2588 return result;
2589}
2590
2591
2592Object* Heap::AllocateEmptyFixedArray() {
2593 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002594 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002595 if (result->IsFailure()) return result;
2596 // Initialize the object.
2597 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2598 reinterpret_cast<Array*>(result)->set_length(0);
2599 return result;
2600}
2601
2602
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002603Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002604 // Use the general function if we're forced to always allocate.
2605 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002606 // Allocate the raw data for a fixed array.
2607 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002608 return size <= kMaxObjectSizeInNewSpace
2609 ? new_space_.AllocateRaw(size)
2610 : lo_space_->AllocateRawFixedArray(size);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002611}
2612
2613
2614Object* Heap::CopyFixedArray(FixedArray* src) {
2615 int len = src->length();
2616 Object* obj = AllocateRawFixedArray(len);
2617 if (obj->IsFailure()) return obj;
2618 if (Heap::InNewSpace(obj)) {
2619 HeapObject* dst = HeapObject::cast(obj);
2620 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2621 reinterpret_cast<Object**>(src->address()),
2622 FixedArray::SizeFor(len));
2623 return obj;
2624 }
2625 HeapObject::cast(obj)->set_map(src->map());
2626 FixedArray* result = FixedArray::cast(obj);
2627 result->set_length(len);
2628 // Copy the content
2629 WriteBarrierMode mode = result->GetWriteBarrierMode();
2630 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2631 return result;
2632}
2633
2634
2635Object* Heap::AllocateFixedArray(int length) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002636 ASSERT(length >= 0);
ager@chromium.org32912102009-01-16 10:38:43 +00002637 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002638 Object* result = AllocateRawFixedArray(length);
2639 if (!result->IsFailure()) {
2640 // Initialize header.
2641 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2642 FixedArray* array = FixedArray::cast(result);
2643 array->set_length(length);
2644 Object* value = undefined_value();
2645 // Initialize body.
2646 for (int index = 0; index < length; index++) {
2647 array->set(index, value, SKIP_WRITE_BARRIER);
2648 }
2649 }
2650 return result;
2651}
2652
2653
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002654Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2655 ASSERT(empty_fixed_array()->IsFixedArray());
2656 if (length == 0) return empty_fixed_array();
2657
2658 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002659 Object* result = Failure::OutOfMemoryException();
2660 if (pretenure != TENURED) {
2661 result = size <= kMaxObjectSizeInNewSpace
2662 ? new_space_.AllocateRaw(size)
2663 : lo_space_->AllocateRawFixedArray(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002664 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002665 if (result->IsFailure()) {
2666 if (size > MaxObjectSizeInPagedSpace()) {
2667 result = lo_space_->AllocateRawFixedArray(size);
2668 } else {
2669 AllocationSpace space =
2670 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2671 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
2672 }
2673 if (result->IsFailure()) return result;
2674 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002675 // Initialize the object.
2676 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2677 FixedArray* array = FixedArray::cast(result);
2678 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002679 Object* value = undefined_value();
2680 for (int index = 0; index < length; index++) {
2681 array->set(index, value, SKIP_WRITE_BARRIER);
2682 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002683 return array;
2684}
2685
2686
2687Object* Heap::AllocateFixedArrayWithHoles(int length) {
2688 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002689 Object* result = AllocateRawFixedArray(length);
2690 if (!result->IsFailure()) {
2691 // Initialize header.
2692 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2693 FixedArray* array = FixedArray::cast(result);
2694 array->set_length(length);
2695 // Initialize body.
2696 Object* value = the_hole_value();
2697 for (int index = 0; index < length; index++) {
2698 array->set(index, value, SKIP_WRITE_BARRIER);
2699 }
2700 }
2701 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002702}
2703
2704
2705Object* Heap::AllocateHashTable(int length) {
2706 Object* result = Heap::AllocateFixedArray(length);
2707 if (result->IsFailure()) return result;
2708 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00002709 ASSERT(result->IsHashTable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002710 return result;
2711}
2712
2713
2714Object* Heap::AllocateGlobalContext() {
2715 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2716 if (result->IsFailure()) return result;
2717 Context* context = reinterpret_cast<Context*>(result);
2718 context->set_map(global_context_map());
2719 ASSERT(context->IsGlobalContext());
2720 ASSERT(result->IsContext());
2721 return result;
2722}
2723
2724
2725Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2726 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2727 Object* result = Heap::AllocateFixedArray(length);
2728 if (result->IsFailure()) return result;
2729 Context* context = reinterpret_cast<Context*>(result);
2730 context->set_map(context_map());
2731 context->set_closure(function);
2732 context->set_fcontext(context);
2733 context->set_previous(NULL);
2734 context->set_extension(NULL);
2735 context->set_global(function->context()->global());
2736 ASSERT(!context->IsGlobalContext());
2737 ASSERT(context->is_function_context());
2738 ASSERT(result->IsContext());
2739 return result;
2740}
2741
2742
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002743Object* Heap::AllocateWithContext(Context* previous,
2744 JSObject* extension,
2745 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002746 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2747 if (result->IsFailure()) return result;
2748 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002749 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002750 context->set_closure(previous->closure());
2751 context->set_fcontext(previous->fcontext());
2752 context->set_previous(previous);
2753 context->set_extension(extension);
2754 context->set_global(previous->global());
2755 ASSERT(!context->IsGlobalContext());
2756 ASSERT(!context->is_function_context());
2757 ASSERT(result->IsContext());
2758 return result;
2759}
2760
2761
2762Object* Heap::AllocateStruct(InstanceType type) {
2763 Map* map;
2764 switch (type) {
2765#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2766STRUCT_LIST(MAKE_CASE)
2767#undef MAKE_CASE
2768 default:
2769 UNREACHABLE();
2770 return Failure::InternalError();
2771 }
2772 int size = map->instance_size();
2773 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002774 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002775 Object* result = Heap::Allocate(map, space);
2776 if (result->IsFailure()) return result;
2777 Struct::cast(result)->InitializeBody(size);
2778 return result;
2779}
2780
2781
ager@chromium.org96c75b52009-08-26 09:13:16 +00002782bool Heap::IdleNotification() {
2783 static const int kIdlesBeforeCollection = 7;
2784 static int number_idle_notifications = 0;
2785 static int last_gc_count = gc_count_;
2786
2787 bool finished = false;
2788
2789 if (last_gc_count == gc_count_) {
2790 number_idle_notifications++;
2791 } else {
2792 number_idle_notifications = 0;
2793 last_gc_count = gc_count_;
2794 }
2795
2796 if (number_idle_notifications >= kIdlesBeforeCollection) {
2797 // The first time through we collect without forcing compaction.
2798 // The second time through we force compaction and quit.
2799 bool force_compaction =
2800 number_idle_notifications > kIdlesBeforeCollection;
2801 CollectAllGarbage(force_compaction);
2802 last_gc_count = gc_count_;
2803 if (force_compaction) {
ager@chromium.org439e85a2009-08-26 13:15:29 +00002804 // Shrink new space.
2805 new_space_.Shrink();
ager@chromium.org96c75b52009-08-26 09:13:16 +00002806 number_idle_notifications = 0;
2807 finished = true;
2808 }
2809 }
2810
2811 // Uncommit unused memory in new space.
2812 Heap::UncommitFromSpace();
2813 return finished;
2814}
2815
2816
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002817#ifdef DEBUG
2818
2819void Heap::Print() {
2820 if (!HasBeenSetup()) return;
2821 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002822 AllSpaces spaces;
2823 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002824}
2825
2826
2827void Heap::ReportCodeStatistics(const char* title) {
2828 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2829 PagedSpace::ResetCodeStatistics();
2830 // We do not look for code in new space, map space, or old space. If code
2831 // somehow ends up in those spaces, we would miss it here.
2832 code_space_->CollectCodeStatistics();
2833 lo_space_->CollectCodeStatistics();
2834 PagedSpace::ReportCodeStatistics();
2835}
2836
2837
2838// This function expects that NewSpace's allocated objects histogram is
2839// populated (via a call to CollectStatistics or else as a side effect of a
2840// just-completed scavenge collection).
2841void Heap::ReportHeapStatistics(const char* title) {
2842 USE(title);
2843 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2844 title, gc_count_);
2845 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002846 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2847 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002848
2849 PrintF("\n");
2850 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2851 GlobalHandles::PrintStats();
2852 PrintF("\n");
2853
2854 PrintF("Heap statistics : ");
2855 MemoryAllocator::ReportStatistics();
2856 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002857 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002858 PrintF("Old pointer space : ");
2859 old_pointer_space_->ReportStatistics();
2860 PrintF("Old data space : ");
2861 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002862 PrintF("Code space : ");
2863 code_space_->ReportStatistics();
2864 PrintF("Map space : ");
2865 map_space_->ReportStatistics();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002866 PrintF("Cell space : ");
2867 cell_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002868 PrintF("Large object space : ");
2869 lo_space_->ReportStatistics();
2870 PrintF(">>>>>> ========================================= >>>>>>\n");
2871}
2872
2873#endif // DEBUG
2874
2875bool Heap::Contains(HeapObject* value) {
2876 return Contains(value->address());
2877}
2878
2879
2880bool Heap::Contains(Address addr) {
2881 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2882 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002883 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002884 old_pointer_space_->Contains(addr) ||
2885 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002886 code_space_->Contains(addr) ||
2887 map_space_->Contains(addr) ||
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002888 cell_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002889 lo_space_->SlowContains(addr));
2890}
2891
2892
2893bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2894 return InSpace(value->address(), space);
2895}
2896
2897
2898bool Heap::InSpace(Address addr, AllocationSpace space) {
2899 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2900 if (!HasBeenSetup()) return false;
2901
2902 switch (space) {
2903 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002904 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002905 case OLD_POINTER_SPACE:
2906 return old_pointer_space_->Contains(addr);
2907 case OLD_DATA_SPACE:
2908 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002909 case CODE_SPACE:
2910 return code_space_->Contains(addr);
2911 case MAP_SPACE:
2912 return map_space_->Contains(addr);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002913 case CELL_SPACE:
2914 return cell_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002915 case LO_SPACE:
2916 return lo_space_->SlowContains(addr);
2917 }
2918
2919 return false;
2920}
2921
2922
2923#ifdef DEBUG
2924void Heap::Verify() {
2925 ASSERT(HasBeenSetup());
2926
2927 VerifyPointersVisitor visitor;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002928 IterateRoots(&visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002929
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002930 new_space_.Verify();
2931
2932 VerifyPointersAndRSetVisitor rset_visitor;
2933 old_pointer_space_->Verify(&rset_visitor);
2934 map_space_->Verify(&rset_visitor);
2935
2936 VerifyPointersVisitor no_rset_visitor;
2937 old_data_space_->Verify(&no_rset_visitor);
2938 code_space_->Verify(&no_rset_visitor);
2939 cell_space_->Verify(&no_rset_visitor);
2940
2941 lo_space_->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002942}
2943#endif // DEBUG
2944
2945
2946Object* Heap::LookupSymbol(Vector<const char> string) {
2947 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002948 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002949 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002950 // Can't use set_symbol_table because SymbolTable::cast knows that
2951 // SymbolTable is a singleton and checks for identity.
2952 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002953 ASSERT(symbol != NULL);
2954 return symbol;
2955}
2956
2957
2958Object* Heap::LookupSymbol(String* string) {
2959 if (string->IsSymbol()) return string;
2960 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002961 Object* new_table = symbol_table()->LookupString(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002962 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002963 // Can't use set_symbol_table because SymbolTable::cast knows that
2964 // SymbolTable is a singleton and checks for identity.
2965 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002966 ASSERT(symbol != NULL);
2967 return symbol;
2968}
2969
2970
ager@chromium.org7c537e22008-10-16 08:43:32 +00002971bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2972 if (string->IsSymbol()) {
2973 *symbol = string;
2974 return true;
2975 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002976 return symbol_table()->LookupSymbolIfExists(string, symbol);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002977}
2978
2979
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002980#ifdef DEBUG
2981void Heap::ZapFromSpace() {
2982 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002983 for (Address a = new_space_.FromSpaceLow();
2984 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002985 a += kPointerSize) {
2986 Memory::Address_at(a) = kFromSpaceZapValue;
2987 }
2988}
2989#endif // DEBUG
2990
2991
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002992int Heap::IterateRSetRange(Address object_start,
2993 Address object_end,
2994 Address rset_start,
2995 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002996 Address object_address = object_start;
2997 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002998 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002999
3000 // Loop over all the pointers in [object_start, object_end).
3001 while (object_address < object_end) {
3002 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003003 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003004 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003005 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003006 // Do not dereference pointers at or past object_end.
3007 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3008 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003009 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003010 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3011 }
3012 // If this pointer does not need to be remembered anymore, clear
3013 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003014 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003015 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003016 }
3017 object_address += kPointerSize;
3018 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003019 // Update the remembered set if it has changed.
3020 if (result_rset != rset_word) {
3021 Memory::uint32_at(rset_address) = result_rset;
3022 }
3023 } else {
3024 // No bits in the word were set. This is the common case.
3025 object_address += kPointerSize * kBitsPerInt;
3026 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003027 rset_address += kIntSize;
3028 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003029 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003030}
3031
3032
3033void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3034 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003035 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003036
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003037 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3038 "V8.RSetPaged",
3039 0,
3040 Page::kObjectAreaSize / kPointerSize,
3041 30);
3042
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003043 PageIterator it(space, PageIterator::PAGES_IN_USE);
3044 while (it.has_next()) {
3045 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003046 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3047 page->RSetStart(), copy_object_func);
3048 if (paged_rset_histogram != NULL) {
3049 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3050 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003051 }
3052}
3053
3054
3055#ifdef DEBUG
3056#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
3057#else
3058#define SYNCHRONIZE_TAG(tag)
3059#endif
3060
3061void Heap::IterateRoots(ObjectVisitor* v) {
3062 IterateStrongRoots(v);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003063 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003064 SYNCHRONIZE_TAG("symbol_table");
3065}
3066
3067
3068void Heap::IterateStrongRoots(ObjectVisitor* v) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003069 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003070 SYNCHRONIZE_TAG("strong_root_list");
3071
ager@chromium.org3b45ab52009-03-19 22:21:34 +00003072 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003073 SYNCHRONIZE_TAG("symbol");
3074
3075 Bootstrapper::Iterate(v);
3076 SYNCHRONIZE_TAG("bootstrapper");
3077 Top::Iterate(v);
3078 SYNCHRONIZE_TAG("top");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003079
3080#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003081 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003082#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003083 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003084 CompilationCache::Iterate(v);
3085 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003086
3087 // Iterate over local handles in handle scopes.
3088 HandleScopeImplementer::Iterate(v);
3089 SYNCHRONIZE_TAG("handlescope");
3090
3091 // Iterate over the builtin code objects and code stubs in the heap. Note
3092 // that it is not strictly necessary to iterate over code objects on
3093 // scavenge collections. We still do it here because this same function
3094 // is used by the mark-sweep collector and the deserializer.
3095 Builtins::IterateBuiltins(v);
3096 SYNCHRONIZE_TAG("builtins");
3097
3098 // Iterate over global handles.
3099 GlobalHandles::IterateRoots(v);
3100 SYNCHRONIZE_TAG("globalhandles");
3101
3102 // Iterate over pointers being held by inactive threads.
3103 ThreadManager::Iterate(v);
3104 SYNCHRONIZE_TAG("threadmanager");
3105}
3106#undef SYNCHRONIZE_TAG
3107
3108
3109// Flag is set when the heap has been configured. The heap can be repeatedly
3110// configured through the API until it is setup.
3111static bool heap_configured = false;
3112
3113// TODO(1236194): Since the heap size is configurable on the command line
3114// and through the API, we should gracefully handle the case that the heap
3115// size is not big enough to fit all the initial objects.
3116bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
3117 if (HasBeenSetup()) return false;
3118
3119 if (semispace_size > 0) semispace_size_ = semispace_size;
3120 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
3121
3122 // The new space size must be a power of two to support single-bit testing
3123 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00003124 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003125 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
3126 young_generation_size_ = 2 * semispace_size_;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003127 external_allocation_limit_ = 10 * semispace_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003128
3129 // The old generation is paged.
3130 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
3131
3132 heap_configured = true;
3133 return true;
3134}
3135
3136
kasper.lund7276f142008-07-30 08:49:36 +00003137bool Heap::ConfigureHeapDefault() {
3138 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
3139}
3140
3141
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003142int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003143 return old_pointer_space_->Size()
3144 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003145 + code_space_->Size()
3146 + map_space_->Size()
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003147 + cell_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003148 + lo_space_->Size();
3149}
3150
3151
kasper.lund7276f142008-07-30 08:49:36 +00003152int Heap::PromotedExternalMemorySize() {
3153 if (amount_of_external_allocated_memory_
3154 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3155 return amount_of_external_allocated_memory_
3156 - amount_of_external_allocated_memory_at_last_global_gc_;
3157}
3158
3159
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003160bool Heap::Setup(bool create_heap_objects) {
3161 // Initialize heap spaces and initial maps and objects. Whenever something
3162 // goes wrong, just return false. The caller should check the results and
3163 // call Heap::TearDown() to release allocated memory.
3164 //
3165 // If the heap is not yet configured (eg, through the API), configure it.
3166 // Configuration is based on the flags new-space-size (really the semispace
3167 // size) and old-space-size if set or the initial values of semispace_size_
3168 // and old_generation_size_ otherwise.
3169 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00003170 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003171 }
3172
3173 // Setup memory allocator and allocate an initial chunk of memory. The
3174 // initial chunk is double the size of the new space to ensure that we can
3175 // find a pair of semispaces that are contiguous and aligned to their size.
3176 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
3177 void* chunk
3178 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
3179 if (chunk == NULL) return false;
3180
3181 // Put the initial chunk of the old space at the start of the initial
3182 // chunk, then the two new space semispaces, then the initial chunk of
3183 // code space. Align the pair of semispaces to their size, which must be
3184 // a power of 2.
3185 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003186 Address code_space_start = reinterpret_cast<Address>(chunk);
3187 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
3188 Address old_space_start = new_space_start + young_generation_size_;
3189 int code_space_size = new_space_start - code_space_start;
3190 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003191
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003192 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003193 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003194
3195 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00003196 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003197 old_pointer_space_ =
3198 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
3199 if (old_pointer_space_ == NULL) return false;
3200 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
3201 return false;
3202 }
3203 old_data_space_ =
3204 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
3205 if (old_data_space_ == NULL) return false;
3206 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
3207 old_space_size >> 1)) {
3208 return false;
3209 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003210
3211 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00003212 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003213 code_space_ =
3214 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003215 if (code_space_ == NULL) return false;
3216 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
3217
3218 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00003219 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003220 if (map_space_ == NULL) return false;
3221 // Setting up a paged space without giving it a virtual memory range big
3222 // enough to hold at least a page will cause it to allocate.
3223 if (!map_space_->Setup(NULL, 0)) return false;
3224
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003225 // Initialize global property cell space.
3226 cell_space_ = new CellSpace(old_generation_size_, CELL_SPACE);
3227 if (cell_space_ == NULL) return false;
3228 // Setting up a paged space without giving it a virtual memory range big
3229 // enough to hold at least a page will cause it to allocate.
3230 if (!cell_space_->Setup(NULL, 0)) return false;
3231
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003232 // The large object code space may contain code or data. We set the memory
3233 // to be non-executable here for safety, but this means we need to enable it
3234 // explicitly when allocating large code objects.
3235 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003236 if (lo_space_ == NULL) return false;
3237 if (!lo_space_->Setup()) return false;
3238
3239 if (create_heap_objects) {
3240 // Create initial maps.
3241 if (!CreateInitialMaps()) return false;
3242 if (!CreateApiObjects()) return false;
3243
3244 // Create initial objects
3245 if (!CreateInitialObjects()) return false;
3246 }
3247
3248 LOG(IntEvent("heap-capacity", Capacity()));
3249 LOG(IntEvent("heap-available", Available()));
3250
3251 return true;
3252}
3253
3254
3255void Heap::TearDown() {
3256 GlobalHandles::TearDown();
3257
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003258 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003259
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003260 if (old_pointer_space_ != NULL) {
3261 old_pointer_space_->TearDown();
3262 delete old_pointer_space_;
3263 old_pointer_space_ = NULL;
3264 }
3265
3266 if (old_data_space_ != NULL) {
3267 old_data_space_->TearDown();
3268 delete old_data_space_;
3269 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003270 }
3271
3272 if (code_space_ != NULL) {
3273 code_space_->TearDown();
3274 delete code_space_;
3275 code_space_ = NULL;
3276 }
3277
3278 if (map_space_ != NULL) {
3279 map_space_->TearDown();
3280 delete map_space_;
3281 map_space_ = NULL;
3282 }
3283
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003284 if (cell_space_ != NULL) {
3285 cell_space_->TearDown();
3286 delete cell_space_;
3287 cell_space_ = NULL;
3288 }
3289
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003290 if (lo_space_ != NULL) {
3291 lo_space_->TearDown();
3292 delete lo_space_;
3293 lo_space_ = NULL;
3294 }
3295
3296 MemoryAllocator::TearDown();
3297}
3298
3299
3300void Heap::Shrink() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003301 // Try to shrink all paged spaces.
3302 PagedSpaces spaces;
3303 while (PagedSpace* space = spaces.next()) space->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003304}
3305
3306
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003307#ifdef ENABLE_HEAP_PROTECTION
3308
3309void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003310 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003311 AllSpaces spaces;
3312 while (Space* space = spaces.next()) space->Protect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003313 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003314}
3315
3316
3317void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003318 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003319 AllSpaces spaces;
3320 while (Space* space = spaces.next()) space->Unprotect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003321 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003322}
3323
3324#endif
3325
3326
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003327#ifdef DEBUG
3328
3329class PrintHandleVisitor: public ObjectVisitor {
3330 public:
3331 void VisitPointers(Object** start, Object** end) {
3332 for (Object** p = start; p < end; p++)
3333 PrintF(" handle %p to %p\n", p, *p);
3334 }
3335};
3336
3337void Heap::PrintHandles() {
3338 PrintF("Handles:\n");
3339 PrintHandleVisitor v;
3340 HandleScopeImplementer::Iterate(&v);
3341}
3342
3343#endif
3344
3345
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003346Space* AllSpaces::next() {
3347 switch (counter_++) {
3348 case NEW_SPACE:
3349 return Heap::new_space();
3350 case OLD_POINTER_SPACE:
3351 return Heap::old_pointer_space();
3352 case OLD_DATA_SPACE:
3353 return Heap::old_data_space();
3354 case CODE_SPACE:
3355 return Heap::code_space();
3356 case MAP_SPACE:
3357 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003358 case CELL_SPACE:
3359 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003360 case LO_SPACE:
3361 return Heap::lo_space();
3362 default:
3363 return NULL;
3364 }
3365}
3366
3367
3368PagedSpace* PagedSpaces::next() {
3369 switch (counter_++) {
3370 case OLD_POINTER_SPACE:
3371 return Heap::old_pointer_space();
3372 case OLD_DATA_SPACE:
3373 return Heap::old_data_space();
3374 case CODE_SPACE:
3375 return Heap::code_space();
3376 case MAP_SPACE:
3377 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003378 case CELL_SPACE:
3379 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003380 default:
3381 return NULL;
3382 }
3383}
3384
3385
3386
3387OldSpace* OldSpaces::next() {
3388 switch (counter_++) {
3389 case OLD_POINTER_SPACE:
3390 return Heap::old_pointer_space();
3391 case OLD_DATA_SPACE:
3392 return Heap::old_data_space();
3393 case CODE_SPACE:
3394 return Heap::code_space();
3395 default:
3396 return NULL;
3397 }
3398}
3399
3400
kasper.lund7276f142008-07-30 08:49:36 +00003401SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3402}
3403
3404
3405SpaceIterator::~SpaceIterator() {
3406 // Delete active iterator if any.
3407 delete iterator_;
3408}
3409
3410
3411bool SpaceIterator::has_next() {
3412 // Iterate until no more spaces.
3413 return current_space_ != LAST_SPACE;
3414}
3415
3416
3417ObjectIterator* SpaceIterator::next() {
3418 if (iterator_ != NULL) {
3419 delete iterator_;
3420 iterator_ = NULL;
3421 // Move to the next space
3422 current_space_++;
3423 if (current_space_ > LAST_SPACE) {
3424 return NULL;
3425 }
3426 }
3427
3428 // Return iterator for the new current space.
3429 return CreateIterator();
3430}
3431
3432
3433// Create an iterator for the space to iterate.
3434ObjectIterator* SpaceIterator::CreateIterator() {
3435 ASSERT(iterator_ == NULL);
3436
3437 switch (current_space_) {
3438 case NEW_SPACE:
3439 iterator_ = new SemiSpaceIterator(Heap::new_space());
3440 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003441 case OLD_POINTER_SPACE:
3442 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3443 break;
3444 case OLD_DATA_SPACE:
3445 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003446 break;
3447 case CODE_SPACE:
3448 iterator_ = new HeapObjectIterator(Heap::code_space());
3449 break;
3450 case MAP_SPACE:
3451 iterator_ = new HeapObjectIterator(Heap::map_space());
3452 break;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003453 case CELL_SPACE:
3454 iterator_ = new HeapObjectIterator(Heap::cell_space());
3455 break;
kasper.lund7276f142008-07-30 08:49:36 +00003456 case LO_SPACE:
3457 iterator_ = new LargeObjectIterator(Heap::lo_space());
3458 break;
3459 }
3460
3461 // Return the newly allocated iterator;
3462 ASSERT(iterator_ != NULL);
3463 return iterator_;
3464}
3465
3466
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003467HeapIterator::HeapIterator() {
3468 Init();
3469}
3470
3471
3472HeapIterator::~HeapIterator() {
3473 Shutdown();
3474}
3475
3476
3477void HeapIterator::Init() {
3478 // Start the iteration.
3479 space_iterator_ = new SpaceIterator();
3480 object_iterator_ = space_iterator_->next();
3481}
3482
3483
3484void HeapIterator::Shutdown() {
3485 // Make sure the last iterator is deallocated.
3486 delete space_iterator_;
3487 space_iterator_ = NULL;
3488 object_iterator_ = NULL;
3489}
3490
3491
3492bool HeapIterator::has_next() {
3493 // No iterator means we are done.
3494 if (object_iterator_ == NULL) return false;
3495
3496 if (object_iterator_->has_next_object()) {
3497 // If the current iterator has more objects we are fine.
3498 return true;
3499 } else {
3500 // Go though the spaces looking for one that has objects.
3501 while (space_iterator_->has_next()) {
3502 object_iterator_ = space_iterator_->next();
3503 if (object_iterator_->has_next_object()) {
3504 return true;
3505 }
3506 }
3507 }
3508 // Done with the last space.
3509 object_iterator_ = NULL;
3510 return false;
3511}
3512
3513
3514HeapObject* HeapIterator::next() {
3515 if (has_next()) {
3516 return object_iterator_->next_object();
3517 } else {
3518 return NULL;
3519 }
3520}
3521
3522
3523void HeapIterator::reset() {
3524 // Restart the iterator.
3525 Shutdown();
3526 Init();
3527}
3528
3529
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003530#ifdef ENABLE_LOGGING_AND_PROFILING
3531namespace {
3532
3533// JSConstructorProfile is responsible for gathering and logging
3534// "constructor profile" of JS object allocated on heap.
3535// It is run during garbage collection cycle, thus it doesn't need
3536// to use handles.
3537class JSConstructorProfile BASE_EMBEDDED {
3538 public:
3539 JSConstructorProfile() : zscope_(DELETE_ON_EXIT) {}
3540 void CollectStats(JSObject* obj);
3541 void PrintStats();
3542 // Used by ZoneSplayTree::ForEach.
3543 void Call(String* name, const NumberAndSizeInfo& number_and_size);
3544 private:
3545 struct TreeConfig {
3546 typedef String* Key;
3547 typedef NumberAndSizeInfo Value;
3548 static const Key kNoKey;
3549 static const Value kNoValue;
3550 // Strings are unique, so it is sufficient to compare their pointers.
3551 static int Compare(const Key& a, const Key& b) {
3552 return a == b ? 0 : (a < b ? -1 : 1);
3553 }
3554 };
3555
3556 typedef ZoneSplayTree<TreeConfig> JSObjectsInfoTree;
3557 static int CalculateJSObjectNetworkSize(JSObject* obj);
3558
3559 ZoneScope zscope_;
3560 JSObjectsInfoTree js_objects_info_tree_;
3561};
3562
3563const JSConstructorProfile::TreeConfig::Key
3564 JSConstructorProfile::TreeConfig::kNoKey = NULL;
3565const JSConstructorProfile::TreeConfig::Value
3566 JSConstructorProfile::TreeConfig::kNoValue;
3567
3568
3569int JSConstructorProfile::CalculateJSObjectNetworkSize(JSObject* obj) {
3570 int size = obj->Size();
3571 // If 'properties' and 'elements' are non-empty (thus, non-shared),
3572 // take their size into account.
3573 if (FixedArray::cast(obj->properties())->length() != 0) {
3574 size += obj->properties()->Size();
3575 }
3576 if (FixedArray::cast(obj->elements())->length() != 0) {
3577 size += obj->elements()->Size();
3578 }
3579 return size;
3580}
3581
3582
3583void JSConstructorProfile::Call(String* name,
3584 const NumberAndSizeInfo& number_and_size) {
3585 SmartPointer<char> s_name;
3586 if (name != NULL) {
3587 s_name = name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
3588 }
3589 LOG(HeapSampleJSConstructorEvent(*s_name,
3590 number_and_size.number(),
3591 number_and_size.bytes()));
3592}
3593
3594
3595void JSConstructorProfile::CollectStats(JSObject* obj) {
3596 String* constructor_func = NULL;
3597 if (obj->map()->constructor()->IsJSFunction()) {
3598 JSFunction* constructor = JSFunction::cast(obj->map()->constructor());
3599 SharedFunctionInfo* sfi = constructor->shared();
3600 String* name = String::cast(sfi->name());
3601 constructor_func = name->length() > 0 ? name : sfi->inferred_name();
3602 } else if (obj->IsJSFunction()) {
3603 constructor_func = Heap::function_class_symbol();
3604 }
3605 JSObjectsInfoTree::Locator loc;
3606 if (!js_objects_info_tree_.Find(constructor_func, &loc)) {
3607 js_objects_info_tree_.Insert(constructor_func, &loc);
3608 }
3609 NumberAndSizeInfo number_and_size = loc.value();
3610 number_and_size.increment_number(1);
3611 number_and_size.increment_bytes(CalculateJSObjectNetworkSize(obj));
3612 loc.set_value(number_and_size);
3613}
3614
3615
3616void JSConstructorProfile::PrintStats() {
3617 js_objects_info_tree_.ForEach(this);
3618}
3619
3620} // namespace
3621#endif
3622
3623
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003624//
3625// HeapProfiler class implementation.
3626//
3627#ifdef ENABLE_LOGGING_AND_PROFILING
3628void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3629 InstanceType type = obj->map()->instance_type();
3630 ASSERT(0 <= type && type <= LAST_TYPE);
3631 info[type].increment_number(1);
3632 info[type].increment_bytes(obj->Size());
3633}
3634#endif
3635
3636
3637#ifdef ENABLE_LOGGING_AND_PROFILING
3638void HeapProfiler::WriteSample() {
3639 LOG(HeapSampleBeginEvent("Heap", "allocated"));
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003640 LOG(HeapSampleStats(
3641 "Heap", "allocated", Heap::Capacity(), Heap::SizeOfObjects()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003642
3643 HistogramInfo info[LAST_TYPE+1];
3644#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3645 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3646#undef DEF_TYPE_NAME
3647
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003648 JSConstructorProfile js_cons_profile;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003649 HeapIterator iterator;
3650 while (iterator.has_next()) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003651 HeapObject* obj = iterator.next();
3652 CollectStats(obj, info);
3653 if (obj->IsJSObject()) {
3654 js_cons_profile.CollectStats(JSObject::cast(obj));
3655 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003656 }
3657
3658 // Lump all the string types together.
3659 int string_number = 0;
3660 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003661#define INCREMENT_SIZE(type, size, name, camel_name) \
3662 string_number += info[type].number(); \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003663 string_bytes += info[type].bytes();
3664 STRING_TYPE_LIST(INCREMENT_SIZE)
3665#undef INCREMENT_SIZE
3666 if (string_bytes > 0) {
3667 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3668 }
3669
3670 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3671 if (info[i].bytes() > 0) {
3672 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3673 info[i].bytes()));
3674 }
3675 }
3676
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00003677 js_cons_profile.PrintStats();
3678
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003679 LOG(HeapSampleEndEvent("Heap", "allocated"));
3680}
3681
3682
3683#endif
3684
3685
3686
3687#ifdef DEBUG
3688
3689static bool search_for_any_global;
3690static Object* search_target;
3691static bool found_target;
3692static List<Object*> object_stack(20);
3693
3694
3695// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3696static const int kMarkTag = 2;
3697
3698static void MarkObjectRecursively(Object** p);
3699class MarkObjectVisitor : public ObjectVisitor {
3700 public:
3701 void VisitPointers(Object** start, Object** end) {
3702 // Copy all HeapObject pointers in [start, end)
3703 for (Object** p = start; p < end; p++) {
3704 if ((*p)->IsHeapObject())
3705 MarkObjectRecursively(p);
3706 }
3707 }
3708};
3709
3710static MarkObjectVisitor mark_visitor;
3711
3712static void MarkObjectRecursively(Object** p) {
3713 if (!(*p)->IsHeapObject()) return;
3714
3715 HeapObject* obj = HeapObject::cast(*p);
3716
3717 Object* map = obj->map();
3718
3719 if (!map->IsHeapObject()) return; // visited before
3720
3721 if (found_target) return; // stop if target found
3722 object_stack.Add(obj);
3723 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3724 (!search_for_any_global && (obj == search_target))) {
3725 found_target = true;
3726 return;
3727 }
3728
3729 if (obj->IsCode()) {
3730 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3731 }
3732
3733 // not visited yet
3734 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3735
3736 Address map_addr = map_p->address();
3737
3738 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3739
3740 MarkObjectRecursively(&map);
3741
3742 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3743 &mark_visitor);
3744
3745 if (!found_target) // don't pop if found the target
3746 object_stack.RemoveLast();
3747}
3748
3749
3750static void UnmarkObjectRecursively(Object** p);
3751class UnmarkObjectVisitor : public ObjectVisitor {
3752 public:
3753 void VisitPointers(Object** start, Object** end) {
3754 // Copy all HeapObject pointers in [start, end)
3755 for (Object** p = start; p < end; p++) {
3756 if ((*p)->IsHeapObject())
3757 UnmarkObjectRecursively(p);
3758 }
3759 }
3760};
3761
3762static UnmarkObjectVisitor unmark_visitor;
3763
3764static void UnmarkObjectRecursively(Object** p) {
3765 if (!(*p)->IsHeapObject()) return;
3766
3767 HeapObject* obj = HeapObject::cast(*p);
3768
3769 Object* map = obj->map();
3770
3771 if (map->IsHeapObject()) return; // unmarked already
3772
3773 Address map_addr = reinterpret_cast<Address>(map);
3774
3775 map_addr -= kMarkTag;
3776
3777 ASSERT_TAG_ALIGNED(map_addr);
3778
3779 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3780
3781 obj->set_map(reinterpret_cast<Map*>(map_p));
3782
3783 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3784
3785 obj->IterateBody(Map::cast(map_p)->instance_type(),
3786 obj->SizeFromMap(Map::cast(map_p)),
3787 &unmark_visitor);
3788
3789 if (obj->IsCode()) {
3790 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3791 }
3792}
3793
3794
3795static void MarkRootObjectRecursively(Object** root) {
3796 if (search_for_any_global) {
3797 ASSERT(search_target == NULL);
3798 } else {
3799 ASSERT(search_target->IsHeapObject());
3800 }
3801 found_target = false;
3802 object_stack.Clear();
3803
3804 MarkObjectRecursively(root);
3805 UnmarkObjectRecursively(root);
3806
3807 if (found_target) {
3808 PrintF("=====================================\n");
3809 PrintF("==== Path to object ====\n");
3810 PrintF("=====================================\n\n");
3811
3812 ASSERT(!object_stack.is_empty());
3813 for (int i = 0; i < object_stack.length(); i++) {
3814 if (i > 0) PrintF("\n |\n |\n V\n\n");
3815 Object* obj = object_stack[i];
3816 obj->Print();
3817 }
3818 PrintF("=====================================\n");
3819 }
3820}
3821
3822
3823// Helper class for visiting HeapObjects recursively.
3824class MarkRootVisitor: public ObjectVisitor {
3825 public:
3826 void VisitPointers(Object** start, Object** end) {
3827 // Visit all HeapObject pointers in [start, end)
3828 for (Object** p = start; p < end; p++) {
3829 if ((*p)->IsHeapObject())
3830 MarkRootObjectRecursively(p);
3831 }
3832 }
3833};
3834
3835
3836// Triggers a depth-first traversal of reachable objects from roots
3837// and finds a path to a specific heap object and prints it.
3838void Heap::TracePathToObject() {
3839 search_target = NULL;
3840 search_for_any_global = false;
3841
3842 MarkRootVisitor root_visitor;
3843 IterateRoots(&root_visitor);
3844}
3845
3846
3847// Triggers a depth-first traversal of reachable objects from roots
3848// and finds a path to any global object and prints it. Useful for
3849// determining the source for leaks of global objects.
3850void Heap::TracePathToGlobal() {
3851 search_target = NULL;
3852 search_for_any_global = true;
3853
3854 MarkRootVisitor root_visitor;
3855 IterateRoots(&root_visitor);
3856}
3857#endif
3858
3859
kasper.lund7276f142008-07-30 08:49:36 +00003860GCTracer::GCTracer()
3861 : start_time_(0.0),
3862 start_size_(0.0),
3863 gc_count_(0),
3864 full_gc_count_(0),
3865 is_compacting_(false),
3866 marked_count_(0) {
3867 // These two fields reflect the state of the previous full collection.
3868 // Set them before they are changed by the collector.
3869 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3870 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3871 if (!FLAG_trace_gc) return;
3872 start_time_ = OS::TimeCurrentMillis();
3873 start_size_ = SizeOfHeapObjects();
3874}
3875
3876
3877GCTracer::~GCTracer() {
3878 if (!FLAG_trace_gc) return;
3879 // Printf ONE line iff flag is set.
3880 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3881 CollectorString(),
3882 start_size_, SizeOfHeapObjects(),
3883 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
kasperl@chromium.orge959c182009-07-27 08:59:04 +00003884
3885#if defined(ENABLE_LOGGING_AND_PROFILING)
3886 Heap::PrintShortHeapStatistics();
3887#endif
kasper.lund7276f142008-07-30 08:49:36 +00003888}
3889
3890
3891const char* GCTracer::CollectorString() {
3892 switch (collector_) {
3893 case SCAVENGER:
3894 return "Scavenge";
3895 case MARK_COMPACTOR:
3896 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3897 : "Mark-sweep";
3898 }
3899 return "Unknown GC";
3900}
3901
3902
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003903int KeyedLookupCache::Hash(Map* map, String* name) {
3904 // Uses only lower 32 bits if pointers are larger.
3905 uintptr_t addr_hash =
3906 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
3907 return (addr_hash ^ name->Hash()) % kLength;
3908}
3909
3910
3911int KeyedLookupCache::Lookup(Map* map, String* name) {
3912 int index = Hash(map, name);
3913 Key& key = keys_[index];
3914 if ((key.map == map) && key.name->Equals(name)) {
3915 return field_offsets_[index];
3916 }
3917 return -1;
3918}
3919
3920
3921void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
3922 String* symbol;
3923 if (Heap::LookupSymbolIfExists(name, &symbol)) {
3924 int index = Hash(map, symbol);
3925 Key& key = keys_[index];
3926 key.map = map;
3927 key.name = symbol;
3928 field_offsets_[index] = field_offset;
3929 }
3930}
3931
3932
3933void KeyedLookupCache::Clear() {
3934 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
3935}
3936
3937
3938KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
3939
3940
3941int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
3942
3943
3944void DescriptorLookupCache::Clear() {
3945 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
3946}
3947
3948
3949DescriptorLookupCache::Key
3950DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
3951
3952int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
3953
3954
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003955#ifdef DEBUG
3956bool Heap::GarbageCollectionGreedyCheck() {
3957 ASSERT(FLAG_gc_greedy);
3958 if (Bootstrapper::IsActive()) return true;
3959 if (disallow_allocation_failure()) return true;
3960 return CollectGarbage(0, NEW_SPACE);
3961}
3962#endif
3963
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003964} } // namespace v8::internal