blob: 0af3d90efa3b98344ff91bf11443336b206d5b4d [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.org2abc4502009-07-02 07:00:29 +000072#if V8_TARGET_ARCH_ARM
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;
76#else
77int Heap::semispace_size_ = 8*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078int Heap::old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000079int Heap::initial_semispace_size_ = 512*KB;
80#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081
82GCCallback Heap::global_gc_prologue_callback_ = NULL;
83GCCallback Heap::global_gc_epilogue_callback_ = NULL;
84
85// Variables set based on semispace_size_ and old_generation_size_ in
86// ConfigureHeap.
87int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
88
ager@chromium.orgeadaf222009-06-16 09:43:10 +000089int Heap::survived_since_last_expansion_ = 0;
90
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000091Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
92
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000093int Heap::mc_count_ = 0;
94int Heap::gc_count_ = 0;
95
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000096int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +000097bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000098
kasper.lund7276f142008-07-30 08:49:36 +000099#ifdef DEBUG
100bool Heap::allocation_allowed_ = true;
101
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000102int Heap::allocation_timeout_ = 0;
103bool Heap::disallow_allocation_failure_ = false;
104#endif // DEBUG
105
106
107int Heap::Capacity() {
108 if (!HasBeenSetup()) return 0;
109
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000110 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000111 old_pointer_space_->Capacity() +
112 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000113 code_space_->Capacity() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000114 map_space_->Capacity() +
115 cell_space_->Capacity();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000116}
117
118
119int Heap::Available() {
120 if (!HasBeenSetup()) return 0;
121
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000122 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000123 old_pointer_space_->Available() +
124 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000125 code_space_->Available() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000126 map_space_->Available() +
127 cell_space_->Available();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128}
129
130
131bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000132 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000133 old_data_space_ != NULL &&
134 code_space_ != NULL &&
135 map_space_ != NULL &&
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000136 cell_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000137 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000138}
139
140
141GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
142 // Is global GC requested?
143 if (space != NEW_SPACE || FLAG_gc_global) {
144 Counters::gc_compactor_caused_by_request.Increment();
145 return MARK_COMPACTOR;
146 }
147
148 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000149 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000150 Counters::gc_compactor_caused_by_promoted_data.Increment();
151 return MARK_COMPACTOR;
152 }
153
154 // Have allocation in OLD and LO failed?
155 if (old_gen_exhausted_) {
156 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
157 return MARK_COMPACTOR;
158 }
159
160 // Is there enough space left in OLD to guarantee that a scavenge can
161 // succeed?
162 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000163 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000164 // for object promotion. It counts only the bytes that the memory
165 // allocator has not yet allocated from the OS and assigned to any space,
166 // and does not count available bytes already in the old space or code
167 // space. Undercounting is safe---we may get an unrequested full GC when
168 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000169 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000170 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
171 return MARK_COMPACTOR;
172 }
173
174 // Default
175 return SCAVENGER;
176}
177
178
179// TODO(1238405): Combine the infrastructure for --heap-stats and
180// --log-gc to avoid the complicated preprocessor and flag testing.
181#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
182void Heap::ReportStatisticsBeforeGC() {
183 // Heap::ReportHeapStatistics will also log NewSpace statistics when
184 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
185 // following logic is used to avoid double logging.
186#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000187 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000188 if (FLAG_heap_stats) {
189 ReportHeapStatistics("Before GC");
190 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000191 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000192 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000193 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000194#elif defined(DEBUG)
195 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000196 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000197 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000198 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199 }
200#elif defined(ENABLE_LOGGING_AND_PROFILING)
201 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000202 new_space_.CollectStatistics();
203 new_space_.ReportStatistics();
204 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000205 }
206#endif
207}
208
209
210// TODO(1238405): Combine the infrastructure for --heap-stats and
211// --log-gc to avoid the complicated preprocessor and flag testing.
212void Heap::ReportStatisticsAfterGC() {
213 // Similar to the before GC, we use some complicated logic to ensure that
214 // NewSpace statistics are logged exactly once when --log-gc is turned on.
215#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
216 if (FLAG_heap_stats) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000217 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000218 ReportHeapStatistics("After GC");
219 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000220 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000221 }
222#elif defined(DEBUG)
223 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
224#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000225 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000226#endif
227}
228#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
229
230
231void Heap::GarbageCollectionPrologue() {
kasper.lund7276f142008-07-30 08:49:36 +0000232 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000233#ifdef DEBUG
234 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
235 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000236
237 if (FLAG_verify_heap) {
238 Verify();
239 }
240
241 if (FLAG_gc_verbose) Print();
242
243 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000244 // Not all spaces have remembered set bits that we care about.
245 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000246 map_space_->PrintRSet();
247 lo_space_->PrintRSet();
248 }
249#endif
250
251#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
252 ReportStatisticsBeforeGC();
253#endif
254}
255
256int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000257 int total = 0;
258 AllSpaces spaces;
259 while (Space* space = spaces.next()) total += space->Size();
260 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261}
262
263void Heap::GarbageCollectionEpilogue() {
264#ifdef DEBUG
265 allow_allocation(true);
266 ZapFromSpace();
267
268 if (FLAG_verify_heap) {
269 Verify();
270 }
271
272 if (FLAG_print_global_handles) GlobalHandles::Print();
273 if (FLAG_print_handles) PrintHandles();
274 if (FLAG_gc_verbose) Print();
275 if (FLAG_code_stats) ReportCodeStatistics("After GC");
276#endif
277
278 Counters::alive_after_last_gc.Set(SizeOfObjects());
279
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000280 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
281 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
283 ReportStatisticsAfterGC();
284#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000285#ifdef ENABLE_DEBUGGER_SUPPORT
286 Debug::AfterGarbageCollection();
287#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000288}
289
290
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000291void Heap::CollectAllGarbage() {
292 // Since we are ignoring the return value, the exact choice of space does
293 // not matter, so long as we do not specify NEW_SPACE, which would not
294 // cause a full GC.
295 CollectGarbage(0, OLD_POINTER_SPACE);
296}
297
298
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000299void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000300 // If the garbage collector interface is exposed through the global
301 // gc() function, we avoid being clever about forcing GCs when
302 // contexts are disposed and leave it to the embedder to make
303 // informed decisions about when to force a collection.
304 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000305 HistogramTimerScope scope(&Counters::gc_context);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000306 CollectAllGarbage();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000307 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000308 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000309}
310
311
312void Heap::NotifyContextDisposed() {
313 context_disposed_pending_ = true;
314}
315
316
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
318 // The VM is in the GC state until exiting this function.
319 VMState state(GC);
320
321#ifdef DEBUG
322 // Reset the allocation timeout to the GC interval, but make sure to
323 // allow at least a few allocations after a collection. The reason
324 // for this is that we have a lot of allocation sequences and we
325 // assume that a garbage collection will allow the subsequent
326 // allocation attempts to go through.
327 allocation_timeout_ = Max(6, FLAG_gc_interval);
328#endif
329
330 { GCTracer tracer;
331 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000332 // The GC count was incremented in the prologue. Tell the tracer about
333 // it.
334 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335
336 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000337 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 tracer.set_collector(collector);
339
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000340 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 ? &Counters::gc_scavenger
342 : &Counters::gc_compactor;
343 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000344 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000345 rate->Stop();
346
347 GarbageCollectionEpilogue();
348 }
349
350
351#ifdef ENABLE_LOGGING_AND_PROFILING
352 if (FLAG_log_gc) HeapProfiler::WriteSample();
353#endif
354
355 switch (space) {
356 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000357 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000358 case OLD_POINTER_SPACE:
359 return old_pointer_space_->Available() >= requested_size;
360 case OLD_DATA_SPACE:
361 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000362 case CODE_SPACE:
363 return code_space_->Available() >= requested_size;
364 case MAP_SPACE:
365 return map_space_->Available() >= requested_size;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000366 case CELL_SPACE:
367 return cell_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368 case LO_SPACE:
369 return lo_space_->Available() >= requested_size;
370 }
371 return false;
372}
373
374
kasper.lund7276f142008-07-30 08:49:36 +0000375void Heap::PerformScavenge() {
376 GCTracer tracer;
377 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
378}
379
380
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000381#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000382// Helper class for verifying the symbol table.
383class SymbolTableVerifier : public ObjectVisitor {
384 public:
385 SymbolTableVerifier() { }
386 void VisitPointers(Object** start, Object** end) {
387 // Visit all HeapObject pointers in [start, end).
388 for (Object** p = start; p < end; p++) {
389 if ((*p)->IsHeapObject()) {
390 // Check that the symbol is actually a symbol.
391 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000392 }
393 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000394 }
395};
396#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000397
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000398
399static void VerifySymbolTable() {
400#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000401 SymbolTableVerifier verifier;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000402 Heap::symbol_table()->IterateElements(&verifier);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000403#endif // DEBUG
404}
405
406
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000407void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000408 GarbageCollector collector,
409 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000410 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
412 ASSERT(!allocation_allowed_);
413 global_gc_prologue_callback_();
414 }
415
416 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000417 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000419 int old_gen_size = PromotedSpaceSize();
420 old_gen_promotion_limit_ =
421 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
422 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000423 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000424 old_gen_exhausted_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000425 }
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000426 Scavenge();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000427 Counters::objs_since_last_young.Set(0);
428
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000429 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000430
kasper.lund7276f142008-07-30 08:49:36 +0000431 if (collector == MARK_COMPACTOR) {
432 // Register the amount of external allocated memory.
433 amount_of_external_allocated_memory_at_last_global_gc_ =
434 amount_of_external_allocated_memory_;
435 }
436
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000437 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
438 ASSERT(!allocation_allowed_);
439 global_gc_epilogue_callback_();
440 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000441 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000442}
443
444
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000445void Heap::PostGarbageCollectionProcessing() {
446 // Process weak handles post gc.
447 GlobalHandles::PostGarbageCollectionProcessing();
448 // Update flat string readers.
449 FlatStringReader::PostGarbageCollectionProcessing();
450}
451
452
kasper.lund7276f142008-07-30 08:49:36 +0000453void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000454 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000455 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000456 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000457 LOG(ResourceEvent("markcompact", "begin"));
458
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000459 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000460
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000461 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000462
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000463 MarkCompactPrologue(is_compacting);
464
465 MarkCompactCollector::CollectGarbage();
466
467 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468
469 LOG(ResourceEvent("markcompact", "end"));
470
471 gc_state_ = NOT_IN_GC;
472
473 Shrink();
474
475 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000476 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477}
478
479
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000480void Heap::MarkCompactPrologue(bool is_compacting) {
481 // At any old GC clear the keyed lookup cache to enable collection of unused
482 // maps.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000483 KeyedLookupCache::Clear();
484 ContextSlotCache::Clear();
485 DescriptorLookupCache::Clear();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000486
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000487 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000488
489 Top::MarkCompactPrologue(is_compacting);
490 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000491}
492
493
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000494void Heap::MarkCompactEpilogue(bool is_compacting) {
495 Top::MarkCompactEpilogue(is_compacting);
496 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000497}
498
499
500Object* Heap::FindCodeObject(Address a) {
501 Object* obj = code_space_->FindObject(a);
502 if (obj->IsFailure()) {
503 obj = lo_space_->FindObject(a);
504 }
kasper.lund7276f142008-07-30 08:49:36 +0000505 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506 return obj;
507}
508
509
510// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000511class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512 public:
513
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000514 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515
516 void VisitPointers(Object** start, Object** end) {
517 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000518 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000519 }
520
521 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000522 void ScavengePointer(Object** p) {
523 Object* object = *p;
524 if (!Heap::InNewSpace(object)) return;
525 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
526 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000527 }
528};
529
530
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000531// A queue of pointers and maps of to-be-promoted objects during a
532// scavenge collection.
533class PromotionQueue {
534 public:
535 void Initialize(Address start_address) {
536 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
537 }
538
539 bool is_empty() { return front_ <= rear_; }
540
541 void insert(HeapObject* object, Map* map) {
542 *(--rear_) = object;
543 *(--rear_) = map;
544 // Assert no overflow into live objects.
545 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
546 }
547
548 void remove(HeapObject** object, Map** map) {
549 *object = *(--front_);
550 *map = Map::cast(*(--front_));
551 // Assert no underflow.
552 ASSERT(front_ >= rear_);
553 }
554
555 private:
556 // The front of the queue is higher in memory than the rear.
557 HeapObject** front_;
558 HeapObject** rear_;
559};
560
561
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000562// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000563static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000564
565
566#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000567// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000569class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570 public:
571 void VisitPointers(Object** start, Object**end) {
572 for (Object** current = start; current < end; current++) {
573 if ((*current)->IsHeapObject()) {
574 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
575 }
576 }
577 }
578};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000579
580
581static void VerifyNonPointerSpacePointers() {
582 // Verify that there are no pointers to new space in spaces where we
583 // do not expect them.
584 VerifyNonPointerSpacePointersVisitor v;
585 HeapObjectIterator code_it(Heap::code_space());
586 while (code_it.has_next()) {
587 HeapObject* object = code_it.next();
588 if (object->IsCode()) {
589 Code::cast(object)->ConvertICTargetsFromAddressToObject();
590 object->Iterate(&v);
591 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
592 } else {
593 // If we find non-code objects in code space (e.g., free list
594 // nodes) we want to verify them as well.
595 object->Iterate(&v);
596 }
597 }
598
599 HeapObjectIterator data_it(Heap::old_data_space());
600 while (data_it.has_next()) data_it.next()->Iterate(&v);
601}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000602#endif
603
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000604
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000605void Heap::Scavenge() {
606#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000607 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000608#endif
609
610 gc_state_ = SCAVENGE;
611
612 // Implements Cheney's copying algorithm
613 LOG(ResourceEvent("scavenge", "begin"));
614
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000615 // Clear descriptor cache.
616 DescriptorLookupCache::Clear();
617
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000618 // Used for updating survived_since_last_expansion_ at function end.
619 int survived_watermark = PromotedSpaceSize();
620
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000621 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000622 survived_since_last_expansion_ > new_space_.Capacity()) {
623 // Double the size of new space if there is room to grow and enough
624 // data has survived scavenge since the last expansion.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625 // TODO(1240712): NewSpace::Double has a return value which is
626 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000627 new_space_.Double();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000628 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000629 }
630
631 // Flip the semispaces. After flipping, to space is empty, from space has
632 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000633 new_space_.Flip();
634 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000635
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000636 // We need to sweep newly copied objects which can be either in the
637 // to space or promoted to the old generation. For to-space
638 // objects, we treat the bottom of the to space as a queue. Newly
639 // copied and unswept objects lie between a 'front' mark and the
640 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000641 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000642 // Promoted objects can go into various old-generation spaces, and
643 // can be allocated internally in the spaces (from the free list).
644 // We treat the top of the to space as a queue of addresses of
645 // promoted objects. The addresses of newly promoted and unswept
646 // objects lie between a 'front' mark and a 'rear' mark that is
647 // updated as a side effect of promoting an object.
648 //
649 // There is guaranteed to be enough room at the top of the to space
650 // for the addresses of promoted objects: every object promoted
651 // frees up its size in bytes from the top of the new space, and
652 // objects are at least one pointer in size.
653 Address new_space_front = new_space_.ToSpaceLow();
654 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000655
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000656 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000657 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000658 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000659
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000660 // Copy objects reachable from weak pointers.
661 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
662
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000663#ifdef V8_HOST_ARCH_64_BIT
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000664 // TODO(X64): Make this go away again. We currently disable RSets for
665 // 64-bit-mode.
666 HeapObjectIterator old_pointer_iterator(old_pointer_space_);
667 while (old_pointer_iterator.has_next()) {
668 HeapObject* heap_object = old_pointer_iterator.next();
669 heap_object->Iterate(&scavenge_visitor);
670 }
671 HeapObjectIterator map_iterator(map_space_);
672 while (map_iterator.has_next()) {
673 HeapObject* heap_object = map_iterator.next();
674 heap_object->Iterate(&scavenge_visitor);
675 }
676 LargeObjectIterator lo_iterator(lo_space_);
677 while (lo_iterator.has_next()) {
678 HeapObject* heap_object = lo_iterator.next();
679 if (heap_object->IsFixedArray()) {
680 heap_object->Iterate(&scavenge_visitor);
681 }
682 }
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000683#else // !defined(V8_HOST_ARCH_64_BIT)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000684 // Copy objects reachable from the old generation. By definition,
685 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000686 IterateRSet(old_pointer_space_, &ScavengePointer);
687 IterateRSet(map_space_, &ScavengePointer);
688 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000689#endif
690
691 // Copy objects reachable from cells by scavenging cell values directly.
692 HeapObjectIterator cell_iterator(cell_space_);
693 while (cell_iterator.has_next()) {
694 HeapObject* cell = cell_iterator.next();
695 if (cell->IsJSGlobalPropertyCell()) {
696 Address value_address =
697 reinterpret_cast<Address>(cell) +
698 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
699 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
700 }
701 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000703 do {
704 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000705
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000706 // The addresses new_space_front and new_space_.top() define a
707 // queue of unprocessed copied objects. Process them until the
708 // queue is empty.
709 while (new_space_front < new_space_.top()) {
710 HeapObject* object = HeapObject::FromAddress(new_space_front);
711 object->Iterate(&scavenge_visitor);
712 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713 }
714
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000715 // Promote and process all the to-be-promoted objects.
716 while (!promotion_queue.is_empty()) {
717 HeapObject* source;
718 Map* map;
719 promotion_queue.remove(&source, &map);
720 // Copy the from-space object to its new location (given by the
721 // forwarding address) and fix its map.
722 HeapObject* target = source->map_word().ToForwardingAddress();
723 CopyBlock(reinterpret_cast<Object**>(target->address()),
724 reinterpret_cast<Object**>(source->address()),
725 source->SizeFromMap(map));
726 target->set_map(map);
727
728#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
729 // Update NewSpace stats if necessary.
730 RecordCopiedObject(target);
731#endif
732 // Visit the newly copied object for pointers to new space.
733 target->Iterate(&scavenge_visitor);
734 UpdateRSet(target);
735 }
736
737 // Take another spin if there are now unswept objects in new space
738 // (there are currently no more unswept promoted objects).
739 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000740
741 // Set age mark.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000742 new_space_.set_age_mark(new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000743
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000744 // Update how much has survived scavenge.
745 survived_since_last_expansion_ +=
746 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
747
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000748 LOG(ResourceEvent("scavenge", "end"));
749
750 gc_state_ = NOT_IN_GC;
751}
752
753
754void Heap::ClearRSetRange(Address start, int size_in_bytes) {
755 uint32_t start_bit;
756 Address start_word_address =
757 Page::ComputeRSetBitPosition(start, 0, &start_bit);
758 uint32_t end_bit;
759 Address end_word_address =
760 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
761 0,
762 &end_bit);
763
764 // We want to clear the bits in the starting word starting with the
765 // first bit, and in the ending word up to and including the last
766 // bit. Build a pair of bitmasks to do that.
767 uint32_t start_bitmask = start_bit - 1;
768 uint32_t end_bitmask = ~((end_bit << 1) - 1);
769
770 // If the start address and end address are the same, we mask that
771 // word once, otherwise mask the starting and ending word
772 // separately and all the ones in between.
773 if (start_word_address == end_word_address) {
774 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
775 } else {
776 Memory::uint32_at(start_word_address) &= start_bitmask;
777 Memory::uint32_at(end_word_address) &= end_bitmask;
778 start_word_address += kIntSize;
779 memset(start_word_address, 0, end_word_address - start_word_address);
780 }
781}
782
783
784class UpdateRSetVisitor: public ObjectVisitor {
785 public:
786
787 void VisitPointer(Object** p) {
788 UpdateRSet(p);
789 }
790
791 void VisitPointers(Object** start, Object** end) {
792 // Update a store into slots [start, end), used (a) to update remembered
793 // set when promoting a young object to old space or (b) to rebuild
794 // remembered sets after a mark-compact collection.
795 for (Object** p = start; p < end; p++) UpdateRSet(p);
796 }
797 private:
798
799 void UpdateRSet(Object** p) {
800 // The remembered set should not be set. It should be clear for objects
801 // newly copied to old space, and it is cleared before rebuilding in the
802 // mark-compact collector.
803 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
804 if (Heap::InNewSpace(*p)) {
805 Page::SetRSet(reinterpret_cast<Address>(p), 0);
806 }
807 }
808};
809
810
811int Heap::UpdateRSet(HeapObject* obj) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000812#ifndef V8_HOST_ARCH_64_BIT
813 // TODO(X64) Reenable RSet when we have a working 64-bit layout of Page.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000814 ASSERT(!InNewSpace(obj));
815 // Special handling of fixed arrays to iterate the body based on the start
816 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
817 // will not work because Page::SetRSet needs to have the start of the
818 // object.
819 if (obj->IsFixedArray()) {
820 FixedArray* array = FixedArray::cast(obj);
821 int length = array->length();
822 for (int i = 0; i < length; i++) {
823 int offset = FixedArray::kHeaderSize + i * kPointerSize;
824 ASSERT(!Page::IsRSetSet(obj->address(), offset));
825 if (Heap::InNewSpace(array->get(i))) {
826 Page::SetRSet(obj->address(), offset);
827 }
828 }
829 } else if (!obj->IsCode()) {
830 // Skip code object, we know it does not contain inter-generational
831 // pointers.
832 UpdateRSetVisitor v;
833 obj->Iterate(&v);
834 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000835#endif // V8_HOST_ARCH_64_BIT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000836 return obj->Size();
837}
838
839
840void Heap::RebuildRSets() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000841 // By definition, we do not care about remembered set bits in code,
842 // data, or cell spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000843 map_space_->ClearRSet();
844 RebuildRSets(map_space_);
845
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000846 old_pointer_space_->ClearRSet();
847 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000848
849 Heap::lo_space_->ClearRSet();
850 RebuildRSets(lo_space_);
851}
852
853
854void Heap::RebuildRSets(PagedSpace* space) {
855 HeapObjectIterator it(space);
856 while (it.has_next()) Heap::UpdateRSet(it.next());
857}
858
859
860void Heap::RebuildRSets(LargeObjectSpace* space) {
861 LargeObjectIterator it(space);
862 while (it.has_next()) Heap::UpdateRSet(it.next());
863}
864
865
866#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
867void Heap::RecordCopiedObject(HeapObject* obj) {
868 bool should_record = false;
869#ifdef DEBUG
870 should_record = FLAG_heap_stats;
871#endif
872#ifdef ENABLE_LOGGING_AND_PROFILING
873 should_record = should_record || FLAG_log_gc;
874#endif
875 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000876 if (new_space_.Contains(obj)) {
877 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000879 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000880 }
881 }
882}
883#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
884
885
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000886
887HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000888 HeapObject* target,
889 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000890 // Copy the content of source to target.
891 CopyBlock(reinterpret_cast<Object**>(target->address()),
892 reinterpret_cast<Object**>(source->address()),
893 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000894
kasper.lund7276f142008-07-30 08:49:36 +0000895 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000896 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000897
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000899 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900 RecordCopiedObject(target);
901#endif
902
903 return target;
904}
905
906
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000907static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000908 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000909 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000910 InstanceType type = map->instance_type();
911 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
912 ASSERT(object->IsString() && !object->IsSymbol());
913 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000914}
915
916
917void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
918 ASSERT(InFromSpace(object));
919 MapWord first_word = object->map_word();
920 ASSERT(!first_word.IsForwardingAddress());
921
922 // Optimization: Bypass flattened ConsString objects.
923 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000924 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 *p = object;
926 // After patching *p we have to repeat the checks that object is in the
927 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000928 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000929 first_word = object->map_word();
930 if (first_word.IsForwardingAddress()) {
931 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000932 return;
933 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000934 }
935
kasper.lund7276f142008-07-30 08:49:36 +0000936 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000937 // We rely on live objects in new space to be at least two pointers,
938 // so we can store the from-space address and map pointer of promoted
939 // objects in the to space.
940 ASSERT(object_size >= 2 * kPointerSize);
941
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000942 // If the object should be promoted, we try to copy it to old space.
943 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000944 Object* result;
945 if (object_size > MaxObjectSizeInPagedSpace()) {
946 result = lo_space_->AllocateRawFixedArray(object_size);
947 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000948 // Save the from-space object pointer and its map pointer at the
949 // top of the to space to be swept and copied later. Write the
950 // forwarding address over the map word of the from-space
951 // object.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000952 HeapObject* target = HeapObject::cast(result);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000953 promotion_queue.insert(object, first_word.ToMap());
954 object->set_map_word(MapWord::FromForwardingAddress(target));
955
956 // Give the space allocated for the result a proper map by
957 // treating it as a free list node (not linked into the free
958 // list).
959 FreeListNode* node = FreeListNode::FromAddress(target->address());
960 node->set_size(object_size);
961
962 *p = target;
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000963 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000964 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000965 } else {
966 OldSpace* target_space = Heap::TargetSpace(object);
967 ASSERT(target_space == Heap::old_pointer_space_ ||
968 target_space == Heap::old_data_space_);
969 result = target_space->AllocateRaw(object_size);
970 if (!result->IsFailure()) {
971 HeapObject* target = HeapObject::cast(result);
972 if (target_space == Heap::old_pointer_space_) {
973 // Save the from-space object pointer and its map pointer at the
974 // top of the to space to be swept and copied later. Write the
975 // forwarding address over the map word of the from-space
976 // object.
977 promotion_queue.insert(object, first_word.ToMap());
978 object->set_map_word(MapWord::FromForwardingAddress(target));
979
980 // Give the space allocated for the result a proper map by
981 // treating it as a free list node (not linked into the free
982 // list).
983 FreeListNode* node = FreeListNode::FromAddress(target->address());
984 node->set_size(object_size);
985
986 *p = target;
987 } else {
988 // Objects promoted to the data space can be copied immediately
989 // and not revisited---we will never sweep that space for
990 // pointers and the copied objects do not contain pointers to
991 // new space objects.
992 *p = MigrateObject(object, target, object_size);
993#ifdef DEBUG
994 VerifyNonPointerSpacePointersVisitor v;
995 (*p)->Iterate(&v);
996#endif
997 }
998 return;
999 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001000 }
1001 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001002 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001003 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001004 // Failed allocation at this point is utterly unexpected.
1005 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001006 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1007}
1008
1009
1010void Heap::ScavengePointer(HeapObject** p) {
1011 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001012}
1013
1014
1015Object* Heap::AllocatePartialMap(InstanceType instance_type,
1016 int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001017 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001018 if (result->IsFailure()) return result;
1019
1020 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001021 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1023 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001024 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001025 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1026 return result;
1027}
1028
1029
1030Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001031 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001032 if (result->IsFailure()) return result;
1033
1034 Map* map = reinterpret_cast<Map*>(result);
1035 map->set_map(meta_map());
1036 map->set_instance_type(instance_type);
1037 map->set_prototype(null_value());
1038 map->set_constructor(null_value());
1039 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001040 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001041 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001042 map->set_code_cache(empty_fixed_array());
1043 map->set_unused_property_fields(0);
1044 map->set_bit_field(0);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001045 map->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046 return map;
1047}
1048
1049
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001050const Heap::StringTypeTable Heap::string_type_table[] = {
1051#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1052 {type, size, k##camel_name##MapRootIndex},
1053 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1054#undef STRING_TYPE_ELEMENT
1055};
1056
1057
1058const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1059#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1060 {contents, k##name##RootIndex},
1061 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1062#undef CONSTANT_SYMBOL_ELEMENT
1063};
1064
1065
1066const Heap::StructTable Heap::struct_table[] = {
1067#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1068 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1069 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1070#undef STRUCT_TABLE_ELEMENT
1071};
1072
1073
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001074bool Heap::CreateInitialMaps() {
1075 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1076 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001077 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001078 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1079 set_meta_map(new_meta_map);
1080 new_meta_map->set_map(new_meta_map);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001081
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001082 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001083 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001084 set_fixed_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001085
1086 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1087 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001088 set_oddball_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001089
1090 // Allocate the empty array
1091 obj = AllocateEmptyFixedArray();
1092 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001093 set_empty_fixed_array(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001094
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001095 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001096 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001097 set_null_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001098
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001099 // Allocate the empty descriptor array.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001100 obj = AllocateEmptyFixedArray();
1101 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001102 set_empty_descriptor_array(DescriptorArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001103
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001104 // Fix the instance_descriptors for the existing maps.
1105 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001106 meta_map()->set_code_cache(empty_fixed_array());
1107
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001108 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001109 fixed_array_map()->set_code_cache(empty_fixed_array());
1110
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001111 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001112 oddball_map()->set_code_cache(empty_fixed_array());
1113
1114 // Fix prototype object for existing maps.
1115 meta_map()->set_prototype(null_value());
1116 meta_map()->set_constructor(null_value());
1117
1118 fixed_array_map()->set_prototype(null_value());
1119 fixed_array_map()->set_constructor(null_value());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001120
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001121 oddball_map()->set_prototype(null_value());
1122 oddball_map()->set_constructor(null_value());
1123
1124 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1125 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001126 set_heap_number_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001127
1128 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1129 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001130 set_proxy_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001131
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001132 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1133 const StringTypeTable& entry = string_type_table[i];
1134 obj = AllocateMap(entry.type, entry.size);
1135 if (obj->IsFailure()) return false;
1136 roots_[entry.index] = Map::cast(obj);
1137 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001138
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001139 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001140 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001141 set_undetectable_short_string_map(Map::cast(obj));
1142 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001143
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001144 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001145 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001146 set_undetectable_medium_string_map(Map::cast(obj));
1147 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001148
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001149 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001150 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001151 set_undetectable_long_string_map(Map::cast(obj));
1152 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001153
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001154 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001155 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001156 set_undetectable_short_ascii_string_map(Map::cast(obj));
1157 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001158
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001159 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001161 set_undetectable_medium_ascii_string_map(Map::cast(obj));
1162 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001163
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001164 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001165 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001166 set_undetectable_long_ascii_string_map(Map::cast(obj));
1167 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001168
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001169 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001170 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001171 set_byte_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001172
1173 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1174 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001175 set_code_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001176
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001177 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1178 JSGlobalPropertyCell::kSize);
1179 if (obj->IsFailure()) return false;
1180 set_global_property_cell_map(Map::cast(obj));
1181
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001182 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1183 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001184 set_one_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001185
1186 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1187 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001188 set_two_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001189
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001190 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1191 const StructTable& entry = struct_table[i];
1192 obj = AllocateMap(entry.type, entry.size);
1193 if (obj->IsFailure()) return false;
1194 roots_[entry.index] = Map::cast(obj);
1195 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001196
ager@chromium.org236ad962008-09-25 09:45:57 +00001197 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001198 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001199 set_hash_table_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001200
ager@chromium.org236ad962008-09-25 09:45:57 +00001201 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001202 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001203 set_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001204
ager@chromium.org236ad962008-09-25 09:45:57 +00001205 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001206 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001207 set_catch_context_map(Map::cast(obj));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001208
1209 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1210 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001211 set_global_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001212
1213 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1214 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001215 set_boilerplate_function_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001216
1217 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1218 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001219 set_shared_function_info_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001220
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001221 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001222 return true;
1223}
1224
1225
1226Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1227 // Statically ensure that it is safe to allocate heap numbers in paged
1228 // spaces.
1229 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001230 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001231 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001232 if (result->IsFailure()) return result;
1233
1234 HeapObject::cast(result)->set_map(heap_number_map());
1235 HeapNumber::cast(result)->set_value(value);
1236 return result;
1237}
1238
1239
1240Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001241 // Use general version, if we're forced to always allocate.
1242 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001243 // This version of AllocateHeapNumber is optimized for
1244 // allocation in new space.
1245 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1246 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001247 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001248 if (result->IsFailure()) return result;
1249 HeapObject::cast(result)->set_map(heap_number_map());
1250 HeapNumber::cast(result)->set_value(value);
1251 return result;
1252}
1253
1254
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001255Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001256 Object* result = AllocateRawCell();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001257 if (result->IsFailure()) return result;
1258 HeapObject::cast(result)->set_map(global_property_cell_map());
1259 JSGlobalPropertyCell::cast(result)->set_value(value);
1260 return result;
1261}
1262
1263
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001264Object* Heap::CreateOddball(Map* map,
1265 const char* to_string,
1266 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001267 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001268 if (result->IsFailure()) return result;
1269 return Oddball::cast(result)->Initialize(to_string, to_number);
1270}
1271
1272
1273bool Heap::CreateApiObjects() {
1274 Object* obj;
1275
1276 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1277 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001278 set_neander_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001279
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001280 obj = Heap::AllocateJSObjectFromMap(neander_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001281 if (obj->IsFailure()) return false;
1282 Object* elements = AllocateFixedArray(2);
1283 if (elements->IsFailure()) return false;
1284 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1285 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001286 set_message_listeners(JSObject::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001287
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001288 return true;
1289}
1290
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001291
1292void Heap::CreateCEntryStub() {
1293 CEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001294 set_c_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001295}
1296
1297
1298void Heap::CreateCEntryDebugBreakStub() {
1299 CEntryDebugBreakStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001300 set_c_entry_debug_break_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001301}
1302
1303
1304void Heap::CreateJSEntryStub() {
1305 JSEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001306 set_js_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001307}
1308
1309
1310void Heap::CreateJSConstructEntryStub() {
1311 JSConstructEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001312 set_js_construct_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001313}
1314
1315
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001316void Heap::CreateFixedStubs() {
1317 // Here we create roots for fixed stubs. They are needed at GC
1318 // for cooking and uncooking (check out frames.cc).
1319 // The eliminates the need for doing dictionary lookup in the
1320 // stub cache for these stubs.
1321 HandleScope scope;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001322 // gcc-4.4 has problem generating correct code of following snippet:
1323 // { CEntryStub stub;
1324 // c_entry_code_ = *stub.GetCode();
1325 // }
1326 // { CEntryDebugBreakStub stub;
1327 // c_entry_debug_break_code_ = *stub.GetCode();
1328 // }
1329 // To workaround the problem, make separate functions without inlining.
1330 Heap::CreateCEntryStub();
1331 Heap::CreateCEntryDebugBreakStub();
1332 Heap::CreateJSEntryStub();
1333 Heap::CreateJSConstructEntryStub();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001334}
1335
1336
1337bool Heap::CreateInitialObjects() {
1338 Object* obj;
1339
1340 // The -0 value must be set before NumberFromDouble works.
1341 obj = AllocateHeapNumber(-0.0, TENURED);
1342 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001343 set_minus_zero_value(obj);
1344 ASSERT(signbit(minus_zero_value()->Number()) != 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001345
1346 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1347 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001348 set_nan_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001349
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001350 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001351 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001352 set_undefined_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001353 ASSERT(!InNewSpace(undefined_value()));
1354
1355 // Allocate initial symbol table.
1356 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1357 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001358 // Don't use set_symbol_table() due to asserts.
1359 roots_[kSymbolTableRootIndex] = obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360
1361 // Assign the print strings for oddballs after creating symboltable.
1362 Object* symbol = LookupAsciiSymbol("undefined");
1363 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001364 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1365 Oddball::cast(undefined_value())->set_to_number(nan_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001366
1367 // Assign the print strings for oddballs after creating symboltable.
1368 symbol = LookupAsciiSymbol("null");
1369 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001370 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1371 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001372
1373 // Allocate the null_value
1374 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1375 if (obj->IsFailure()) return false;
1376
1377 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1378 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001379 set_true_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001380
1381 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1382 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001383 set_false_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001384
1385 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1386 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001387 set_the_hole_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001388
1389 // Allocate the empty string.
1390 obj = AllocateRawAsciiString(0, TENURED);
1391 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001392 set_empty_string(String::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001393
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001394 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1395 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1396 if (obj->IsFailure()) return false;
1397 roots_[constant_symbol_table[i].index] = String::cast(obj);
1398 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001400 // Allocate the hidden symbol which is used to identify the hidden properties
1401 // in JSObjects. The hash code has a special value so that it will not match
1402 // the empty string when searching for the property. It cannot be part of the
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001403 // loop above because it needs to be allocated manually with the special
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001404 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1405 // that it will always be at the first entry in property descriptors.
1406 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1407 if (obj->IsFailure()) return false;
1408 hidden_symbol_ = String::cast(obj);
1409
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001410 // Allocate the proxy for __proto__.
1411 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1412 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001413 set_prototype_accessors(Proxy::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001414
1415 // Allocate the code_stubs dictionary.
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00001416 obj = NumberDictionary::Allocate(4);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001417 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001418 set_code_stubs(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001419
1420 // Allocate the non_monomorphic_cache used in stub-cache.cc
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00001421 obj = NumberDictionary::Allocate(4);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001422 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001423 set_non_monomorphic_cache(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001424
1425 CreateFixedStubs();
1426
1427 // Allocate the number->string conversion cache
1428 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1429 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001430 set_number_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001431
1432 // Allocate cache for single character strings.
1433 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1434 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001435 set_single_character_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001436
1437 // Allocate cache for external strings pointing to native source code.
1438 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1439 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001440 set_natives_source_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001441
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001442 // Handling of script id generation is in Factory::NewScript.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001443 set_last_script_id(undefined_value());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001444
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001445 // Initialize keyed lookup cache.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001446 KeyedLookupCache::Clear();
1447
1448 // Initialize context slot cache.
1449 ContextSlotCache::Clear();
1450
1451 // Initialize descriptor cache.
1452 DescriptorLookupCache::Clear();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001453
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001454 // Initialize compilation cache.
1455 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001456
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001457 return true;
1458}
1459
1460
1461static inline int double_get_hash(double d) {
1462 DoubleRepresentation rep(d);
1463 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1464 (Heap::kNumberStringCacheSize - 1));
1465}
1466
1467
1468static inline int smi_get_hash(Smi* smi) {
1469 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1470}
1471
1472
1473
1474Object* Heap::GetNumberStringCache(Object* number) {
1475 int hash;
1476 if (number->IsSmi()) {
1477 hash = smi_get_hash(Smi::cast(number));
1478 } else {
1479 hash = double_get_hash(number->Number());
1480 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001481 Object* key = number_string_cache()->get(hash * 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001482 if (key == number) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001483 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001484 } else if (key->IsHeapNumber() &&
1485 number->IsHeapNumber() &&
1486 key->Number() == number->Number()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001487 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001488 }
1489 return undefined_value();
1490}
1491
1492
1493void Heap::SetNumberStringCache(Object* number, String* string) {
1494 int hash;
1495 if (number->IsSmi()) {
1496 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001497 number_string_cache()->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001498 } else {
1499 hash = double_get_hash(number->Number());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001500 number_string_cache()->set(hash * 2, number);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001501 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001502 number_string_cache()->set(hash * 2 + 1, string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001503}
1504
1505
1506Object* Heap::SmiOrNumberFromDouble(double value,
1507 bool new_object,
1508 PretenureFlag pretenure) {
1509 // We need to distinguish the minus zero value and this cannot be
1510 // done after conversion to int. Doing this by comparing bit
1511 // patterns is faster than using fpclassify() et al.
1512 static const DoubleRepresentation plus_zero(0.0);
1513 static const DoubleRepresentation minus_zero(-0.0);
1514 static const DoubleRepresentation nan(OS::nan_value());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001515 ASSERT(minus_zero_value() != NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001516 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1517
1518 DoubleRepresentation rep(value);
1519 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1520 if (rep.bits == minus_zero.bits) {
1521 return new_object ? AllocateHeapNumber(-0.0, pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001522 : minus_zero_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001523 }
1524 if (rep.bits == nan.bits) {
1525 return new_object
1526 ? AllocateHeapNumber(OS::nan_value(), pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001527 : nan_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001528 }
1529
1530 // Try to represent the value as a tagged small integer.
1531 int int_value = FastD2I(value);
1532 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1533 return Smi::FromInt(int_value);
1534 }
1535
1536 // Materialize the value in the heap.
1537 return AllocateHeapNumber(value, pretenure);
1538}
1539
1540
1541Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1542 return SmiOrNumberFromDouble(value,
1543 true /* number object must be new */,
1544 pretenure);
1545}
1546
1547
1548Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1549 return SmiOrNumberFromDouble(value,
1550 false /* use preallocated NaN, -0.0 */,
1551 pretenure);
1552}
1553
1554
1555Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1556 // Statically ensure that it is safe to allocate proxies in paged spaces.
1557 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001558 AllocationSpace space =
1559 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001560 Object* result = Allocate(proxy_map(), space);
1561 if (result->IsFailure()) return result;
1562
1563 Proxy::cast(result)->set_proxy(proxy);
1564 return result;
1565}
1566
1567
1568Object* Heap::AllocateSharedFunctionInfo(Object* name) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001569 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570 if (result->IsFailure()) return result;
1571
1572 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1573 share->set_name(name);
1574 Code* illegal = Builtins::builtin(Builtins::Illegal);
1575 share->set_code(illegal);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001576 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1577 share->set_construct_stub(construct_stub);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001578 share->set_expected_nof_properties(0);
1579 share->set_length(0);
1580 share->set_formal_parameter_count(0);
1581 share->set_instance_class_name(Object_symbol());
1582 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583 share->set_script(undefined_value());
1584 share->set_start_position_and_type(0);
1585 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001586 share->set_inferred_name(empty_string());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001587 return result;
1588}
1589
1590
ager@chromium.org3e875802009-06-29 08:26:34 +00001591Object* Heap::AllocateConsString(String* first, String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001592 int first_length = first->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001593 if (first_length == 0) return second;
1594
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001595 int second_length = second->length();
ager@chromium.org3e875802009-06-29 08:26:34 +00001596 if (second_length == 0) return first;
1597
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001598 int length = first_length + second_length;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001599 bool is_ascii = first->IsAsciiRepresentation()
1600 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001601
ager@chromium.org3e875802009-06-29 08:26:34 +00001602 // Make sure that an out of memory exception is thrown if the length
1603 // of the new cons string is too large to fit in a Smi.
1604 if (length > Smi::kMaxValue || length < -0) {
1605 Top::context()->mark_out_of_memory();
1606 return Failure::OutOfMemoryException();
1607 }
1608
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001610 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001611 ASSERT(first->IsFlat());
1612 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001613 if (is_ascii) {
1614 Object* result = AllocateRawAsciiString(length);
1615 if (result->IsFailure()) return result;
1616 // Copy the characters into the new object.
1617 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org3e875802009-06-29 08:26:34 +00001618 // Copy first part.
1619 char* src = SeqAsciiString::cast(first)->GetChars();
1620 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1621 // Copy second part.
1622 src = SeqAsciiString::cast(second)->GetChars();
1623 for (int i = 0; i < second_length; i++) *dest++ = src[i];
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001624 return result;
1625 } else {
1626 Object* result = AllocateRawTwoByteString(length);
1627 if (result->IsFailure()) return result;
1628 // Copy the characters into the new object.
1629 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001630 String::WriteToFlat(first, dest, 0, first_length);
1631 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001632 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001633 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634 }
1635
1636 Map* map;
1637 if (length <= String::kMaxShortStringSize) {
1638 map = is_ascii ? short_cons_ascii_string_map()
1639 : short_cons_string_map();
1640 } else if (length <= String::kMaxMediumStringSize) {
1641 map = is_ascii ? medium_cons_ascii_string_map()
1642 : medium_cons_string_map();
1643 } else {
1644 map = is_ascii ? long_cons_ascii_string_map()
1645 : long_cons_string_map();
1646 }
1647
1648 Object* result = Allocate(map, NEW_SPACE);
1649 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001650 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001651 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001652 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1653 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001655 return result;
1656}
1657
1658
ager@chromium.org870a0b62008-11-04 11:43:05 +00001659Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001660 int start,
1661 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001662 int length = end - start;
1663
1664 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001665 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001666 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001667 }
1668
1669 Map* map;
1670 if (length <= String::kMaxShortStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001671 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001672 short_sliced_ascii_string_map() :
1673 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001674 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001675 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001676 medium_sliced_ascii_string_map() :
1677 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001678 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001679 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001680 long_sliced_ascii_string_map() :
1681 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682 }
1683
1684 Object* result = Allocate(map, NEW_SPACE);
1685 if (result->IsFailure()) return result;
1686
1687 SlicedString* sliced_string = SlicedString::cast(result);
1688 sliced_string->set_buffer(buffer);
1689 sliced_string->set_start(start);
1690 sliced_string->set_length(length);
1691
1692 return result;
1693}
1694
1695
ager@chromium.org870a0b62008-11-04 11:43:05 +00001696Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001697 int start,
1698 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001699 int length = end - start;
1700
ager@chromium.org7c537e22008-10-16 08:43:32 +00001701 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001702 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001703 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001704 }
1705
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001707 if (!buffer->IsFlat()) {
1708 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001709 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710
ager@chromium.org5ec48922009-05-05 07:25:34 +00001711 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 ? AllocateRawAsciiString(length)
1713 : AllocateRawTwoByteString(length);
1714 if (result->IsFailure()) return result;
1715
1716 // Copy the characters into the new object.
1717 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001718 StringHasher hasher(length);
1719 int i = 0;
1720 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001721 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001722 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001723 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001724 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001725 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001726 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001727 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001728 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001729 }
1730 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001731 return result;
1732}
1733
1734
1735Object* Heap::AllocateExternalStringFromAscii(
1736 ExternalAsciiString::Resource* resource) {
1737 Map* map;
1738 int length = resource->length();
1739 if (length <= String::kMaxShortStringSize) {
1740 map = short_external_ascii_string_map();
1741 } else if (length <= String::kMaxMediumStringSize) {
1742 map = medium_external_ascii_string_map();
1743 } else {
1744 map = long_external_ascii_string_map();
1745 }
1746
1747 Object* result = Allocate(map, NEW_SPACE);
1748 if (result->IsFailure()) return result;
1749
1750 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1751 external_string->set_length(length);
1752 external_string->set_resource(resource);
1753
1754 return result;
1755}
1756
1757
1758Object* Heap::AllocateExternalStringFromTwoByte(
1759 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001760 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001761
ager@chromium.org6f10e412009-02-13 10:11:16 +00001762 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001763 Object* result = Allocate(map, NEW_SPACE);
1764 if (result->IsFailure()) return result;
1765
1766 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1767 external_string->set_length(length);
1768 external_string->set_resource(resource);
1769
1770 return result;
1771}
1772
1773
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001774Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001775 if (code <= String::kMaxAsciiCharCode) {
1776 Object* value = Heap::single_character_string_cache()->get(code);
1777 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001778
1779 char buffer[1];
1780 buffer[0] = static_cast<char>(code);
1781 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1782
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001783 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001784 Heap::single_character_string_cache()->set(code, result);
1785 return result;
1786 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001787
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001788 Object* result = Heap::AllocateRawTwoByteString(1);
1789 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001790 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001791 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001792 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001793}
1794
1795
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001796Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1797 if (pretenure == NOT_TENURED) {
1798 return AllocateByteArray(length);
1799 }
1800 int size = ByteArray::SizeFor(length);
1801 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001802 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : OLD_DATA_SPACE;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001803
1804 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1805
1806 if (result->IsFailure()) return result;
1807
1808 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1809 reinterpret_cast<Array*>(result)->set_length(length);
1810 return result;
1811}
1812
1813
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001814Object* Heap::AllocateByteArray(int length) {
1815 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001816 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001817 size > MaxObjectSizeInPagedSpace() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001818
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001819 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001820
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001821 if (result->IsFailure()) return result;
1822
1823 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1824 reinterpret_cast<Array*>(result)->set_length(length);
1825 return result;
1826}
1827
1828
ager@chromium.org6f10e412009-02-13 10:11:16 +00001829void Heap::CreateFillerObjectAt(Address addr, int size) {
1830 if (size == 0) return;
1831 HeapObject* filler = HeapObject::FromAddress(addr);
1832 if (size == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001833 filler->set_map(Heap::one_pointer_filler_map());
ager@chromium.org6f10e412009-02-13 10:11:16 +00001834 } else {
1835 filler->set_map(Heap::byte_array_map());
1836 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1837 }
1838}
1839
1840
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001841Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001842 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001843 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001844 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001845 // Compute size
1846 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1847 int sinfo_size = 0;
1848 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1849 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001850 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001851 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001852 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001853 result = lo_space_->AllocateRawCode(obj_size);
1854 } else {
1855 result = code_space_->AllocateRaw(obj_size);
1856 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001857
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001858 if (result->IsFailure()) return result;
1859
1860 // Initialize the object
1861 HeapObject::cast(result)->set_map(code_map());
1862 Code* code = Code::cast(result);
1863 code->set_instruction_size(desc.instr_size);
1864 code->set_relocation_size(desc.reloc_size);
1865 code->set_sinfo_size(sinfo_size);
1866 code->set_flags(flags);
1867 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001868 // Allow self references to created code object by patching the handle to
1869 // point to the newly allocated Code object.
1870 if (!self_reference.is_null()) {
1871 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001872 }
1873 // Migrate generated code.
1874 // The generated code can contain Object** values (typically from handles)
1875 // that are dereferenced during the copy to point directly to the actual heap
1876 // objects. These pointers can include references to the code object itself,
1877 // through the self_reference parameter.
1878 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001879 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1880
1881#ifdef DEBUG
1882 code->Verify();
1883#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001884 return code;
1885}
1886
1887
1888Object* Heap::CopyCode(Code* code) {
1889 // Allocate an object the same size as the code object.
1890 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001891 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001892 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001893 result = lo_space_->AllocateRawCode(obj_size);
1894 } else {
1895 result = code_space_->AllocateRaw(obj_size);
1896 }
1897
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001898 if (result->IsFailure()) return result;
1899
1900 // Copy code object.
1901 Address old_addr = code->address();
1902 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001903 CopyBlock(reinterpret_cast<Object**>(new_addr),
1904 reinterpret_cast<Object**>(old_addr),
1905 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001906 // Relocate the copy.
1907 Code* new_code = Code::cast(result);
1908 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001909 return new_code;
1910}
1911
1912
1913Object* Heap::Allocate(Map* map, AllocationSpace space) {
1914 ASSERT(gc_state_ == NOT_IN_GC);
1915 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001916 Object* result = AllocateRaw(map->instance_size(),
1917 space,
1918 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001919 if (result->IsFailure()) return result;
1920 HeapObject::cast(result)->set_map(map);
1921 return result;
1922}
1923
1924
1925Object* Heap::InitializeFunction(JSFunction* function,
1926 SharedFunctionInfo* shared,
1927 Object* prototype) {
1928 ASSERT(!prototype->IsMap());
1929 function->initialize_properties();
1930 function->initialize_elements();
1931 function->set_shared(shared);
1932 function->set_prototype_or_initial_map(prototype);
1933 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001934 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001935 return function;
1936}
1937
1938
1939Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001940 // Allocate the prototype. Make sure to use the object function
1941 // from the function's context, since the function can be from a
1942 // different context.
1943 JSFunction* object_function =
1944 function->context()->global_context()->object_function();
1945 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001946 if (prototype->IsFailure()) return prototype;
1947 // When creating the prototype for the function we must set its
1948 // constructor to the function.
1949 Object* result =
1950 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1951 function,
1952 DONT_ENUM);
1953 if (result->IsFailure()) return result;
1954 return prototype;
1955}
1956
1957
1958Object* Heap::AllocateFunction(Map* function_map,
1959 SharedFunctionInfo* shared,
1960 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001961 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001962 if (result->IsFailure()) return result;
1963 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1964}
1965
1966
1967Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001968 // To get fast allocation and map sharing for arguments objects we
1969 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001970
1971 // This calls Copy directly rather than using Heap::AllocateRaw so we
1972 // duplicate the check here.
1973 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1974
1975 JSObject* boilerplate =
1976 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001977
1978 // Make the clone.
1979 Map* map = boilerplate->map();
1980 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001981 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001982 if (result->IsFailure()) return result;
1983
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001984 // Copy the content. The arguments boilerplate doesn't have any
1985 // fields that point to new space so it's safe to skip the write
1986 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001987 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1988 reinterpret_cast<Object**>(boilerplate->address()),
1989 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001990
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001991 // Set the two properties.
1992 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001993 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001994 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1995 Smi::FromInt(length),
1996 SKIP_WRITE_BARRIER);
1997
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001998 // Check the state of the object
1999 ASSERT(JSObject::cast(result)->HasFastProperties());
2000 ASSERT(JSObject::cast(result)->HasFastElements());
2001
2002 return result;
2003}
2004
2005
2006Object* Heap::AllocateInitialMap(JSFunction* fun) {
2007 ASSERT(!fun->has_initial_map());
2008
ager@chromium.org7c537e22008-10-16 08:43:32 +00002009 // First create a new map with the expected number of properties being
2010 // allocated in-object.
2011 int expected_nof_properties = fun->shared()->expected_nof_properties();
2012 int instance_size = JSObject::kHeaderSize +
2013 expected_nof_properties * kPointerSize;
2014 if (instance_size > JSObject::kMaxInstanceSize) {
2015 instance_size = JSObject::kMaxInstanceSize;
2016 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
2017 kPointerSize;
2018 }
2019 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002020 if (map_obj->IsFailure()) return map_obj;
2021
2022 // Fetch or allocate prototype.
2023 Object* prototype;
2024 if (fun->has_instance_prototype()) {
2025 prototype = fun->instance_prototype();
2026 } else {
2027 prototype = AllocateFunctionPrototype(fun);
2028 if (prototype->IsFailure()) return prototype;
2029 }
2030 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002031 map->set_inobject_properties(expected_nof_properties);
2032 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002033 map->set_prototype(prototype);
2034 return map;
2035}
2036
2037
2038void Heap::InitializeJSObjectFromMap(JSObject* obj,
2039 FixedArray* properties,
2040 Map* map) {
2041 obj->set_properties(properties);
2042 obj->initialize_elements();
2043 // TODO(1240798): Initialize the object's body using valid initial values
2044 // according to the object's initial map. For example, if the map's
2045 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2046 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2047 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2048 // verification code has to cope with (temporarily) invalid objects. See
2049 // for example, JSArray::JSArrayVerify).
2050 obj->InitializeBody(map->instance_size());
2051}
2052
2053
2054Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2055 // JSFunctions should be allocated using AllocateFunction to be
2056 // properly initialized.
2057 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2058
2059 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002060 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002061 Object* properties = AllocateFixedArray(prop_size, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002062 if (properties->IsFailure()) return properties;
2063
2064 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002065 AllocationSpace space =
2066 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002067 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002068 Object* obj = Allocate(map, space);
2069 if (obj->IsFailure()) return obj;
2070
2071 // Initialize the JSObject.
2072 InitializeJSObjectFromMap(JSObject::cast(obj),
2073 FixedArray::cast(properties),
2074 map);
2075 return obj;
2076}
2077
2078
2079Object* Heap::AllocateJSObject(JSFunction* constructor,
2080 PretenureFlag pretenure) {
2081 // Allocate the initial map if absent.
2082 if (!constructor->has_initial_map()) {
2083 Object* initial_map = AllocateInitialMap(constructor);
2084 if (initial_map->IsFailure()) return initial_map;
2085 constructor->set_initial_map(Map::cast(initial_map));
2086 Map::cast(initial_map)->set_constructor(constructor);
2087 }
2088 // Allocate the object based on the constructors initial map.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002089 Object* result =
2090 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2091 // Make sure result is NOT a global object if valid.
2092 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2093 return result;
2094}
2095
2096
2097Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2098 ASSERT(constructor->has_initial_map());
2099 // Make sure no field properties are described in the initial map.
2100 // This guarantees us that normalizing the properties does not
2101 // require us to change property values to JSGlobalPropertyCells.
2102 ASSERT(constructor->initial_map()->NextFreePropertyIndex() == 0);
2103
2104 // Make sure we don't have a ton of pre-allocated slots in the
2105 // global objects. They will be unused once we normalize the object.
2106 ASSERT(constructor->initial_map()->unused_property_fields() == 0);
2107 ASSERT(constructor->initial_map()->inobject_properties() == 0);
2108
2109 // Allocate the object based on the constructors initial map.
2110 Object* result = AllocateJSObjectFromMap(constructor->initial_map(), TENURED);
2111 if (result->IsFailure()) return result;
2112
2113 // Normalize the result.
2114 JSObject* global = JSObject::cast(result);
2115 result = global->NormalizeProperties(CLEAR_INOBJECT_PROPERTIES);
2116 if (result->IsFailure()) return result;
2117
2118 // Make sure result is a global object with properties in dictionary.
2119 ASSERT(global->IsGlobalObject());
2120 ASSERT(!global->HasFastProperties());
2121 return global;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002122}
2123
2124
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002125Object* Heap::CopyJSObject(JSObject* source) {
2126 // Never used to copy functions. If functions need to be copied we
2127 // have to be careful to clear the literals array.
2128 ASSERT(!source->IsJSFunction());
2129
2130 // Make the clone.
2131 Map* map = source->map();
2132 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002133 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002134
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002135 // If we're forced to always allocate, we use the general allocation
2136 // functions which may leave us with an object in old space.
2137 if (always_allocate()) {
2138 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2139 if (clone->IsFailure()) return clone;
2140 Address clone_address = HeapObject::cast(clone)->address();
2141 CopyBlock(reinterpret_cast<Object**>(clone_address),
2142 reinterpret_cast<Object**>(source->address()),
2143 object_size);
2144 // Update write barrier for all fields that lie beyond the header.
2145 for (int offset = JSObject::kHeaderSize;
2146 offset < object_size;
2147 offset += kPointerSize) {
2148 RecordWrite(clone_address, offset);
2149 }
2150 } else {
2151 clone = new_space_.AllocateRaw(object_size);
2152 if (clone->IsFailure()) return clone;
2153 ASSERT(Heap::InNewSpace(clone));
2154 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002155 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002156 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2157 reinterpret_cast<Object**>(source->address()),
2158 object_size);
2159 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002160
2161 FixedArray* elements = FixedArray::cast(source->elements());
2162 FixedArray* properties = FixedArray::cast(source->properties());
2163 // Update elements if necessary.
2164 if (elements->length()> 0) {
2165 Object* elem = CopyFixedArray(elements);
2166 if (elem->IsFailure()) return elem;
2167 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2168 }
2169 // Update properties if necessary.
2170 if (properties->length() > 0) {
2171 Object* prop = CopyFixedArray(properties);
2172 if (prop->IsFailure()) return prop;
2173 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2174 }
2175 // Return the new clone.
2176 return clone;
2177}
2178
2179
2180Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2181 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002182 // Allocate initial map if absent.
2183 if (!constructor->has_initial_map()) {
2184 Object* initial_map = AllocateInitialMap(constructor);
2185 if (initial_map->IsFailure()) return initial_map;
2186 constructor->set_initial_map(Map::cast(initial_map));
2187 Map::cast(initial_map)->set_constructor(constructor);
2188 }
2189
2190 Map* map = constructor->initial_map();
2191
2192 // Check that the already allocated object has the same size as
2193 // objects allocated using the constructor.
2194 ASSERT(map->instance_size() == object->map()->instance_size());
2195
2196 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002197 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002198 Object* properties = AllocateFixedArray(prop_size, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002199 if (properties->IsFailure()) return properties;
2200
2201 // Reset the map for the object.
2202 object->set_map(constructor->initial_map());
2203
2204 // Reinitialize the object from the constructor map.
2205 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2206 return object;
2207}
2208
2209
2210Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2211 PretenureFlag pretenure) {
2212 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2213 if (result->IsFailure()) return result;
2214
2215 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002216 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002217 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002218 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002219 }
2220 return result;
2221}
2222
2223
2224Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2225 PretenureFlag pretenure) {
2226 // Count the number of characters in the UTF-8 string and check if
2227 // it is an ASCII string.
2228 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2229 decoder->Reset(string.start(), string.length());
2230 int chars = 0;
2231 bool is_ascii = true;
2232 while (decoder->has_more()) {
2233 uc32 r = decoder->GetNext();
2234 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2235 chars++;
2236 }
2237
2238 // If the string is ascii, we do not need to convert the characters
2239 // since UTF8 is backwards compatible with ascii.
2240 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2241
2242 Object* result = AllocateRawTwoByteString(chars, pretenure);
2243 if (result->IsFailure()) return result;
2244
2245 // Convert and copy the characters into the new object.
2246 String* string_result = String::cast(result);
2247 decoder->Reset(string.start(), string.length());
2248 for (int i = 0; i < chars; i++) {
2249 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002250 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002251 }
2252 return result;
2253}
2254
2255
2256Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2257 PretenureFlag pretenure) {
2258 // Check if the string is an ASCII string.
2259 int i = 0;
2260 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2261
2262 Object* result;
2263 if (i == string.length()) { // It's an ASCII string.
2264 result = AllocateRawAsciiString(string.length(), pretenure);
2265 } else { // It's not an ASCII string.
2266 result = AllocateRawTwoByteString(string.length(), pretenure);
2267 }
2268 if (result->IsFailure()) return result;
2269
2270 // Copy the characters into the new object, which may be either ASCII or
2271 // UTF-16.
2272 String* string_result = String::cast(result);
2273 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002274 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002275 }
2276 return result;
2277}
2278
2279
2280Map* Heap::SymbolMapForString(String* string) {
2281 // If the string is in new space it cannot be used as a symbol.
2282 if (InNewSpace(string)) return NULL;
2283
2284 // Find the corresponding symbol map for strings.
2285 Map* map = string->map();
2286
2287 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2288 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2289 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2290
2291 if (map == short_string_map()) return short_symbol_map();
2292 if (map == medium_string_map()) return medium_symbol_map();
2293 if (map == long_string_map()) return long_symbol_map();
2294
2295 if (map == short_cons_string_map()) return short_cons_symbol_map();
2296 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2297 if (map == long_cons_string_map()) return long_cons_symbol_map();
2298
2299 if (map == short_cons_ascii_string_map()) {
2300 return short_cons_ascii_symbol_map();
2301 }
2302 if (map == medium_cons_ascii_string_map()) {
2303 return medium_cons_ascii_symbol_map();
2304 }
2305 if (map == long_cons_ascii_string_map()) {
2306 return long_cons_ascii_symbol_map();
2307 }
2308
2309 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002310 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2311 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002312
2313 if (map == short_sliced_ascii_string_map()) {
2314 return short_sliced_ascii_symbol_map();
2315 }
2316 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002317 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002318 }
2319 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002320 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002321 }
2322
ager@chromium.org6f10e412009-02-13 10:11:16 +00002323 if (map == short_external_string_map()) {
2324 return short_external_symbol_map();
2325 }
2326 if (map == medium_external_string_map()) {
2327 return medium_external_symbol_map();
2328 }
2329 if (map == long_external_string_map()) {
2330 return long_external_symbol_map();
2331 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002332
2333 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002334 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002335 }
2336 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002337 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002338 }
2339 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002340 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002341 }
2342
2343 // No match found.
2344 return NULL;
2345}
2346
2347
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002348Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2349 int chars,
2350 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002351 // Ensure the chars matches the number of characters in the buffer.
2352 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2353 // Determine whether the string is ascii.
2354 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002355 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002356 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2357 }
2358 buffer->Rewind();
2359
2360 // Compute map and object size.
2361 int size;
2362 Map* map;
2363
2364 if (is_ascii) {
2365 if (chars <= String::kMaxShortStringSize) {
2366 map = short_ascii_symbol_map();
2367 } else if (chars <= String::kMaxMediumStringSize) {
2368 map = medium_ascii_symbol_map();
2369 } else {
2370 map = long_ascii_symbol_map();
2371 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002372 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002373 } else {
2374 if (chars <= String::kMaxShortStringSize) {
2375 map = short_symbol_map();
2376 } else if (chars <= String::kMaxMediumStringSize) {
2377 map = medium_symbol_map();
2378 } else {
2379 map = long_symbol_map();
2380 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002381 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002382 }
2383
2384 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002385 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002386 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002387 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002388 if (result->IsFailure()) return result;
2389
2390 reinterpret_cast<HeapObject*>(result)->set_map(map);
2391 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002392 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002393 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002394
ager@chromium.org870a0b62008-11-04 11:43:05 +00002395 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002396
2397 // Fill in the characters.
2398 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002399 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002400 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002401 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002402}
2403
2404
2405Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002406 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002407 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002408
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002409 Object* result = Failure::OutOfMemoryException();
2410 if (space == NEW_SPACE) {
2411 result = size <= kMaxObjectSizeInNewSpace
2412 ? new_space_.AllocateRaw(size)
2413 : lo_space_->AllocateRawFixedArray(size);
2414 } else {
2415 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2416 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2417 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002418 if (result->IsFailure()) return result;
2419
2420 // Determine the map based on the string's length.
2421 Map* map;
2422 if (length <= String::kMaxShortStringSize) {
2423 map = short_ascii_string_map();
2424 } else if (length <= String::kMaxMediumStringSize) {
2425 map = medium_ascii_string_map();
2426 } else {
2427 map = long_ascii_string_map();
2428 }
2429
2430 // Partially initialize the object.
2431 HeapObject::cast(result)->set_map(map);
2432 String::cast(result)->set_length(length);
2433 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2434 return result;
2435}
2436
2437
2438Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002439 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002440 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002441
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002442 Object* result = Failure::OutOfMemoryException();
2443 if (space == NEW_SPACE) {
2444 result = size <= kMaxObjectSizeInNewSpace
2445 ? new_space_.AllocateRaw(size)
2446 : lo_space_->AllocateRawFixedArray(size);
2447 } else {
2448 if (size > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
2449 result = AllocateRaw(size, space, OLD_DATA_SPACE);
2450 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002451 if (result->IsFailure()) return result;
2452
2453 // Determine the map based on the string's length.
2454 Map* map;
2455 if (length <= String::kMaxShortStringSize) {
2456 map = short_string_map();
2457 } else if (length <= String::kMaxMediumStringSize) {
2458 map = medium_string_map();
2459 } else {
2460 map = long_string_map();
2461 }
2462
2463 // Partially initialize the object.
2464 HeapObject::cast(result)->set_map(map);
2465 String::cast(result)->set_length(length);
2466 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2467 return result;
2468}
2469
2470
2471Object* Heap::AllocateEmptyFixedArray() {
2472 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002473 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002474 if (result->IsFailure()) return result;
2475 // Initialize the object.
2476 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2477 reinterpret_cast<Array*>(result)->set_length(0);
2478 return result;
2479}
2480
2481
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002482Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002483 // Use the general function if we're forced to always allocate.
2484 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002485 // Allocate the raw data for a fixed array.
2486 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002487 return size <= kMaxObjectSizeInNewSpace
2488 ? new_space_.AllocateRaw(size)
2489 : lo_space_->AllocateRawFixedArray(size);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002490}
2491
2492
2493Object* Heap::CopyFixedArray(FixedArray* src) {
2494 int len = src->length();
2495 Object* obj = AllocateRawFixedArray(len);
2496 if (obj->IsFailure()) return obj;
2497 if (Heap::InNewSpace(obj)) {
2498 HeapObject* dst = HeapObject::cast(obj);
2499 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2500 reinterpret_cast<Object**>(src->address()),
2501 FixedArray::SizeFor(len));
2502 return obj;
2503 }
2504 HeapObject::cast(obj)->set_map(src->map());
2505 FixedArray* result = FixedArray::cast(obj);
2506 result->set_length(len);
2507 // Copy the content
2508 WriteBarrierMode mode = result->GetWriteBarrierMode();
2509 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2510 return result;
2511}
2512
2513
2514Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002515 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002516 Object* result = AllocateRawFixedArray(length);
2517 if (!result->IsFailure()) {
2518 // Initialize header.
2519 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2520 FixedArray* array = FixedArray::cast(result);
2521 array->set_length(length);
2522 Object* value = undefined_value();
2523 // Initialize body.
2524 for (int index = 0; index < length; index++) {
2525 array->set(index, value, SKIP_WRITE_BARRIER);
2526 }
2527 }
2528 return result;
2529}
2530
2531
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002532Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2533 ASSERT(empty_fixed_array()->IsFixedArray());
2534 if (length == 0) return empty_fixed_array();
2535
2536 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002537 Object* result = Failure::OutOfMemoryException();
2538 if (pretenure != TENURED) {
2539 result = size <= kMaxObjectSizeInNewSpace
2540 ? new_space_.AllocateRaw(size)
2541 : lo_space_->AllocateRawFixedArray(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002542 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002543 if (result->IsFailure()) {
2544 if (size > MaxObjectSizeInPagedSpace()) {
2545 result = lo_space_->AllocateRawFixedArray(size);
2546 } else {
2547 AllocationSpace space =
2548 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2549 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
2550 }
2551 if (result->IsFailure()) return result;
2552 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002553 // Initialize the object.
2554 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2555 FixedArray* array = FixedArray::cast(result);
2556 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002557 Object* value = undefined_value();
2558 for (int index = 0; index < length; index++) {
2559 array->set(index, value, SKIP_WRITE_BARRIER);
2560 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002561 return array;
2562}
2563
2564
2565Object* Heap::AllocateFixedArrayWithHoles(int length) {
2566 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002567 Object* result = AllocateRawFixedArray(length);
2568 if (!result->IsFailure()) {
2569 // Initialize header.
2570 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2571 FixedArray* array = FixedArray::cast(result);
2572 array->set_length(length);
2573 // Initialize body.
2574 Object* value = the_hole_value();
2575 for (int index = 0; index < length; index++) {
2576 array->set(index, value, SKIP_WRITE_BARRIER);
2577 }
2578 }
2579 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002580}
2581
2582
2583Object* Heap::AllocateHashTable(int length) {
2584 Object* result = Heap::AllocateFixedArray(length);
2585 if (result->IsFailure()) return result;
2586 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00002587 ASSERT(result->IsHashTable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002588 return result;
2589}
2590
2591
2592Object* Heap::AllocateGlobalContext() {
2593 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2594 if (result->IsFailure()) return result;
2595 Context* context = reinterpret_cast<Context*>(result);
2596 context->set_map(global_context_map());
2597 ASSERT(context->IsGlobalContext());
2598 ASSERT(result->IsContext());
2599 return result;
2600}
2601
2602
2603Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2604 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2605 Object* result = Heap::AllocateFixedArray(length);
2606 if (result->IsFailure()) return result;
2607 Context* context = reinterpret_cast<Context*>(result);
2608 context->set_map(context_map());
2609 context->set_closure(function);
2610 context->set_fcontext(context);
2611 context->set_previous(NULL);
2612 context->set_extension(NULL);
2613 context->set_global(function->context()->global());
2614 ASSERT(!context->IsGlobalContext());
2615 ASSERT(context->is_function_context());
2616 ASSERT(result->IsContext());
2617 return result;
2618}
2619
2620
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002621Object* Heap::AllocateWithContext(Context* previous,
2622 JSObject* extension,
2623 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002624 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2625 if (result->IsFailure()) return result;
2626 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002627 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002628 context->set_closure(previous->closure());
2629 context->set_fcontext(previous->fcontext());
2630 context->set_previous(previous);
2631 context->set_extension(extension);
2632 context->set_global(previous->global());
2633 ASSERT(!context->IsGlobalContext());
2634 ASSERT(!context->is_function_context());
2635 ASSERT(result->IsContext());
2636 return result;
2637}
2638
2639
2640Object* Heap::AllocateStruct(InstanceType type) {
2641 Map* map;
2642 switch (type) {
2643#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2644STRUCT_LIST(MAKE_CASE)
2645#undef MAKE_CASE
2646 default:
2647 UNREACHABLE();
2648 return Failure::InternalError();
2649 }
2650 int size = map->instance_size();
2651 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002652 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002653 Object* result = Heap::Allocate(map, space);
2654 if (result->IsFailure()) return result;
2655 Struct::cast(result)->InitializeBody(size);
2656 return result;
2657}
2658
2659
2660#ifdef DEBUG
2661
2662void Heap::Print() {
2663 if (!HasBeenSetup()) return;
2664 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002665 AllSpaces spaces;
2666 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002667}
2668
2669
2670void Heap::ReportCodeStatistics(const char* title) {
2671 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2672 PagedSpace::ResetCodeStatistics();
2673 // We do not look for code in new space, map space, or old space. If code
2674 // somehow ends up in those spaces, we would miss it here.
2675 code_space_->CollectCodeStatistics();
2676 lo_space_->CollectCodeStatistics();
2677 PagedSpace::ReportCodeStatistics();
2678}
2679
2680
2681// This function expects that NewSpace's allocated objects histogram is
2682// populated (via a call to CollectStatistics or else as a side effect of a
2683// just-completed scavenge collection).
2684void Heap::ReportHeapStatistics(const char* title) {
2685 USE(title);
2686 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2687 title, gc_count_);
2688 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002689 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2690 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002691
2692 PrintF("\n");
2693 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2694 GlobalHandles::PrintStats();
2695 PrintF("\n");
2696
2697 PrintF("Heap statistics : ");
2698 MemoryAllocator::ReportStatistics();
2699 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002700 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002701 PrintF("Old pointer space : ");
2702 old_pointer_space_->ReportStatistics();
2703 PrintF("Old data space : ");
2704 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002705 PrintF("Code space : ");
2706 code_space_->ReportStatistics();
2707 PrintF("Map space : ");
2708 map_space_->ReportStatistics();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002709 PrintF("Cell space : ");
2710 cell_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002711 PrintF("Large object space : ");
2712 lo_space_->ReportStatistics();
2713 PrintF(">>>>>> ========================================= >>>>>>\n");
2714}
2715
2716#endif // DEBUG
2717
2718bool Heap::Contains(HeapObject* value) {
2719 return Contains(value->address());
2720}
2721
2722
2723bool Heap::Contains(Address addr) {
2724 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2725 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002726 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002727 old_pointer_space_->Contains(addr) ||
2728 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002729 code_space_->Contains(addr) ||
2730 map_space_->Contains(addr) ||
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002731 cell_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002732 lo_space_->SlowContains(addr));
2733}
2734
2735
2736bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2737 return InSpace(value->address(), space);
2738}
2739
2740
2741bool Heap::InSpace(Address addr, AllocationSpace space) {
2742 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2743 if (!HasBeenSetup()) return false;
2744
2745 switch (space) {
2746 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002747 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002748 case OLD_POINTER_SPACE:
2749 return old_pointer_space_->Contains(addr);
2750 case OLD_DATA_SPACE:
2751 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002752 case CODE_SPACE:
2753 return code_space_->Contains(addr);
2754 case MAP_SPACE:
2755 return map_space_->Contains(addr);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002756 case CELL_SPACE:
2757 return cell_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002758 case LO_SPACE:
2759 return lo_space_->SlowContains(addr);
2760 }
2761
2762 return false;
2763}
2764
2765
2766#ifdef DEBUG
2767void Heap::Verify() {
2768 ASSERT(HasBeenSetup());
2769
2770 VerifyPointersVisitor visitor;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002771 IterateRoots(&visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002772
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002773 new_space_.Verify();
2774
2775 VerifyPointersAndRSetVisitor rset_visitor;
2776 old_pointer_space_->Verify(&rset_visitor);
2777 map_space_->Verify(&rset_visitor);
2778
2779 VerifyPointersVisitor no_rset_visitor;
2780 old_data_space_->Verify(&no_rset_visitor);
2781 code_space_->Verify(&no_rset_visitor);
2782 cell_space_->Verify(&no_rset_visitor);
2783
2784 lo_space_->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002785}
2786#endif // DEBUG
2787
2788
2789Object* Heap::LookupSymbol(Vector<const char> string) {
2790 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002791 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002792 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002793 // Can't use set_symbol_table because SymbolTable::cast knows that
2794 // SymbolTable is a singleton and checks for identity.
2795 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002796 ASSERT(symbol != NULL);
2797 return symbol;
2798}
2799
2800
2801Object* Heap::LookupSymbol(String* string) {
2802 if (string->IsSymbol()) return string;
2803 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002804 Object* new_table = symbol_table()->LookupString(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002805 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002806 // Can't use set_symbol_table because SymbolTable::cast knows that
2807 // SymbolTable is a singleton and checks for identity.
2808 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002809 ASSERT(symbol != NULL);
2810 return symbol;
2811}
2812
2813
ager@chromium.org7c537e22008-10-16 08:43:32 +00002814bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2815 if (string->IsSymbol()) {
2816 *symbol = string;
2817 return true;
2818 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002819 return symbol_table()->LookupSymbolIfExists(string, symbol);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002820}
2821
2822
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002823#ifdef DEBUG
2824void Heap::ZapFromSpace() {
2825 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002826 for (Address a = new_space_.FromSpaceLow();
2827 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002828 a += kPointerSize) {
2829 Memory::Address_at(a) = kFromSpaceZapValue;
2830 }
2831}
2832#endif // DEBUG
2833
2834
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002835int Heap::IterateRSetRange(Address object_start,
2836 Address object_end,
2837 Address rset_start,
2838 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002839 Address object_address = object_start;
2840 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002841 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002842
2843 // Loop over all the pointers in [object_start, object_end).
2844 while (object_address < object_end) {
2845 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002846 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002847 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002848 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002849 // Do not dereference pointers at or past object_end.
2850 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2851 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002852 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002853 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2854 }
2855 // If this pointer does not need to be remembered anymore, clear
2856 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002857 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002858 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002859 }
2860 object_address += kPointerSize;
2861 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002862 // Update the remembered set if it has changed.
2863 if (result_rset != rset_word) {
2864 Memory::uint32_at(rset_address) = result_rset;
2865 }
2866 } else {
2867 // No bits in the word were set. This is the common case.
2868 object_address += kPointerSize * kBitsPerInt;
2869 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002870 rset_address += kIntSize;
2871 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002872 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002873}
2874
2875
2876void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2877 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002878 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002879
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002880 static void* paged_rset_histogram = StatsTable::CreateHistogram(
2881 "V8.RSetPaged",
2882 0,
2883 Page::kObjectAreaSize / kPointerSize,
2884 30);
2885
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002886 PageIterator it(space, PageIterator::PAGES_IN_USE);
2887 while (it.has_next()) {
2888 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002889 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2890 page->RSetStart(), copy_object_func);
2891 if (paged_rset_histogram != NULL) {
2892 StatsTable::AddHistogramSample(paged_rset_histogram, count);
2893 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002894 }
2895}
2896
2897
2898#ifdef DEBUG
2899#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2900#else
2901#define SYNCHRONIZE_TAG(tag)
2902#endif
2903
2904void Heap::IterateRoots(ObjectVisitor* v) {
2905 IterateStrongRoots(v);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002906 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002907 SYNCHRONIZE_TAG("symbol_table");
2908}
2909
2910
2911void Heap::IterateStrongRoots(ObjectVisitor* v) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00002912 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002913 SYNCHRONIZE_TAG("strong_root_list");
2914
ager@chromium.org3b45ab52009-03-19 22:21:34 +00002915 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002916 SYNCHRONIZE_TAG("symbol");
2917
2918 Bootstrapper::Iterate(v);
2919 SYNCHRONIZE_TAG("bootstrapper");
2920 Top::Iterate(v);
2921 SYNCHRONIZE_TAG("top");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002922
2923#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002924 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002925#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002926 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002927 CompilationCache::Iterate(v);
2928 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002929
2930 // Iterate over local handles in handle scopes.
2931 HandleScopeImplementer::Iterate(v);
2932 SYNCHRONIZE_TAG("handlescope");
2933
2934 // Iterate over the builtin code objects and code stubs in the heap. Note
2935 // that it is not strictly necessary to iterate over code objects on
2936 // scavenge collections. We still do it here because this same function
2937 // is used by the mark-sweep collector and the deserializer.
2938 Builtins::IterateBuiltins(v);
2939 SYNCHRONIZE_TAG("builtins");
2940
2941 // Iterate over global handles.
2942 GlobalHandles::IterateRoots(v);
2943 SYNCHRONIZE_TAG("globalhandles");
2944
2945 // Iterate over pointers being held by inactive threads.
2946 ThreadManager::Iterate(v);
2947 SYNCHRONIZE_TAG("threadmanager");
2948}
2949#undef SYNCHRONIZE_TAG
2950
2951
2952// Flag is set when the heap has been configured. The heap can be repeatedly
2953// configured through the API until it is setup.
2954static bool heap_configured = false;
2955
2956// TODO(1236194): Since the heap size is configurable on the command line
2957// and through the API, we should gracefully handle the case that the heap
2958// size is not big enough to fit all the initial objects.
2959bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2960 if (HasBeenSetup()) return false;
2961
2962 if (semispace_size > 0) semispace_size_ = semispace_size;
2963 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2964
2965 // The new space size must be a power of two to support single-bit testing
2966 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002967 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002968 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2969 young_generation_size_ = 2 * semispace_size_;
2970
2971 // The old generation is paged.
2972 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2973
2974 heap_configured = true;
2975 return true;
2976}
2977
2978
kasper.lund7276f142008-07-30 08:49:36 +00002979bool Heap::ConfigureHeapDefault() {
2980 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2981}
2982
2983
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002984int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002985 return old_pointer_space_->Size()
2986 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002987 + code_space_->Size()
2988 + map_space_->Size()
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002989 + cell_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002990 + lo_space_->Size();
2991}
2992
2993
kasper.lund7276f142008-07-30 08:49:36 +00002994int Heap::PromotedExternalMemorySize() {
2995 if (amount_of_external_allocated_memory_
2996 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2997 return amount_of_external_allocated_memory_
2998 - amount_of_external_allocated_memory_at_last_global_gc_;
2999}
3000
3001
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003002bool Heap::Setup(bool create_heap_objects) {
3003 // Initialize heap spaces and initial maps and objects. Whenever something
3004 // goes wrong, just return false. The caller should check the results and
3005 // call Heap::TearDown() to release allocated memory.
3006 //
3007 // If the heap is not yet configured (eg, through the API), configure it.
3008 // Configuration is based on the flags new-space-size (really the semispace
3009 // size) and old-space-size if set or the initial values of semispace_size_
3010 // and old_generation_size_ otherwise.
3011 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00003012 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003013 }
3014
3015 // Setup memory allocator and allocate an initial chunk of memory. The
3016 // initial chunk is double the size of the new space to ensure that we can
3017 // find a pair of semispaces that are contiguous and aligned to their size.
3018 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
3019 void* chunk
3020 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
3021 if (chunk == NULL) return false;
3022
3023 // Put the initial chunk of the old space at the start of the initial
3024 // chunk, then the two new space semispaces, then the initial chunk of
3025 // code space. Align the pair of semispaces to their size, which must be
3026 // a power of 2.
3027 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003028 Address code_space_start = reinterpret_cast<Address>(chunk);
3029 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
3030 Address old_space_start = new_space_start + young_generation_size_;
3031 int code_space_size = new_space_start - code_space_start;
3032 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003033
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003034 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003035 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003036
3037 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00003038 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003039 old_pointer_space_ =
3040 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
3041 if (old_pointer_space_ == NULL) return false;
3042 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
3043 return false;
3044 }
3045 old_data_space_ =
3046 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
3047 if (old_data_space_ == NULL) return false;
3048 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
3049 old_space_size >> 1)) {
3050 return false;
3051 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003052
3053 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00003054 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003055 code_space_ =
3056 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003057 if (code_space_ == NULL) return false;
3058 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
3059
3060 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00003061 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003062 if (map_space_ == NULL) return false;
3063 // Setting up a paged space without giving it a virtual memory range big
3064 // enough to hold at least a page will cause it to allocate.
3065 if (!map_space_->Setup(NULL, 0)) return false;
3066
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003067 // Initialize global property cell space.
3068 cell_space_ = new CellSpace(old_generation_size_, CELL_SPACE);
3069 if (cell_space_ == NULL) return false;
3070 // Setting up a paged space without giving it a virtual memory range big
3071 // enough to hold at least a page will cause it to allocate.
3072 if (!cell_space_->Setup(NULL, 0)) return false;
3073
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003074 // The large object code space may contain code or data. We set the memory
3075 // to be non-executable here for safety, but this means we need to enable it
3076 // explicitly when allocating large code objects.
3077 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003078 if (lo_space_ == NULL) return false;
3079 if (!lo_space_->Setup()) return false;
3080
3081 if (create_heap_objects) {
3082 // Create initial maps.
3083 if (!CreateInitialMaps()) return false;
3084 if (!CreateApiObjects()) return false;
3085
3086 // Create initial objects
3087 if (!CreateInitialObjects()) return false;
3088 }
3089
3090 LOG(IntEvent("heap-capacity", Capacity()));
3091 LOG(IntEvent("heap-available", Available()));
3092
3093 return true;
3094}
3095
3096
3097void Heap::TearDown() {
3098 GlobalHandles::TearDown();
3099
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003100 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003101
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003102 if (old_pointer_space_ != NULL) {
3103 old_pointer_space_->TearDown();
3104 delete old_pointer_space_;
3105 old_pointer_space_ = NULL;
3106 }
3107
3108 if (old_data_space_ != NULL) {
3109 old_data_space_->TearDown();
3110 delete old_data_space_;
3111 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003112 }
3113
3114 if (code_space_ != NULL) {
3115 code_space_->TearDown();
3116 delete code_space_;
3117 code_space_ = NULL;
3118 }
3119
3120 if (map_space_ != NULL) {
3121 map_space_->TearDown();
3122 delete map_space_;
3123 map_space_ = NULL;
3124 }
3125
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003126 if (cell_space_ != NULL) {
3127 cell_space_->TearDown();
3128 delete cell_space_;
3129 cell_space_ = NULL;
3130 }
3131
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003132 if (lo_space_ != NULL) {
3133 lo_space_->TearDown();
3134 delete lo_space_;
3135 lo_space_ = NULL;
3136 }
3137
3138 MemoryAllocator::TearDown();
3139}
3140
3141
3142void Heap::Shrink() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003143 // Try to shrink all paged spaces.
3144 PagedSpaces spaces;
3145 while (PagedSpace* space = spaces.next()) space->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003146}
3147
3148
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003149#ifdef ENABLE_HEAP_PROTECTION
3150
3151void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003152 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003153 AllSpaces spaces;
3154 while (Space* space = spaces.next()) space->Protect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003155 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003156}
3157
3158
3159void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003160 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003161 AllSpaces spaces;
3162 while (Space* space = spaces.next()) space->Unprotect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003163 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003164}
3165
3166#endif
3167
3168
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003169#ifdef DEBUG
3170
3171class PrintHandleVisitor: public ObjectVisitor {
3172 public:
3173 void VisitPointers(Object** start, Object** end) {
3174 for (Object** p = start; p < end; p++)
3175 PrintF(" handle %p to %p\n", p, *p);
3176 }
3177};
3178
3179void Heap::PrintHandles() {
3180 PrintF("Handles:\n");
3181 PrintHandleVisitor v;
3182 HandleScopeImplementer::Iterate(&v);
3183}
3184
3185#endif
3186
3187
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003188Space* AllSpaces::next() {
3189 switch (counter_++) {
3190 case NEW_SPACE:
3191 return Heap::new_space();
3192 case OLD_POINTER_SPACE:
3193 return Heap::old_pointer_space();
3194 case OLD_DATA_SPACE:
3195 return Heap::old_data_space();
3196 case CODE_SPACE:
3197 return Heap::code_space();
3198 case MAP_SPACE:
3199 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003200 case CELL_SPACE:
3201 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003202 case LO_SPACE:
3203 return Heap::lo_space();
3204 default:
3205 return NULL;
3206 }
3207}
3208
3209
3210PagedSpace* PagedSpaces::next() {
3211 switch (counter_++) {
3212 case OLD_POINTER_SPACE:
3213 return Heap::old_pointer_space();
3214 case OLD_DATA_SPACE:
3215 return Heap::old_data_space();
3216 case CODE_SPACE:
3217 return Heap::code_space();
3218 case MAP_SPACE:
3219 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003220 case CELL_SPACE:
3221 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003222 default:
3223 return NULL;
3224 }
3225}
3226
3227
3228
3229OldSpace* OldSpaces::next() {
3230 switch (counter_++) {
3231 case OLD_POINTER_SPACE:
3232 return Heap::old_pointer_space();
3233 case OLD_DATA_SPACE:
3234 return Heap::old_data_space();
3235 case CODE_SPACE:
3236 return Heap::code_space();
3237 default:
3238 return NULL;
3239 }
3240}
3241
3242
kasper.lund7276f142008-07-30 08:49:36 +00003243SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3244}
3245
3246
3247SpaceIterator::~SpaceIterator() {
3248 // Delete active iterator if any.
3249 delete iterator_;
3250}
3251
3252
3253bool SpaceIterator::has_next() {
3254 // Iterate until no more spaces.
3255 return current_space_ != LAST_SPACE;
3256}
3257
3258
3259ObjectIterator* SpaceIterator::next() {
3260 if (iterator_ != NULL) {
3261 delete iterator_;
3262 iterator_ = NULL;
3263 // Move to the next space
3264 current_space_++;
3265 if (current_space_ > LAST_SPACE) {
3266 return NULL;
3267 }
3268 }
3269
3270 // Return iterator for the new current space.
3271 return CreateIterator();
3272}
3273
3274
3275// Create an iterator for the space to iterate.
3276ObjectIterator* SpaceIterator::CreateIterator() {
3277 ASSERT(iterator_ == NULL);
3278
3279 switch (current_space_) {
3280 case NEW_SPACE:
3281 iterator_ = new SemiSpaceIterator(Heap::new_space());
3282 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003283 case OLD_POINTER_SPACE:
3284 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3285 break;
3286 case OLD_DATA_SPACE:
3287 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003288 break;
3289 case CODE_SPACE:
3290 iterator_ = new HeapObjectIterator(Heap::code_space());
3291 break;
3292 case MAP_SPACE:
3293 iterator_ = new HeapObjectIterator(Heap::map_space());
3294 break;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003295 case CELL_SPACE:
3296 iterator_ = new HeapObjectIterator(Heap::cell_space());
3297 break;
kasper.lund7276f142008-07-30 08:49:36 +00003298 case LO_SPACE:
3299 iterator_ = new LargeObjectIterator(Heap::lo_space());
3300 break;
3301 }
3302
3303 // Return the newly allocated iterator;
3304 ASSERT(iterator_ != NULL);
3305 return iterator_;
3306}
3307
3308
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003309HeapIterator::HeapIterator() {
3310 Init();
3311}
3312
3313
3314HeapIterator::~HeapIterator() {
3315 Shutdown();
3316}
3317
3318
3319void HeapIterator::Init() {
3320 // Start the iteration.
3321 space_iterator_ = new SpaceIterator();
3322 object_iterator_ = space_iterator_->next();
3323}
3324
3325
3326void HeapIterator::Shutdown() {
3327 // Make sure the last iterator is deallocated.
3328 delete space_iterator_;
3329 space_iterator_ = NULL;
3330 object_iterator_ = NULL;
3331}
3332
3333
3334bool HeapIterator::has_next() {
3335 // No iterator means we are done.
3336 if (object_iterator_ == NULL) return false;
3337
3338 if (object_iterator_->has_next_object()) {
3339 // If the current iterator has more objects we are fine.
3340 return true;
3341 } else {
3342 // Go though the spaces looking for one that has objects.
3343 while (space_iterator_->has_next()) {
3344 object_iterator_ = space_iterator_->next();
3345 if (object_iterator_->has_next_object()) {
3346 return true;
3347 }
3348 }
3349 }
3350 // Done with the last space.
3351 object_iterator_ = NULL;
3352 return false;
3353}
3354
3355
3356HeapObject* HeapIterator::next() {
3357 if (has_next()) {
3358 return object_iterator_->next_object();
3359 } else {
3360 return NULL;
3361 }
3362}
3363
3364
3365void HeapIterator::reset() {
3366 // Restart the iterator.
3367 Shutdown();
3368 Init();
3369}
3370
3371
3372//
3373// HeapProfiler class implementation.
3374//
3375#ifdef ENABLE_LOGGING_AND_PROFILING
3376void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3377 InstanceType type = obj->map()->instance_type();
3378 ASSERT(0 <= type && type <= LAST_TYPE);
3379 info[type].increment_number(1);
3380 info[type].increment_bytes(obj->Size());
3381}
3382#endif
3383
3384
3385#ifdef ENABLE_LOGGING_AND_PROFILING
3386void HeapProfiler::WriteSample() {
3387 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3388
3389 HistogramInfo info[LAST_TYPE+1];
3390#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3391 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3392#undef DEF_TYPE_NAME
3393
3394 HeapIterator iterator;
3395 while (iterator.has_next()) {
3396 CollectStats(iterator.next(), info);
3397 }
3398
3399 // Lump all the string types together.
3400 int string_number = 0;
3401 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003402#define INCREMENT_SIZE(type, size, name, camel_name) \
3403 string_number += info[type].number(); \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003404 string_bytes += info[type].bytes();
3405 STRING_TYPE_LIST(INCREMENT_SIZE)
3406#undef INCREMENT_SIZE
3407 if (string_bytes > 0) {
3408 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3409 }
3410
3411 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3412 if (info[i].bytes() > 0) {
3413 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3414 info[i].bytes()));
3415 }
3416 }
3417
3418 LOG(HeapSampleEndEvent("Heap", "allocated"));
3419}
3420
3421
3422#endif
3423
3424
3425
3426#ifdef DEBUG
3427
3428static bool search_for_any_global;
3429static Object* search_target;
3430static bool found_target;
3431static List<Object*> object_stack(20);
3432
3433
3434// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3435static const int kMarkTag = 2;
3436
3437static void MarkObjectRecursively(Object** p);
3438class MarkObjectVisitor : public ObjectVisitor {
3439 public:
3440 void VisitPointers(Object** start, Object** end) {
3441 // Copy all HeapObject pointers in [start, end)
3442 for (Object** p = start; p < end; p++) {
3443 if ((*p)->IsHeapObject())
3444 MarkObjectRecursively(p);
3445 }
3446 }
3447};
3448
3449static MarkObjectVisitor mark_visitor;
3450
3451static void MarkObjectRecursively(Object** p) {
3452 if (!(*p)->IsHeapObject()) return;
3453
3454 HeapObject* obj = HeapObject::cast(*p);
3455
3456 Object* map = obj->map();
3457
3458 if (!map->IsHeapObject()) return; // visited before
3459
3460 if (found_target) return; // stop if target found
3461 object_stack.Add(obj);
3462 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3463 (!search_for_any_global && (obj == search_target))) {
3464 found_target = true;
3465 return;
3466 }
3467
3468 if (obj->IsCode()) {
3469 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3470 }
3471
3472 // not visited yet
3473 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3474
3475 Address map_addr = map_p->address();
3476
3477 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3478
3479 MarkObjectRecursively(&map);
3480
3481 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3482 &mark_visitor);
3483
3484 if (!found_target) // don't pop if found the target
3485 object_stack.RemoveLast();
3486}
3487
3488
3489static void UnmarkObjectRecursively(Object** p);
3490class UnmarkObjectVisitor : public ObjectVisitor {
3491 public:
3492 void VisitPointers(Object** start, Object** end) {
3493 // Copy all HeapObject pointers in [start, end)
3494 for (Object** p = start; p < end; p++) {
3495 if ((*p)->IsHeapObject())
3496 UnmarkObjectRecursively(p);
3497 }
3498 }
3499};
3500
3501static UnmarkObjectVisitor unmark_visitor;
3502
3503static void UnmarkObjectRecursively(Object** p) {
3504 if (!(*p)->IsHeapObject()) return;
3505
3506 HeapObject* obj = HeapObject::cast(*p);
3507
3508 Object* map = obj->map();
3509
3510 if (map->IsHeapObject()) return; // unmarked already
3511
3512 Address map_addr = reinterpret_cast<Address>(map);
3513
3514 map_addr -= kMarkTag;
3515
3516 ASSERT_TAG_ALIGNED(map_addr);
3517
3518 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3519
3520 obj->set_map(reinterpret_cast<Map*>(map_p));
3521
3522 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3523
3524 obj->IterateBody(Map::cast(map_p)->instance_type(),
3525 obj->SizeFromMap(Map::cast(map_p)),
3526 &unmark_visitor);
3527
3528 if (obj->IsCode()) {
3529 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3530 }
3531}
3532
3533
3534static void MarkRootObjectRecursively(Object** root) {
3535 if (search_for_any_global) {
3536 ASSERT(search_target == NULL);
3537 } else {
3538 ASSERT(search_target->IsHeapObject());
3539 }
3540 found_target = false;
3541 object_stack.Clear();
3542
3543 MarkObjectRecursively(root);
3544 UnmarkObjectRecursively(root);
3545
3546 if (found_target) {
3547 PrintF("=====================================\n");
3548 PrintF("==== Path to object ====\n");
3549 PrintF("=====================================\n\n");
3550
3551 ASSERT(!object_stack.is_empty());
3552 for (int i = 0; i < object_stack.length(); i++) {
3553 if (i > 0) PrintF("\n |\n |\n V\n\n");
3554 Object* obj = object_stack[i];
3555 obj->Print();
3556 }
3557 PrintF("=====================================\n");
3558 }
3559}
3560
3561
3562// Helper class for visiting HeapObjects recursively.
3563class MarkRootVisitor: public ObjectVisitor {
3564 public:
3565 void VisitPointers(Object** start, Object** end) {
3566 // Visit all HeapObject pointers in [start, end)
3567 for (Object** p = start; p < end; p++) {
3568 if ((*p)->IsHeapObject())
3569 MarkRootObjectRecursively(p);
3570 }
3571 }
3572};
3573
3574
3575// Triggers a depth-first traversal of reachable objects from roots
3576// and finds a path to a specific heap object and prints it.
3577void Heap::TracePathToObject() {
3578 search_target = NULL;
3579 search_for_any_global = false;
3580
3581 MarkRootVisitor root_visitor;
3582 IterateRoots(&root_visitor);
3583}
3584
3585
3586// Triggers a depth-first traversal of reachable objects from roots
3587// and finds a path to any global object and prints it. Useful for
3588// determining the source for leaks of global objects.
3589void Heap::TracePathToGlobal() {
3590 search_target = NULL;
3591 search_for_any_global = true;
3592
3593 MarkRootVisitor root_visitor;
3594 IterateRoots(&root_visitor);
3595}
3596#endif
3597
3598
kasper.lund7276f142008-07-30 08:49:36 +00003599GCTracer::GCTracer()
3600 : start_time_(0.0),
3601 start_size_(0.0),
3602 gc_count_(0),
3603 full_gc_count_(0),
3604 is_compacting_(false),
3605 marked_count_(0) {
3606 // These two fields reflect the state of the previous full collection.
3607 // Set them before they are changed by the collector.
3608 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3609 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3610 if (!FLAG_trace_gc) return;
3611 start_time_ = OS::TimeCurrentMillis();
3612 start_size_ = SizeOfHeapObjects();
3613}
3614
3615
3616GCTracer::~GCTracer() {
3617 if (!FLAG_trace_gc) return;
3618 // Printf ONE line iff flag is set.
3619 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3620 CollectorString(),
3621 start_size_, SizeOfHeapObjects(),
3622 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3623}
3624
3625
3626const char* GCTracer::CollectorString() {
3627 switch (collector_) {
3628 case SCAVENGER:
3629 return "Scavenge";
3630 case MARK_COMPACTOR:
3631 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3632 : "Mark-sweep";
3633 }
3634 return "Unknown GC";
3635}
3636
3637
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003638int KeyedLookupCache::Hash(Map* map, String* name) {
3639 // Uses only lower 32 bits if pointers are larger.
3640 uintptr_t addr_hash =
3641 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> 2;
3642 return (addr_hash ^ name->Hash()) % kLength;
3643}
3644
3645
3646int KeyedLookupCache::Lookup(Map* map, String* name) {
3647 int index = Hash(map, name);
3648 Key& key = keys_[index];
3649 if ((key.map == map) && key.name->Equals(name)) {
3650 return field_offsets_[index];
3651 }
3652 return -1;
3653}
3654
3655
3656void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
3657 String* symbol;
3658 if (Heap::LookupSymbolIfExists(name, &symbol)) {
3659 int index = Hash(map, symbol);
3660 Key& key = keys_[index];
3661 key.map = map;
3662 key.name = symbol;
3663 field_offsets_[index] = field_offset;
3664 }
3665}
3666
3667
3668void KeyedLookupCache::Clear() {
3669 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
3670}
3671
3672
3673KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
3674
3675
3676int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
3677
3678
3679void DescriptorLookupCache::Clear() {
3680 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
3681}
3682
3683
3684DescriptorLookupCache::Key
3685DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
3686
3687int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
3688
3689
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003690#ifdef DEBUG
3691bool Heap::GarbageCollectionGreedyCheck() {
3692 ASSERT(FLAG_gc_greedy);
3693 if (Bootstrapper::IsActive()) return true;
3694 if (disallow_allocation_failure()) return true;
3695 return CollectGarbage(0, NEW_SPACE);
3696}
3697#endif
3698
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003699} } // namespace v8::internal