blob: eb70f21a809961c3ec7c50a34a85154983fa4fb4 [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#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
47 ROOT_LIST(ROOT_ALLOCATION)
48#undef ROOT_ALLOCATION
49
50
51#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
52 STRUCT_LIST(STRUCT_ALLOCATION)
53#undef STRUCT_ALLOCATION
54
55
56#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
57 SYMBOL_LIST(SYMBOL_ALLOCATION)
58#undef SYMBOL_ALLOCATION
59
ager@chromium.org3b45ab52009-03-19 22:21:34 +000060String* Heap::hidden_symbol_;
61
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000062NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000063OldSpace* Heap::old_pointer_space_ = NULL;
64OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065OldSpace* Heap::code_space_ = NULL;
66MapSpace* Heap::map_space_ = NULL;
67LargeObjectSpace* Heap::lo_space_ = NULL;
68
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000069static const int kMinimumPromotionLimit = 2*MB;
70static const int kMinimumAllocationLimit = 8*MB;
71
72int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
73int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
74
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000075int Heap::old_gen_exhausted_ = false;
76
kasper.lund7276f142008-07-30 08:49:36 +000077int Heap::amount_of_external_allocated_memory_ = 0;
78int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
79
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000080// semispace_size_ should be a power of 2 and old_generation_size_ should be
81// a multiple of Page::kPageSize.
ager@chromium.orgeadaf222009-06-16 09:43:10 +000082#if V8_HOST_ARCH_ARM
83int Heap::semispace_size_ = 512*KB;
84int Heap::old_generation_size_ = 128*MB;
85int Heap::initial_semispace_size_ = 128*KB;
86#else
87int Heap::semispace_size_ = 8*MB;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000088int Heap::old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000089int Heap::initial_semispace_size_ = 512*KB;
90#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000091
92GCCallback Heap::global_gc_prologue_callback_ = NULL;
93GCCallback Heap::global_gc_epilogue_callback_ = NULL;
94
95// Variables set based on semispace_size_ and old_generation_size_ in
96// ConfigureHeap.
97int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
98
ager@chromium.orgeadaf222009-06-16 09:43:10 +000099int Heap::survived_since_last_expansion_ = 0;
100
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000101Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
102
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000103int Heap::mc_count_ = 0;
104int Heap::gc_count_ = 0;
105
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000106int Heap::always_allocate_scope_depth_ = 0;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000107bool Heap::context_disposed_pending_ = false;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000108
kasper.lund7276f142008-07-30 08:49:36 +0000109#ifdef DEBUG
110bool Heap::allocation_allowed_ = true;
111
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000112int Heap::allocation_timeout_ = 0;
113bool Heap::disallow_allocation_failure_ = false;
114#endif // DEBUG
115
116
117int Heap::Capacity() {
118 if (!HasBeenSetup()) return 0;
119
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000120 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000121 old_pointer_space_->Capacity() +
122 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 code_space_->Capacity() +
124 map_space_->Capacity();
125}
126
127
128int Heap::Available() {
129 if (!HasBeenSetup()) return 0;
130
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000131 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000132 old_pointer_space_->Available() +
133 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000134 code_space_->Available() +
135 map_space_->Available();
136}
137
138
139bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000140 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000141 old_data_space_ != NULL &&
142 code_space_ != NULL &&
143 map_space_ != NULL &&
144 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000145}
146
147
148GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
149 // Is global GC requested?
150 if (space != NEW_SPACE || FLAG_gc_global) {
151 Counters::gc_compactor_caused_by_request.Increment();
152 return MARK_COMPACTOR;
153 }
154
155 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000156 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000157 Counters::gc_compactor_caused_by_promoted_data.Increment();
158 return MARK_COMPACTOR;
159 }
160
161 // Have allocation in OLD and LO failed?
162 if (old_gen_exhausted_) {
163 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
164 return MARK_COMPACTOR;
165 }
166
167 // Is there enough space left in OLD to guarantee that a scavenge can
168 // succeed?
169 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000170 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000171 // for object promotion. It counts only the bytes that the memory
172 // allocator has not yet allocated from the OS and assigned to any space,
173 // and does not count available bytes already in the old space or code
174 // space. Undercounting is safe---we may get an unrequested full GC when
175 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000176 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000177 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
178 return MARK_COMPACTOR;
179 }
180
181 // Default
182 return SCAVENGER;
183}
184
185
186// TODO(1238405): Combine the infrastructure for --heap-stats and
187// --log-gc to avoid the complicated preprocessor and flag testing.
188#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
189void Heap::ReportStatisticsBeforeGC() {
190 // Heap::ReportHeapStatistics will also log NewSpace statistics when
191 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
192 // following logic is used to avoid double logging.
193#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000194 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000195 if (FLAG_heap_stats) {
196 ReportHeapStatistics("Before GC");
197 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000198 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000199 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000200 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000201#elif defined(DEBUG)
202 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000203 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000205 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000206 }
207#elif defined(ENABLE_LOGGING_AND_PROFILING)
208 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000209 new_space_.CollectStatistics();
210 new_space_.ReportStatistics();
211 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000212 }
213#endif
214}
215
216
217// TODO(1238405): Combine the infrastructure for --heap-stats and
218// --log-gc to avoid the complicated preprocessor and flag testing.
219void Heap::ReportStatisticsAfterGC() {
220 // Similar to the before GC, we use some complicated logic to ensure that
221 // NewSpace statistics are logged exactly once when --log-gc is turned on.
222#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
223 if (FLAG_heap_stats) {
224 ReportHeapStatistics("After GC");
225 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000226 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000227 }
228#elif defined(DEBUG)
229 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
230#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000231 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232#endif
233}
234#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
235
236
237void Heap::GarbageCollectionPrologue() {
kasper.lund7276f142008-07-30 08:49:36 +0000238 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239#ifdef DEBUG
240 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
241 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000242
243 if (FLAG_verify_heap) {
244 Verify();
245 }
246
247 if (FLAG_gc_verbose) Print();
248
249 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000250 // Not all spaces have remembered set bits that we care about.
251 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000252 map_space_->PrintRSet();
253 lo_space_->PrintRSet();
254 }
255#endif
256
257#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
258 ReportStatisticsBeforeGC();
259#endif
260}
261
262int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000263 int total = 0;
264 AllSpaces spaces;
265 while (Space* space = spaces.next()) total += space->Size();
266 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000267}
268
269void Heap::GarbageCollectionEpilogue() {
270#ifdef DEBUG
271 allow_allocation(true);
272 ZapFromSpace();
273
274 if (FLAG_verify_heap) {
275 Verify();
276 }
277
278 if (FLAG_print_global_handles) GlobalHandles::Print();
279 if (FLAG_print_handles) PrintHandles();
280 if (FLAG_gc_verbose) Print();
281 if (FLAG_code_stats) ReportCodeStatistics("After GC");
282#endif
283
284 Counters::alive_after_last_gc.Set(SizeOfObjects());
285
286 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
287 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
288 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
289#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
290 ReportStatisticsAfterGC();
291#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000292#ifdef ENABLE_DEBUGGER_SUPPORT
293 Debug::AfterGarbageCollection();
294#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000295}
296
297
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000298void Heap::CollectAllGarbage() {
299 // Since we are ignoring the return value, the exact choice of space does
300 // not matter, so long as we do not specify NEW_SPACE, which would not
301 // cause a full GC.
302 CollectGarbage(0, OLD_POINTER_SPACE);
303}
304
305
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000306void Heap::CollectAllGarbageIfContextDisposed() {
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000307 // If the garbage collector interface is exposed through the global
308 // gc() function, we avoid being clever about forcing GCs when
309 // contexts are disposed and leave it to the embedder to make
310 // informed decisions about when to force a collection.
311 if (!FLAG_expose_gc && context_disposed_pending_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000312 HistogramTimerScope scope(&Counters::gc_context);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000313 CollectAllGarbage();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000314 }
kasperl@chromium.orgd55d36b2009-03-05 08:03:28 +0000315 context_disposed_pending_ = false;
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000316}
317
318
319void Heap::NotifyContextDisposed() {
320 context_disposed_pending_ = true;
321}
322
323
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
325 // The VM is in the GC state until exiting this function.
326 VMState state(GC);
327
328#ifdef DEBUG
329 // Reset the allocation timeout to the GC interval, but make sure to
330 // allow at least a few allocations after a collection. The reason
331 // for this is that we have a lot of allocation sequences and we
332 // assume that a garbage collection will allow the subsequent
333 // allocation attempts to go through.
334 allocation_timeout_ = Max(6, FLAG_gc_interval);
335#endif
336
337 { GCTracer tracer;
338 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000339 // The GC count was incremented in the prologue. Tell the tracer about
340 // it.
341 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342
343 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000344 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000345 tracer.set_collector(collector);
346
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000347 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000348 ? &Counters::gc_scavenger
349 : &Counters::gc_compactor;
350 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000351 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000352 rate->Stop();
353
354 GarbageCollectionEpilogue();
355 }
356
357
358#ifdef ENABLE_LOGGING_AND_PROFILING
359 if (FLAG_log_gc) HeapProfiler::WriteSample();
360#endif
361
362 switch (space) {
363 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000364 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000365 case OLD_POINTER_SPACE:
366 return old_pointer_space_->Available() >= requested_size;
367 case OLD_DATA_SPACE:
368 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369 case CODE_SPACE:
370 return code_space_->Available() >= requested_size;
371 case MAP_SPACE:
372 return map_space_->Available() >= requested_size;
373 case LO_SPACE:
374 return lo_space_->Available() >= requested_size;
375 }
376 return false;
377}
378
379
kasper.lund7276f142008-07-30 08:49:36 +0000380void Heap::PerformScavenge() {
381 GCTracer tracer;
382 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
383}
384
385
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000386#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000387// Helper class for verifying the symbol table.
388class SymbolTableVerifier : public ObjectVisitor {
389 public:
390 SymbolTableVerifier() { }
391 void VisitPointers(Object** start, Object** end) {
392 // Visit all HeapObject pointers in [start, end).
393 for (Object** p = start; p < end; p++) {
394 if ((*p)->IsHeapObject()) {
395 // Check that the symbol is actually a symbol.
396 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000397 }
398 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000399 }
400};
401#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000402
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000403
404static void VerifySymbolTable() {
405#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000406 SymbolTableVerifier verifier;
407 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table());
408 symbol_table->IterateElements(&verifier);
409#endif // DEBUG
410}
411
412
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000413void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000414 GarbageCollector collector,
415 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000416 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
418 ASSERT(!allocation_allowed_);
419 global_gc_prologue_callback_();
420 }
421
422 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000423 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000424
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000425 int old_gen_size = PromotedSpaceSize();
426 old_gen_promotion_limit_ =
427 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
428 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000429 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000430 old_gen_exhausted_ = false;
431
432 // If we have used the mark-compact collector to collect the new
433 // space, and it has not compacted the new space, we force a
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000434 // separate scavenge collection. This is a hack. It covers the
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000435 // case where (1) a new space collection was requested, (2) the
436 // collector selection policy selected the mark-compact collector,
437 // and (3) the mark-compact collector policy selected not to
438 // compact the new space. In that case, there is no more (usable)
439 // free space in the new space after the collection compared to
440 // before.
441 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
442 Scavenge();
443 }
444 } else {
445 Scavenge();
446 }
447 Counters::objs_since_last_young.Set(0);
448
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000449 PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450
kasper.lund7276f142008-07-30 08:49:36 +0000451 if (collector == MARK_COMPACTOR) {
452 // Register the amount of external allocated memory.
453 amount_of_external_allocated_memory_at_last_global_gc_ =
454 amount_of_external_allocated_memory_;
455 }
456
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000457 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
458 ASSERT(!allocation_allowed_);
459 global_gc_epilogue_callback_();
460 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000461 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000462}
463
464
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000465void Heap::PostGarbageCollectionProcessing() {
466 // Process weak handles post gc.
467 GlobalHandles::PostGarbageCollectionProcessing();
468 // Update flat string readers.
469 FlatStringReader::PostGarbageCollectionProcessing();
470}
471
472
kasper.lund7276f142008-07-30 08:49:36 +0000473void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000475 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000476 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477 LOG(ResourceEvent("markcompact", "begin"));
478
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000479 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000481 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000483 MarkCompactPrologue(is_compacting);
484
485 MarkCompactCollector::CollectGarbage();
486
487 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000488
489 LOG(ResourceEvent("markcompact", "end"));
490
491 gc_state_ = NOT_IN_GC;
492
493 Shrink();
494
495 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000496 context_disposed_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000497}
498
499
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000500void Heap::MarkCompactPrologue(bool is_compacting) {
501 // At any old GC clear the keyed lookup cache to enable collection of unused
502 // maps.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000503 ClearKeyedLookupCache();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000504
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000505 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000506
507 Top::MarkCompactPrologue(is_compacting);
508 ThreadManager::MarkCompactPrologue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000509}
510
511
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000512void Heap::MarkCompactEpilogue(bool is_compacting) {
513 Top::MarkCompactEpilogue(is_compacting);
514 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515}
516
517
518Object* Heap::FindCodeObject(Address a) {
519 Object* obj = code_space_->FindObject(a);
520 if (obj->IsFailure()) {
521 obj = lo_space_->FindObject(a);
522 }
kasper.lund7276f142008-07-30 08:49:36 +0000523 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524 return obj;
525}
526
527
528// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000529class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000530 public:
531
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000532 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000533
534 void VisitPointers(Object** start, Object** end) {
535 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000536 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000537 }
538
539 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000540 void ScavengePointer(Object** p) {
541 Object* object = *p;
542 if (!Heap::InNewSpace(object)) return;
543 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
544 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000545 }
546};
547
548
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000549// A queue of pointers and maps of to-be-promoted objects during a
550// scavenge collection.
551class PromotionQueue {
552 public:
553 void Initialize(Address start_address) {
554 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
555 }
556
557 bool is_empty() { return front_ <= rear_; }
558
559 void insert(HeapObject* object, Map* map) {
560 *(--rear_) = object;
561 *(--rear_) = map;
562 // Assert no overflow into live objects.
563 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
564 }
565
566 void remove(HeapObject** object, Map** map) {
567 *object = *(--front_);
568 *map = Map::cast(*(--front_));
569 // Assert no underflow.
570 ASSERT(front_ >= rear_);
571 }
572
573 private:
574 // The front of the queue is higher in memory than the rear.
575 HeapObject** front_;
576 HeapObject** rear_;
577};
578
579
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000580// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000581static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000582
583
584#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000585// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000586// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000587class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000588 public:
589 void VisitPointers(Object** start, Object**end) {
590 for (Object** current = start; current < end; current++) {
591 if ((*current)->IsHeapObject()) {
592 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
593 }
594 }
595 }
596};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000597
598
599static void VerifyNonPointerSpacePointers() {
600 // Verify that there are no pointers to new space in spaces where we
601 // do not expect them.
602 VerifyNonPointerSpacePointersVisitor v;
603 HeapObjectIterator code_it(Heap::code_space());
604 while (code_it.has_next()) {
605 HeapObject* object = code_it.next();
606 if (object->IsCode()) {
607 Code::cast(object)->ConvertICTargetsFromAddressToObject();
608 object->Iterate(&v);
609 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
610 } else {
611 // If we find non-code objects in code space (e.g., free list
612 // nodes) we want to verify them as well.
613 object->Iterate(&v);
614 }
615 }
616
617 HeapObjectIterator data_it(Heap::old_data_space());
618 while (data_it.has_next()) data_it.next()->Iterate(&v);
619}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000620#endif
621
622void Heap::Scavenge() {
623#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000624 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625#endif
626
627 gc_state_ = SCAVENGE;
628
629 // Implements Cheney's copying algorithm
630 LOG(ResourceEvent("scavenge", "begin"));
631
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000632 // Used for updating survived_since_last_expansion_ at function end.
633 int survived_watermark = PromotedSpaceSize();
634
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000635 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000636 survived_since_last_expansion_ > new_space_.Capacity()) {
637 // Double the size of new space if there is room to grow and enough
638 // data has survived scavenge since the last expansion.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000639 // TODO(1240712): NewSpace::Double has a return value which is
640 // ignored here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000641 new_space_.Double();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000642 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000643 }
644
645 // Flip the semispaces. After flipping, to space is empty, from space has
646 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000647 new_space_.Flip();
648 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000649
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000650 // We need to sweep newly copied objects which can be either in the
651 // to space or promoted to the old generation. For to-space
652 // objects, we treat the bottom of the to space as a queue. Newly
653 // copied and unswept objects lie between a 'front' mark and the
654 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000655 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000656 // Promoted objects can go into various old-generation spaces, and
657 // can be allocated internally in the spaces (from the free list).
658 // We treat the top of the to space as a queue of addresses of
659 // promoted objects. The addresses of newly promoted and unswept
660 // objects lie between a 'front' mark and a 'rear' mark that is
661 // updated as a side effect of promoting an object.
662 //
663 // There is guaranteed to be enough room at the top of the to space
664 // for the addresses of promoted objects: every object promoted
665 // frees up its size in bytes from the top of the new space, and
666 // objects are at least one pointer in size.
667 Address new_space_front = new_space_.ToSpaceLow();
668 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000669
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000670 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000671 // Copy roots.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000672 IterateRoots(&scavenge_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000674 // Copy objects reachable from weak pointers.
675 GlobalHandles::IterateWeakRoots(&scavenge_visitor);
676
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000677#if V8_HOST_ARCH_64_BIT
678 // TODO(X64): Make this go away again. We currently disable RSets for
679 // 64-bit-mode.
680 HeapObjectIterator old_pointer_iterator(old_pointer_space_);
681 while (old_pointer_iterator.has_next()) {
682 HeapObject* heap_object = old_pointer_iterator.next();
683 heap_object->Iterate(&scavenge_visitor);
684 }
685 HeapObjectIterator map_iterator(map_space_);
686 while (map_iterator.has_next()) {
687 HeapObject* heap_object = map_iterator.next();
688 heap_object->Iterate(&scavenge_visitor);
689 }
690 LargeObjectIterator lo_iterator(lo_space_);
691 while (lo_iterator.has_next()) {
692 HeapObject* heap_object = lo_iterator.next();
693 if (heap_object->IsFixedArray()) {
694 heap_object->Iterate(&scavenge_visitor);
695 }
696 }
697#else // V8_HOST_ARCH_64_BIT
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000698 // Copy objects reachable from the old generation. By definition,
699 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000700 IterateRSet(old_pointer_space_, &ScavengePointer);
701 IterateRSet(map_space_, &ScavengePointer);
702 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000703#endif // V8_HOST_ARCH_64_BIT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000704
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000705 do {
706 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000708 // The addresses new_space_front and new_space_.top() define a
709 // queue of unprocessed copied objects. Process them until the
710 // queue is empty.
711 while (new_space_front < new_space_.top()) {
712 HeapObject* object = HeapObject::FromAddress(new_space_front);
713 object->Iterate(&scavenge_visitor);
714 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000715 }
716
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000717 // Promote and process all the to-be-promoted objects.
718 while (!promotion_queue.is_empty()) {
719 HeapObject* source;
720 Map* map;
721 promotion_queue.remove(&source, &map);
722 // Copy the from-space object to its new location (given by the
723 // forwarding address) and fix its map.
724 HeapObject* target = source->map_word().ToForwardingAddress();
725 CopyBlock(reinterpret_cast<Object**>(target->address()),
726 reinterpret_cast<Object**>(source->address()),
727 source->SizeFromMap(map));
728 target->set_map(map);
729
730#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
731 // Update NewSpace stats if necessary.
732 RecordCopiedObject(target);
733#endif
734 // Visit the newly copied object for pointers to new space.
735 target->Iterate(&scavenge_visitor);
736 UpdateRSet(target);
737 }
738
739 // Take another spin if there are now unswept objects in new space
740 // (there are currently no more unswept promoted objects).
741 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000742
743 // Set age mark.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000744 new_space_.set_age_mark(new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000746 // Update how much has survived scavenge.
747 survived_since_last_expansion_ +=
748 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
749
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000750 LOG(ResourceEvent("scavenge", "end"));
751
752 gc_state_ = NOT_IN_GC;
753}
754
755
756void Heap::ClearRSetRange(Address start, int size_in_bytes) {
757 uint32_t start_bit;
758 Address start_word_address =
759 Page::ComputeRSetBitPosition(start, 0, &start_bit);
760 uint32_t end_bit;
761 Address end_word_address =
762 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
763 0,
764 &end_bit);
765
766 // We want to clear the bits in the starting word starting with the
767 // first bit, and in the ending word up to and including the last
768 // bit. Build a pair of bitmasks to do that.
769 uint32_t start_bitmask = start_bit - 1;
770 uint32_t end_bitmask = ~((end_bit << 1) - 1);
771
772 // If the start address and end address are the same, we mask that
773 // word once, otherwise mask the starting and ending word
774 // separately and all the ones in between.
775 if (start_word_address == end_word_address) {
776 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
777 } else {
778 Memory::uint32_at(start_word_address) &= start_bitmask;
779 Memory::uint32_at(end_word_address) &= end_bitmask;
780 start_word_address += kIntSize;
781 memset(start_word_address, 0, end_word_address - start_word_address);
782 }
783}
784
785
786class UpdateRSetVisitor: public ObjectVisitor {
787 public:
788
789 void VisitPointer(Object** p) {
790 UpdateRSet(p);
791 }
792
793 void VisitPointers(Object** start, Object** end) {
794 // Update a store into slots [start, end), used (a) to update remembered
795 // set when promoting a young object to old space or (b) to rebuild
796 // remembered sets after a mark-compact collection.
797 for (Object** p = start; p < end; p++) UpdateRSet(p);
798 }
799 private:
800
801 void UpdateRSet(Object** p) {
802 // The remembered set should not be set. It should be clear for objects
803 // newly copied to old space, and it is cleared before rebuilding in the
804 // mark-compact collector.
805 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
806 if (Heap::InNewSpace(*p)) {
807 Page::SetRSet(reinterpret_cast<Address>(p), 0);
808 }
809 }
810};
811
812
813int Heap::UpdateRSet(HeapObject* obj) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000814#ifndef V8_HOST_ARCH_64_BIT
815 // TODO(X64) Reenable RSet when we have a working 64-bit layout of Page.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816 ASSERT(!InNewSpace(obj));
817 // Special handling of fixed arrays to iterate the body based on the start
818 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
819 // will not work because Page::SetRSet needs to have the start of the
820 // object.
821 if (obj->IsFixedArray()) {
822 FixedArray* array = FixedArray::cast(obj);
823 int length = array->length();
824 for (int i = 0; i < length; i++) {
825 int offset = FixedArray::kHeaderSize + i * kPointerSize;
826 ASSERT(!Page::IsRSetSet(obj->address(), offset));
827 if (Heap::InNewSpace(array->get(i))) {
828 Page::SetRSet(obj->address(), offset);
829 }
830 }
831 } else if (!obj->IsCode()) {
832 // Skip code object, we know it does not contain inter-generational
833 // pointers.
834 UpdateRSetVisitor v;
835 obj->Iterate(&v);
836 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000837#endif // V8_HOST_ARCH_64_BIT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838 return obj->Size();
839}
840
841
842void Heap::RebuildRSets() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000843 // By definition, we do not care about remembered set bits in code or data
844 // spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845 map_space_->ClearRSet();
846 RebuildRSets(map_space_);
847
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000848 old_pointer_space_->ClearRSet();
849 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000850
851 Heap::lo_space_->ClearRSet();
852 RebuildRSets(lo_space_);
853}
854
855
856void Heap::RebuildRSets(PagedSpace* space) {
857 HeapObjectIterator it(space);
858 while (it.has_next()) Heap::UpdateRSet(it.next());
859}
860
861
862void Heap::RebuildRSets(LargeObjectSpace* space) {
863 LargeObjectIterator it(space);
864 while (it.has_next()) Heap::UpdateRSet(it.next());
865}
866
867
868#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
869void Heap::RecordCopiedObject(HeapObject* obj) {
870 bool should_record = false;
871#ifdef DEBUG
872 should_record = FLAG_heap_stats;
873#endif
874#ifdef ENABLE_LOGGING_AND_PROFILING
875 should_record = should_record || FLAG_log_gc;
876#endif
877 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000878 if (new_space_.Contains(obj)) {
879 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000880 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000881 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000882 }
883 }
884}
885#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
886
887
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000888
889HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000890 HeapObject* target,
891 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000892 // Copy the content of source to target.
893 CopyBlock(reinterpret_cast<Object**>(target->address()),
894 reinterpret_cast<Object**>(source->address()),
895 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896
kasper.lund7276f142008-07-30 08:49:36 +0000897 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000898 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000899
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000901 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000902 RecordCopiedObject(target);
903#endif
904
905 return target;
906}
907
908
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000909static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000910 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000911 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000912 InstanceType type = map->instance_type();
913 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
914 ASSERT(object->IsString() && !object->IsSymbol());
915 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000916}
917
918
919void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
920 ASSERT(InFromSpace(object));
921 MapWord first_word = object->map_word();
922 ASSERT(!first_word.IsForwardingAddress());
923
924 // Optimization: Bypass flattened ConsString objects.
925 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +0000926 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000927 *p = object;
928 // After patching *p we have to repeat the checks that object is in the
929 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000930 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000931 first_word = object->map_word();
932 if (first_word.IsForwardingAddress()) {
933 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000934 return;
935 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000936 }
937
kasper.lund7276f142008-07-30 08:49:36 +0000938 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000939 // We rely on live objects in new space to be at least two pointers,
940 // so we can store the from-space address and map pointer of promoted
941 // objects in the to space.
942 ASSERT(object_size >= 2 * kPointerSize);
943
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000944 // If the object should be promoted, we try to copy it to old space.
945 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000946 OldSpace* target_space = Heap::TargetSpace(object);
947 ASSERT(target_space == Heap::old_pointer_space_ ||
948 target_space == Heap::old_data_space_);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000949 Object* result = target_space->AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000951 HeapObject* target = HeapObject::cast(result);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000952 if (target_space == Heap::old_pointer_space_) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000953 // Save the from-space object pointer and its map pointer at the
954 // top of the to space to be swept and copied later. Write the
955 // forwarding address over the map word of the from-space
956 // object.
957 promotion_queue.insert(object, first_word.ToMap());
958 object->set_map_word(MapWord::FromForwardingAddress(target));
959
960 // Give the space allocated for the result a proper map by
961 // treating it as a free list node (not linked into the free
962 // list).
963 FreeListNode* node = FreeListNode::FromAddress(target->address());
964 node->set_size(object_size);
965
966 *p = target;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000967 } else {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000968 // Objects promoted to the data space can be copied immediately
969 // and not revisited---we will never sweep that space for
970 // pointers and the copied objects do not contain pointers to
971 // new space objects.
972 *p = MigrateObject(object, target, object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000973#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000974 VerifyNonPointerSpacePointersVisitor v;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000975 (*p)->Iterate(&v);
976#endif
977 }
978 return;
979 }
980 }
981
982 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000983 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000984 // Failed allocation at this point is utterly unexpected.
985 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000986 *p = MigrateObject(object, HeapObject::cast(result), object_size);
987}
988
989
990void Heap::ScavengePointer(HeapObject** p) {
991 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000992}
993
994
995Object* Heap::AllocatePartialMap(InstanceType instance_type,
996 int instance_size) {
997 Object* result = AllocateRawMap(Map::kSize);
998 if (result->IsFailure()) return result;
999
1000 // Map::cast cannot be used due to uninitialized map field.
1001 reinterpret_cast<Map*>(result)->set_map(meta_map());
1002 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1003 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001004 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001005 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
1006 return result;
1007}
1008
1009
1010Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
1011 Object* result = AllocateRawMap(Map::kSize);
1012 if (result->IsFailure()) return result;
1013
1014 Map* map = reinterpret_cast<Map*>(result);
1015 map->set_map(meta_map());
1016 map->set_instance_type(instance_type);
1017 map->set_prototype(null_value());
1018 map->set_constructor(null_value());
1019 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001020 map->set_inobject_properties(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001021 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001022 map->set_code_cache(empty_fixed_array());
1023 map->set_unused_property_fields(0);
1024 map->set_bit_field(0);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001025 map->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001026 return map;
1027}
1028
1029
1030bool Heap::CreateInitialMaps() {
1031 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1032 if (obj->IsFailure()) return false;
1033
1034 // Map::cast cannot be used due to uninitialized map field.
1035 meta_map_ = reinterpret_cast<Map*>(obj);
1036 meta_map()->set_map(meta_map());
1037
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001038 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001039 if (obj->IsFailure()) return false;
1040 fixed_array_map_ = Map::cast(obj);
1041
1042 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1043 if (obj->IsFailure()) return false;
1044 oddball_map_ = Map::cast(obj);
1045
1046 // Allocate the empty array
1047 obj = AllocateEmptyFixedArray();
1048 if (obj->IsFailure()) return false;
1049 empty_fixed_array_ = FixedArray::cast(obj);
1050
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001051 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001052 if (obj->IsFailure()) return false;
1053 null_value_ = obj;
1054
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001055 // Allocate the empty descriptor array. AllocateMap can now be used.
1056 obj = AllocateEmptyFixedArray();
1057 if (obj->IsFailure()) return false;
1058 // There is a check against empty_descriptor_array() in cast().
1059 empty_descriptor_array_ = reinterpret_cast<DescriptorArray*>(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001061 // Fix the instance_descriptors for the existing maps.
1062 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001063 meta_map()->set_code_cache(empty_fixed_array());
1064
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001065 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001066 fixed_array_map()->set_code_cache(empty_fixed_array());
1067
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001068 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001069 oddball_map()->set_code_cache(empty_fixed_array());
1070
1071 // Fix prototype object for existing maps.
1072 meta_map()->set_prototype(null_value());
1073 meta_map()->set_constructor(null_value());
1074
1075 fixed_array_map()->set_prototype(null_value());
1076 fixed_array_map()->set_constructor(null_value());
1077 oddball_map()->set_prototype(null_value());
1078 oddball_map()->set_constructor(null_value());
1079
1080 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1081 if (obj->IsFailure()) return false;
1082 heap_number_map_ = Map::cast(obj);
1083
1084 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1085 if (obj->IsFailure()) return false;
1086 proxy_map_ = Map::cast(obj);
1087
1088#define ALLOCATE_STRING_MAP(type, size, name) \
1089 obj = AllocateMap(type, size); \
1090 if (obj->IsFailure()) return false; \
1091 name##_map_ = Map::cast(obj);
1092 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
1093#undef ALLOCATE_STRING_MAP
1094
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001095 obj = AllocateMap(SHORT_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001096 if (obj->IsFailure()) return false;
1097 undetectable_short_string_map_ = Map::cast(obj);
1098 undetectable_short_string_map_->set_is_undetectable();
1099
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001100 obj = AllocateMap(MEDIUM_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001101 if (obj->IsFailure()) return false;
1102 undetectable_medium_string_map_ = Map::cast(obj);
1103 undetectable_medium_string_map_->set_is_undetectable();
1104
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001105 obj = AllocateMap(LONG_STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001106 if (obj->IsFailure()) return false;
1107 undetectable_long_string_map_ = Map::cast(obj);
1108 undetectable_long_string_map_->set_is_undetectable();
1109
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001110 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001111 if (obj->IsFailure()) return false;
1112 undetectable_short_ascii_string_map_ = Map::cast(obj);
1113 undetectable_short_ascii_string_map_->set_is_undetectable();
1114
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001115 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001116 if (obj->IsFailure()) return false;
1117 undetectable_medium_ascii_string_map_ = Map::cast(obj);
1118 undetectable_medium_ascii_string_map_->set_is_undetectable();
1119
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001120 obj = AllocateMap(LONG_ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001121 if (obj->IsFailure()) return false;
1122 undetectable_long_ascii_string_map_ = Map::cast(obj);
1123 undetectable_long_ascii_string_map_->set_is_undetectable();
1124
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001125 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001126 if (obj->IsFailure()) return false;
1127 byte_array_map_ = Map::cast(obj);
1128
1129 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1130 if (obj->IsFailure()) return false;
1131 code_map_ = Map::cast(obj);
1132
1133 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1134 if (obj->IsFailure()) return false;
1135 one_word_filler_map_ = Map::cast(obj);
1136
1137 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1138 if (obj->IsFailure()) return false;
1139 two_word_filler_map_ = Map::cast(obj);
1140
1141#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
1142 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
1143 if (obj->IsFailure()) return false; \
1144 name##_map_ = Map::cast(obj);
1145 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
1146#undef ALLOCATE_STRUCT_MAP
1147
ager@chromium.org236ad962008-09-25 09:45:57 +00001148 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001149 if (obj->IsFailure()) return false;
1150 hash_table_map_ = Map::cast(obj);
1151
ager@chromium.org236ad962008-09-25 09:45:57 +00001152 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001153 if (obj->IsFailure()) return false;
1154 context_map_ = Map::cast(obj);
1155
ager@chromium.org236ad962008-09-25 09:45:57 +00001156 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001157 if (obj->IsFailure()) return false;
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001158 catch_context_map_ = Map::cast(obj);
1159
1160 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1161 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001162 global_context_map_ = Map::cast(obj);
1163
1164 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1165 if (obj->IsFailure()) return false;
1166 boilerplate_function_map_ = Map::cast(obj);
1167
1168 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1169 if (obj->IsFailure()) return false;
1170 shared_function_info_map_ = Map::cast(obj);
1171
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001172 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001173 return true;
1174}
1175
1176
1177Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1178 // Statically ensure that it is safe to allocate heap numbers in paged
1179 // spaces.
1180 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001181 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001182 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001183 if (result->IsFailure()) return result;
1184
1185 HeapObject::cast(result)->set_map(heap_number_map());
1186 HeapNumber::cast(result)->set_value(value);
1187 return result;
1188}
1189
1190
1191Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001192 // Use general version, if we're forced to always allocate.
1193 if (always_allocate()) return AllocateHeapNumber(value, NOT_TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001194 // This version of AllocateHeapNumber is optimized for
1195 // allocation in new space.
1196 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1197 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001198 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001199 if (result->IsFailure()) return result;
1200 HeapObject::cast(result)->set_map(heap_number_map());
1201 HeapNumber::cast(result)->set_value(value);
1202 return result;
1203}
1204
1205
1206Object* Heap::CreateOddball(Map* map,
1207 const char* to_string,
1208 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001209 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001210 if (result->IsFailure()) return result;
1211 return Oddball::cast(result)->Initialize(to_string, to_number);
1212}
1213
1214
1215bool Heap::CreateApiObjects() {
1216 Object* obj;
1217
1218 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1219 if (obj->IsFailure()) return false;
1220 neander_map_ = Map::cast(obj);
1221
1222 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1223 if (obj->IsFailure()) return false;
1224 Object* elements = AllocateFixedArray(2);
1225 if (elements->IsFailure()) return false;
1226 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1227 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1228 message_listeners_ = JSObject::cast(obj);
1229
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001230 return true;
1231}
1232
1233void Heap::CreateFixedStubs() {
1234 // Here we create roots for fixed stubs. They are needed at GC
1235 // for cooking and uncooking (check out frames.cc).
1236 // The eliminates the need for doing dictionary lookup in the
1237 // stub cache for these stubs.
1238 HandleScope scope;
1239 {
1240 CEntryStub stub;
1241 c_entry_code_ = *stub.GetCode();
1242 }
1243 {
1244 CEntryDebugBreakStub stub;
1245 c_entry_debug_break_code_ = *stub.GetCode();
1246 }
1247 {
1248 JSEntryStub stub;
1249 js_entry_code_ = *stub.GetCode();
1250 }
1251 {
1252 JSConstructEntryStub stub;
1253 js_construct_entry_code_ = *stub.GetCode();
1254 }
1255}
1256
1257
1258bool Heap::CreateInitialObjects() {
1259 Object* obj;
1260
1261 // The -0 value must be set before NumberFromDouble works.
1262 obj = AllocateHeapNumber(-0.0, TENURED);
1263 if (obj->IsFailure()) return false;
1264 minus_zero_value_ = obj;
1265 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1266
1267 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1268 if (obj->IsFailure()) return false;
1269 nan_value_ = obj;
1270
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001271 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001272 if (obj->IsFailure()) return false;
1273 undefined_value_ = obj;
1274 ASSERT(!InNewSpace(undefined_value()));
1275
1276 // Allocate initial symbol table.
1277 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1278 if (obj->IsFailure()) return false;
1279 symbol_table_ = obj;
1280
1281 // Assign the print strings for oddballs after creating symboltable.
1282 Object* symbol = LookupAsciiSymbol("undefined");
1283 if (symbol->IsFailure()) return false;
1284 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1285 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1286
1287 // Assign the print strings for oddballs after creating symboltable.
1288 symbol = LookupAsciiSymbol("null");
1289 if (symbol->IsFailure()) return false;
1290 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1291 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1292
1293 // Allocate the null_value
1294 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1295 if (obj->IsFailure()) return false;
1296
1297 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1298 if (obj->IsFailure()) return false;
1299 true_value_ = obj;
1300
1301 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1302 if (obj->IsFailure()) return false;
1303 false_value_ = obj;
1304
1305 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1306 if (obj->IsFailure()) return false;
1307 the_hole_value_ = obj;
1308
1309 // Allocate the empty string.
1310 obj = AllocateRawAsciiString(0, TENURED);
1311 if (obj->IsFailure()) return false;
1312 empty_string_ = String::cast(obj);
1313
1314#define SYMBOL_INITIALIZE(name, string) \
1315 obj = LookupAsciiSymbol(string); \
1316 if (obj->IsFailure()) return false; \
1317 (name##_) = String::cast(obj);
1318 SYMBOL_LIST(SYMBOL_INITIALIZE)
1319#undef SYMBOL_INITIALIZE
1320
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001321 // Allocate the hidden symbol which is used to identify the hidden properties
1322 // in JSObjects. The hash code has a special value so that it will not match
1323 // the empty string when searching for the property. It cannot be part of the
1324 // SYMBOL_LIST because it needs to be allocated manually with the special
1325 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1326 // that it will always be at the first entry in property descriptors.
1327 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1328 if (obj->IsFailure()) return false;
1329 hidden_symbol_ = String::cast(obj);
1330
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001331 // Allocate the proxy for __proto__.
1332 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1333 if (obj->IsFailure()) return false;
1334 prototype_accessors_ = Proxy::cast(obj);
1335
1336 // Allocate the code_stubs dictionary.
1337 obj = Dictionary::Allocate(4);
1338 if (obj->IsFailure()) return false;
1339 code_stubs_ = Dictionary::cast(obj);
1340
1341 // Allocate the non_monomorphic_cache used in stub-cache.cc
1342 obj = Dictionary::Allocate(4);
1343 if (obj->IsFailure()) return false;
1344 non_monomorphic_cache_ = Dictionary::cast(obj);
1345
1346 CreateFixedStubs();
1347
1348 // Allocate the number->string conversion cache
1349 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1350 if (obj->IsFailure()) return false;
1351 number_string_cache_ = FixedArray::cast(obj);
1352
1353 // Allocate cache for single character strings.
1354 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1355 if (obj->IsFailure()) return false;
1356 single_character_string_cache_ = FixedArray::cast(obj);
1357
1358 // Allocate cache for external strings pointing to native source code.
1359 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1360 if (obj->IsFailure()) return false;
1361 natives_source_cache_ = FixedArray::cast(obj);
1362
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001363 // Handling of script id generation is in Factory::NewScript.
1364 last_script_id_ = undefined_value();
1365
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001366 // Initialize keyed lookup cache.
1367 ClearKeyedLookupCache();
1368
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001369 // Initialize compilation cache.
1370 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001371
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001372 return true;
1373}
1374
1375
1376static inline int double_get_hash(double d) {
1377 DoubleRepresentation rep(d);
1378 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1379 (Heap::kNumberStringCacheSize - 1));
1380}
1381
1382
1383static inline int smi_get_hash(Smi* smi) {
1384 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1385}
1386
1387
1388
1389Object* Heap::GetNumberStringCache(Object* number) {
1390 int hash;
1391 if (number->IsSmi()) {
1392 hash = smi_get_hash(Smi::cast(number));
1393 } else {
1394 hash = double_get_hash(number->Number());
1395 }
1396 Object* key = number_string_cache_->get(hash * 2);
1397 if (key == number) {
1398 return String::cast(number_string_cache_->get(hash * 2 + 1));
1399 } else if (key->IsHeapNumber() &&
1400 number->IsHeapNumber() &&
1401 key->Number() == number->Number()) {
1402 return String::cast(number_string_cache_->get(hash * 2 + 1));
1403 }
1404 return undefined_value();
1405}
1406
1407
1408void Heap::SetNumberStringCache(Object* number, String* string) {
1409 int hash;
1410 if (number->IsSmi()) {
1411 hash = smi_get_hash(Smi::cast(number));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001412 number_string_cache_->set(hash * 2, number, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001413 } else {
1414 hash = double_get_hash(number->Number());
1415 number_string_cache_->set(hash * 2, number);
1416 }
1417 number_string_cache_->set(hash * 2 + 1, string);
1418}
1419
1420
1421Object* Heap::SmiOrNumberFromDouble(double value,
1422 bool new_object,
1423 PretenureFlag pretenure) {
1424 // We need to distinguish the minus zero value and this cannot be
1425 // done after conversion to int. Doing this by comparing bit
1426 // patterns is faster than using fpclassify() et al.
1427 static const DoubleRepresentation plus_zero(0.0);
1428 static const DoubleRepresentation minus_zero(-0.0);
1429 static const DoubleRepresentation nan(OS::nan_value());
1430 ASSERT(minus_zero_value_ != NULL);
1431 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1432
1433 DoubleRepresentation rep(value);
1434 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1435 if (rep.bits == minus_zero.bits) {
1436 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1437 : minus_zero_value_;
1438 }
1439 if (rep.bits == nan.bits) {
1440 return new_object
1441 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1442 : nan_value_;
1443 }
1444
1445 // Try to represent the value as a tagged small integer.
1446 int int_value = FastD2I(value);
1447 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1448 return Smi::FromInt(int_value);
1449 }
1450
1451 // Materialize the value in the heap.
1452 return AllocateHeapNumber(value, pretenure);
1453}
1454
1455
1456Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1457 return SmiOrNumberFromDouble(value,
1458 true /* number object must be new */,
1459 pretenure);
1460}
1461
1462
1463Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1464 return SmiOrNumberFromDouble(value,
1465 false /* use preallocated NaN, -0.0 */,
1466 pretenure);
1467}
1468
1469
1470Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1471 // Statically ensure that it is safe to allocate proxies in paged spaces.
1472 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001473 AllocationSpace space =
1474 (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475 Object* result = Allocate(proxy_map(), space);
1476 if (result->IsFailure()) return result;
1477
1478 Proxy::cast(result)->set_proxy(proxy);
1479 return result;
1480}
1481
1482
1483Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1484 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1485 if (result->IsFailure()) return result;
1486
1487 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1488 share->set_name(name);
1489 Code* illegal = Builtins::builtin(Builtins::Illegal);
1490 share->set_code(illegal);
1491 share->set_expected_nof_properties(0);
1492 share->set_length(0);
1493 share->set_formal_parameter_count(0);
1494 share->set_instance_class_name(Object_symbol());
1495 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001496 share->set_script(undefined_value());
1497 share->set_start_position_and_type(0);
1498 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001499 share->set_inferred_name(empty_string());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001500 return result;
1501}
1502
1503
ager@chromium.org870a0b62008-11-04 11:43:05 +00001504Object* Heap::AllocateConsString(String* first,
ager@chromium.orgc3e50d82008-11-05 11:53:10 +00001505 String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001506 int first_length = first->length();
1507 int second_length = second->length();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001508 int length = first_length + second_length;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001509 bool is_ascii = first->IsAsciiRepresentation()
1510 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001511
1512 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001513 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001514 ASSERT(first->IsFlat());
1515 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001516 if (is_ascii) {
1517 Object* result = AllocateRawAsciiString(length);
1518 if (result->IsFailure()) return result;
1519 // Copy the characters into the new object.
1520 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001521 String::WriteToFlat(first, dest, 0, first_length);
1522 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001523 return result;
1524 } else {
1525 Object* result = AllocateRawTwoByteString(length);
1526 if (result->IsFailure()) return result;
1527 // Copy the characters into the new object.
1528 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001529 String::WriteToFlat(first, dest, 0, first_length);
1530 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001531 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001532 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001533 }
1534
1535 Map* map;
1536 if (length <= String::kMaxShortStringSize) {
1537 map = is_ascii ? short_cons_ascii_string_map()
1538 : short_cons_string_map();
1539 } else if (length <= String::kMaxMediumStringSize) {
1540 map = is_ascii ? medium_cons_ascii_string_map()
1541 : medium_cons_string_map();
1542 } else {
1543 map = is_ascii ? long_cons_ascii_string_map()
1544 : long_cons_string_map();
1545 }
1546
1547 Object* result = Allocate(map, NEW_SPACE);
1548 if (result->IsFailure()) return result;
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001549 ASSERT(InNewSpace(result));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001550 ConsString* cons_string = ConsString::cast(result);
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001551 cons_string->set_first(first, SKIP_WRITE_BARRIER);
1552 cons_string->set_second(second, SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553 cons_string->set_length(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554 return result;
1555}
1556
1557
ager@chromium.org870a0b62008-11-04 11:43:05 +00001558Object* Heap::AllocateSlicedString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001559 int start,
1560 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001561 int length = end - start;
1562
1563 // If the resulting string is small make a sub string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001564 if (end - start <= String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001565 return Heap::AllocateSubString(buffer, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566 }
1567
1568 Map* map;
1569 if (length <= String::kMaxShortStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001570 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001571 short_sliced_ascii_string_map() :
1572 short_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001573 } else if (length <= String::kMaxMediumStringSize) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001574 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001575 medium_sliced_ascii_string_map() :
1576 medium_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001577 } else {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001578 map = buffer->IsAsciiRepresentation() ?
ager@chromium.org870a0b62008-11-04 11:43:05 +00001579 long_sliced_ascii_string_map() :
1580 long_sliced_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001581 }
1582
1583 Object* result = Allocate(map, NEW_SPACE);
1584 if (result->IsFailure()) return result;
1585
1586 SlicedString* sliced_string = SlicedString::cast(result);
1587 sliced_string->set_buffer(buffer);
1588 sliced_string->set_start(start);
1589 sliced_string->set_length(length);
1590
1591 return result;
1592}
1593
1594
ager@chromium.org870a0b62008-11-04 11:43:05 +00001595Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00001596 int start,
1597 int end) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001598 int length = end - start;
1599
ager@chromium.org7c537e22008-10-16 08:43:32 +00001600 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001601 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001602 buffer->Get(start));
ager@chromium.org7c537e22008-10-16 08:43:32 +00001603 }
1604
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001606 if (!buffer->IsFlat()) {
1607 buffer->TryFlatten();
ager@chromium.org870a0b62008-11-04 11:43:05 +00001608 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609
ager@chromium.org5ec48922009-05-05 07:25:34 +00001610 Object* result = buffer->IsAsciiRepresentation()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001611 ? AllocateRawAsciiString(length)
1612 : AllocateRawTwoByteString(length);
1613 if (result->IsFailure()) return result;
1614
1615 // Copy the characters into the new object.
1616 String* string_result = String::cast(result);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001617 StringHasher hasher(length);
1618 int i = 0;
1619 for (; i < length && hasher.is_array_index(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001620 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001621 hasher.AddCharacter(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001622 string_result->Set(i, c);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00001624 for (; i < length; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001625 uc32 c = buffer->Get(start + i);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001626 hasher.AddCharacterNoIndex(c);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001627 string_result->Set(i, c);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001628 }
1629 string_result->set_length_field(hasher.GetHashField());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001630 return result;
1631}
1632
1633
1634Object* Heap::AllocateExternalStringFromAscii(
1635 ExternalAsciiString::Resource* resource) {
1636 Map* map;
1637 int length = resource->length();
1638 if (length <= String::kMaxShortStringSize) {
1639 map = short_external_ascii_string_map();
1640 } else if (length <= String::kMaxMediumStringSize) {
1641 map = medium_external_ascii_string_map();
1642 } else {
1643 map = long_external_ascii_string_map();
1644 }
1645
1646 Object* result = Allocate(map, NEW_SPACE);
1647 if (result->IsFailure()) return result;
1648
1649 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1650 external_string->set_length(length);
1651 external_string->set_resource(resource);
1652
1653 return result;
1654}
1655
1656
1657Object* Heap::AllocateExternalStringFromTwoByte(
1658 ExternalTwoByteString::Resource* resource) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001659 int length = resource->length();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001660
ager@chromium.org6f10e412009-02-13 10:11:16 +00001661 Map* map = ExternalTwoByteString::StringMap(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001662 Object* result = Allocate(map, NEW_SPACE);
1663 if (result->IsFailure()) return result;
1664
1665 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1666 external_string->set_length(length);
1667 external_string->set_resource(resource);
1668
1669 return result;
1670}
1671
1672
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001673Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001674 if (code <= String::kMaxAsciiCharCode) {
1675 Object* value = Heap::single_character_string_cache()->get(code);
1676 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001677
1678 char buffer[1];
1679 buffer[0] = static_cast<char>(code);
1680 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
1681
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001683 Heap::single_character_string_cache()->set(code, result);
1684 return result;
1685 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001686
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001687 Object* result = Heap::AllocateRawTwoByteString(1);
1688 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00001689 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001690 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00001691 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001692}
1693
1694
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001695Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
1696 if (pretenure == NOT_TENURED) {
1697 return AllocateByteArray(length);
1698 }
1699 int size = ByteArray::SizeFor(length);
1700 AllocationSpace space =
1701 size > MaxHeapObjectSize() ? LO_SPACE : OLD_DATA_SPACE;
1702
1703 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
1704
1705 if (result->IsFailure()) return result;
1706
1707 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1708 reinterpret_cast<Array*>(result)->set_length(length);
1709 return result;
1710}
1711
1712
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001713Object* Heap::AllocateByteArray(int length) {
1714 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001715 AllocationSpace space =
1716 size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001717
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001718 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001719
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720 if (result->IsFailure()) return result;
1721
1722 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1723 reinterpret_cast<Array*>(result)->set_length(length);
1724 return result;
1725}
1726
1727
ager@chromium.org6f10e412009-02-13 10:11:16 +00001728void Heap::CreateFillerObjectAt(Address addr, int size) {
1729 if (size == 0) return;
1730 HeapObject* filler = HeapObject::FromAddress(addr);
1731 if (size == kPointerSize) {
1732 filler->set_map(Heap::one_word_filler_map());
1733 } else {
1734 filler->set_map(Heap::byte_array_map());
1735 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
1736 }
1737}
1738
1739
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001740Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001741 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001742 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001743 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001744 // Compute size
1745 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1746 int sinfo_size = 0;
1747 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1748 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001749 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001750 Object* result;
1751 if (obj_size > MaxHeapObjectSize()) {
1752 result = lo_space_->AllocateRawCode(obj_size);
1753 } else {
1754 result = code_space_->AllocateRaw(obj_size);
1755 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001756
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757 if (result->IsFailure()) return result;
1758
1759 // Initialize the object
1760 HeapObject::cast(result)->set_map(code_map());
1761 Code* code = Code::cast(result);
1762 code->set_instruction_size(desc.instr_size);
1763 code->set_relocation_size(desc.reloc_size);
1764 code->set_sinfo_size(sinfo_size);
1765 code->set_flags(flags);
1766 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001767 // Allow self references to created code object by patching the handle to
1768 // point to the newly allocated Code object.
1769 if (!self_reference.is_null()) {
1770 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001771 }
1772 // Migrate generated code.
1773 // The generated code can contain Object** values (typically from handles)
1774 // that are dereferenced during the copy to point directly to the actual heap
1775 // objects. These pointers can include references to the code object itself,
1776 // through the self_reference parameter.
1777 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001778 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1779
1780#ifdef DEBUG
1781 code->Verify();
1782#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001783 return code;
1784}
1785
1786
1787Object* Heap::CopyCode(Code* code) {
1788 // Allocate an object the same size as the code object.
1789 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001790 Object* result;
1791 if (obj_size > MaxHeapObjectSize()) {
1792 result = lo_space_->AllocateRawCode(obj_size);
1793 } else {
1794 result = code_space_->AllocateRaw(obj_size);
1795 }
1796
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001797 if (result->IsFailure()) return result;
1798
1799 // Copy code object.
1800 Address old_addr = code->address();
1801 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001802 CopyBlock(reinterpret_cast<Object**>(new_addr),
1803 reinterpret_cast<Object**>(old_addr),
1804 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001805 // Relocate the copy.
1806 Code* new_code = Code::cast(result);
1807 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001808 return new_code;
1809}
1810
1811
1812Object* Heap::Allocate(Map* map, AllocationSpace space) {
1813 ASSERT(gc_state_ == NOT_IN_GC);
1814 ASSERT(map->instance_type() != MAP_TYPE);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001815 Object* result = AllocateRaw(map->instance_size(),
1816 space,
1817 TargetSpaceId(map->instance_type()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001818 if (result->IsFailure()) return result;
1819 HeapObject::cast(result)->set_map(map);
1820 return result;
1821}
1822
1823
1824Object* Heap::InitializeFunction(JSFunction* function,
1825 SharedFunctionInfo* shared,
1826 Object* prototype) {
1827 ASSERT(!prototype->IsMap());
1828 function->initialize_properties();
1829 function->initialize_elements();
1830 function->set_shared(shared);
1831 function->set_prototype_or_initial_map(prototype);
1832 function->set_context(undefined_value());
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00001833 function->set_literals(empty_fixed_array(), SKIP_WRITE_BARRIER);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001834 return function;
1835}
1836
1837
1838Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00001839 // Allocate the prototype. Make sure to use the object function
1840 // from the function's context, since the function can be from a
1841 // different context.
1842 JSFunction* object_function =
1843 function->context()->global_context()->object_function();
1844 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001845 if (prototype->IsFailure()) return prototype;
1846 // When creating the prototype for the function we must set its
1847 // constructor to the function.
1848 Object* result =
1849 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1850 function,
1851 DONT_ENUM);
1852 if (result->IsFailure()) return result;
1853 return prototype;
1854}
1855
1856
1857Object* Heap::AllocateFunction(Map* function_map,
1858 SharedFunctionInfo* shared,
1859 Object* prototype) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001860 Object* result = Allocate(function_map, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001861 if (result->IsFailure()) return result;
1862 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1863}
1864
1865
1866Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001867 // To get fast allocation and map sharing for arguments objects we
1868 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001869
1870 // This calls Copy directly rather than using Heap::AllocateRaw so we
1871 // duplicate the check here.
1872 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1873
1874 JSObject* boilerplate =
1875 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001876
1877 // Make the clone.
1878 Map* map = boilerplate->map();
1879 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001880 Object* result = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001881 if (result->IsFailure()) return result;
1882
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001883 // Copy the content. The arguments boilerplate doesn't have any
1884 // fields that point to new space so it's safe to skip the write
1885 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001886 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
1887 reinterpret_cast<Object**>(boilerplate->address()),
1888 object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001889
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001890 // Set the two properties.
1891 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001892 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001893 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
1894 Smi::FromInt(length),
1895 SKIP_WRITE_BARRIER);
1896
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001897 // Check the state of the object
1898 ASSERT(JSObject::cast(result)->HasFastProperties());
1899 ASSERT(JSObject::cast(result)->HasFastElements());
1900
1901 return result;
1902}
1903
1904
1905Object* Heap::AllocateInitialMap(JSFunction* fun) {
1906 ASSERT(!fun->has_initial_map());
1907
ager@chromium.org7c537e22008-10-16 08:43:32 +00001908 // First create a new map with the expected number of properties being
1909 // allocated in-object.
1910 int expected_nof_properties = fun->shared()->expected_nof_properties();
1911 int instance_size = JSObject::kHeaderSize +
1912 expected_nof_properties * kPointerSize;
1913 if (instance_size > JSObject::kMaxInstanceSize) {
1914 instance_size = JSObject::kMaxInstanceSize;
1915 expected_nof_properties = (instance_size - JSObject::kHeaderSize) /
1916 kPointerSize;
1917 }
1918 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001919 if (map_obj->IsFailure()) return map_obj;
1920
1921 // Fetch or allocate prototype.
1922 Object* prototype;
1923 if (fun->has_instance_prototype()) {
1924 prototype = fun->instance_prototype();
1925 } else {
1926 prototype = AllocateFunctionPrototype(fun);
1927 if (prototype->IsFailure()) return prototype;
1928 }
1929 Map* map = Map::cast(map_obj);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001930 map->set_inobject_properties(expected_nof_properties);
1931 map->set_unused_property_fields(expected_nof_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001932 map->set_prototype(prototype);
1933 return map;
1934}
1935
1936
1937void Heap::InitializeJSObjectFromMap(JSObject* obj,
1938 FixedArray* properties,
1939 Map* map) {
1940 obj->set_properties(properties);
1941 obj->initialize_elements();
1942 // TODO(1240798): Initialize the object's body using valid initial values
1943 // according to the object's initial map. For example, if the map's
1944 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1945 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1946 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1947 // verification code has to cope with (temporarily) invalid objects. See
1948 // for example, JSArray::JSArrayVerify).
1949 obj->InitializeBody(map->instance_size());
1950}
1951
1952
1953Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1954 // JSFunctions should be allocated using AllocateFunction to be
1955 // properly initialized.
1956 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1957
1958 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00001959 int prop_size = map->unused_property_fields() - map->inobject_properties();
1960 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001961 if (properties->IsFailure()) return properties;
1962
1963 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001964 AllocationSpace space =
1965 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001966 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1967 Object* obj = Allocate(map, space);
1968 if (obj->IsFailure()) return obj;
1969
1970 // Initialize the JSObject.
1971 InitializeJSObjectFromMap(JSObject::cast(obj),
1972 FixedArray::cast(properties),
1973 map);
1974 return obj;
1975}
1976
1977
1978Object* Heap::AllocateJSObject(JSFunction* constructor,
1979 PretenureFlag pretenure) {
1980 // Allocate the initial map if absent.
1981 if (!constructor->has_initial_map()) {
1982 Object* initial_map = AllocateInitialMap(constructor);
1983 if (initial_map->IsFailure()) return initial_map;
1984 constructor->set_initial_map(Map::cast(initial_map));
1985 Map::cast(initial_map)->set_constructor(constructor);
1986 }
1987 // Allocate the object based on the constructors initial map.
1988 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1989}
1990
1991
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001992Object* Heap::CopyJSObject(JSObject* source) {
1993 // Never used to copy functions. If functions need to be copied we
1994 // have to be careful to clear the literals array.
1995 ASSERT(!source->IsJSFunction());
1996
1997 // Make the clone.
1998 Map* map = source->map();
1999 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002000 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002001
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002002 // If we're forced to always allocate, we use the general allocation
2003 // functions which may leave us with an object in old space.
2004 if (always_allocate()) {
2005 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2006 if (clone->IsFailure()) return clone;
2007 Address clone_address = HeapObject::cast(clone)->address();
2008 CopyBlock(reinterpret_cast<Object**>(clone_address),
2009 reinterpret_cast<Object**>(source->address()),
2010 object_size);
2011 // Update write barrier for all fields that lie beyond the header.
2012 for (int offset = JSObject::kHeaderSize;
2013 offset < object_size;
2014 offset += kPointerSize) {
2015 RecordWrite(clone_address, offset);
2016 }
2017 } else {
2018 clone = new_space_.AllocateRaw(object_size);
2019 if (clone->IsFailure()) return clone;
2020 ASSERT(Heap::InNewSpace(clone));
2021 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002022 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002023 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2024 reinterpret_cast<Object**>(source->address()),
2025 object_size);
2026 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002027
2028 FixedArray* elements = FixedArray::cast(source->elements());
2029 FixedArray* properties = FixedArray::cast(source->properties());
2030 // Update elements if necessary.
2031 if (elements->length()> 0) {
2032 Object* elem = CopyFixedArray(elements);
2033 if (elem->IsFailure()) return elem;
2034 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2035 }
2036 // Update properties if necessary.
2037 if (properties->length() > 0) {
2038 Object* prop = CopyFixedArray(properties);
2039 if (prop->IsFailure()) return prop;
2040 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2041 }
2042 // Return the new clone.
2043 return clone;
2044}
2045
2046
2047Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2048 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002049 // Allocate initial map if absent.
2050 if (!constructor->has_initial_map()) {
2051 Object* initial_map = AllocateInitialMap(constructor);
2052 if (initial_map->IsFailure()) return initial_map;
2053 constructor->set_initial_map(Map::cast(initial_map));
2054 Map::cast(initial_map)->set_constructor(constructor);
2055 }
2056
2057 Map* map = constructor->initial_map();
2058
2059 // Check that the already allocated object has the same size as
2060 // objects allocated using the constructor.
2061 ASSERT(map->instance_size() == object->map()->instance_size());
2062
2063 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002064 int prop_size = map->unused_property_fields() - map->inobject_properties();
2065 Object* properties = AllocateFixedArray(prop_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002066 if (properties->IsFailure()) return properties;
2067
2068 // Reset the map for the object.
2069 object->set_map(constructor->initial_map());
2070
2071 // Reinitialize the object from the constructor map.
2072 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2073 return object;
2074}
2075
2076
2077Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2078 PretenureFlag pretenure) {
2079 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2080 if (result->IsFailure()) return result;
2081
2082 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002083 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002084 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002085 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002086 }
2087 return result;
2088}
2089
2090
2091Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2092 PretenureFlag pretenure) {
2093 // Count the number of characters in the UTF-8 string and check if
2094 // it is an ASCII string.
2095 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2096 decoder->Reset(string.start(), string.length());
2097 int chars = 0;
2098 bool is_ascii = true;
2099 while (decoder->has_more()) {
2100 uc32 r = decoder->GetNext();
2101 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2102 chars++;
2103 }
2104
2105 // If the string is ascii, we do not need to convert the characters
2106 // since UTF8 is backwards compatible with ascii.
2107 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2108
2109 Object* result = AllocateRawTwoByteString(chars, pretenure);
2110 if (result->IsFailure()) return result;
2111
2112 // Convert and copy the characters into the new object.
2113 String* string_result = String::cast(result);
2114 decoder->Reset(string.start(), string.length());
2115 for (int i = 0; i < chars; i++) {
2116 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002117 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002118 }
2119 return result;
2120}
2121
2122
2123Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2124 PretenureFlag pretenure) {
2125 // Check if the string is an ASCII string.
2126 int i = 0;
2127 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2128
2129 Object* result;
2130 if (i == string.length()) { // It's an ASCII string.
2131 result = AllocateRawAsciiString(string.length(), pretenure);
2132 } else { // It's not an ASCII string.
2133 result = AllocateRawTwoByteString(string.length(), pretenure);
2134 }
2135 if (result->IsFailure()) return result;
2136
2137 // Copy the characters into the new object, which may be either ASCII or
2138 // UTF-16.
2139 String* string_result = String::cast(result);
2140 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002141 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002142 }
2143 return result;
2144}
2145
2146
2147Map* Heap::SymbolMapForString(String* string) {
2148 // If the string is in new space it cannot be used as a symbol.
2149 if (InNewSpace(string)) return NULL;
2150
2151 // Find the corresponding symbol map for strings.
2152 Map* map = string->map();
2153
2154 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
2155 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
2156 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
2157
2158 if (map == short_string_map()) return short_symbol_map();
2159 if (map == medium_string_map()) return medium_symbol_map();
2160 if (map == long_string_map()) return long_symbol_map();
2161
2162 if (map == short_cons_string_map()) return short_cons_symbol_map();
2163 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
2164 if (map == long_cons_string_map()) return long_cons_symbol_map();
2165
2166 if (map == short_cons_ascii_string_map()) {
2167 return short_cons_ascii_symbol_map();
2168 }
2169 if (map == medium_cons_ascii_string_map()) {
2170 return medium_cons_ascii_symbol_map();
2171 }
2172 if (map == long_cons_ascii_string_map()) {
2173 return long_cons_ascii_symbol_map();
2174 }
2175
2176 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002177 if (map == medium_sliced_string_map()) return medium_sliced_symbol_map();
2178 if (map == long_sliced_string_map()) return long_sliced_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002179
2180 if (map == short_sliced_ascii_string_map()) {
2181 return short_sliced_ascii_symbol_map();
2182 }
2183 if (map == medium_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002184 return medium_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002185 }
2186 if (map == long_sliced_ascii_string_map()) {
kasperl@chromium.org9fe21c62008-10-28 08:53:51 +00002187 return long_sliced_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002188 }
2189
ager@chromium.org6f10e412009-02-13 10:11:16 +00002190 if (map == short_external_string_map()) {
2191 return short_external_symbol_map();
2192 }
2193 if (map == medium_external_string_map()) {
2194 return medium_external_symbol_map();
2195 }
2196 if (map == long_external_string_map()) {
2197 return long_external_symbol_map();
2198 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002199
2200 if (map == short_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002201 return short_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002202 }
2203 if (map == medium_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002204 return medium_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002205 }
2206 if (map == long_external_ascii_string_map()) {
ager@chromium.org6f10e412009-02-13 10:11:16 +00002207 return long_external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002208 }
2209
2210 // No match found.
2211 return NULL;
2212}
2213
2214
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002215Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2216 int chars,
2217 uint32_t length_field) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002218 // Ensure the chars matches the number of characters in the buffer.
2219 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2220 // Determine whether the string is ascii.
2221 bool is_ascii = true;
ager@chromium.org6f10e412009-02-13 10:11:16 +00002222 while (buffer->has_more() && is_ascii) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002223 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
2224 }
2225 buffer->Rewind();
2226
2227 // Compute map and object size.
2228 int size;
2229 Map* map;
2230
2231 if (is_ascii) {
2232 if (chars <= String::kMaxShortStringSize) {
2233 map = short_ascii_symbol_map();
2234 } else if (chars <= String::kMaxMediumStringSize) {
2235 map = medium_ascii_symbol_map();
2236 } else {
2237 map = long_ascii_symbol_map();
2238 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002239 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002240 } else {
2241 if (chars <= String::kMaxShortStringSize) {
2242 map = short_symbol_map();
2243 } else if (chars <= String::kMaxMediumStringSize) {
2244 map = medium_symbol_map();
2245 } else {
2246 map = long_symbol_map();
2247 }
ager@chromium.org7c537e22008-10-16 08:43:32 +00002248 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002249 }
2250
2251 // Allocate string.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002252 AllocationSpace space =
2253 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_DATA_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002254 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002255 if (result->IsFailure()) return result;
2256
2257 reinterpret_cast<HeapObject*>(result)->set_map(map);
2258 // The hash value contains the length of the string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002259 String* answer = String::cast(result);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002260 answer->set_length_field(length_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002261
ager@chromium.org870a0b62008-11-04 11:43:05 +00002262 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002263
2264 // Fill in the characters.
2265 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002266 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002267 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002268 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002269}
2270
2271
2272Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002273 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002274 int size = SeqAsciiString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002275 if (size > MaxHeapObjectSize()) {
2276 space = LO_SPACE;
2277 }
2278
2279 // Use AllocateRaw rather than Allocate because the object's size cannot be
2280 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002281 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002282 if (result->IsFailure()) return result;
2283
2284 // Determine the map based on the string's length.
2285 Map* map;
2286 if (length <= String::kMaxShortStringSize) {
2287 map = short_ascii_string_map();
2288 } else if (length <= String::kMaxMediumStringSize) {
2289 map = medium_ascii_string_map();
2290 } else {
2291 map = long_ascii_string_map();
2292 }
2293
2294 // Partially initialize the object.
2295 HeapObject::cast(result)->set_map(map);
2296 String::cast(result)->set_length(length);
2297 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2298 return result;
2299}
2300
2301
2302Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002303 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org7c537e22008-10-16 08:43:32 +00002304 int size = SeqTwoByteString::SizeFor(length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002305 if (size > MaxHeapObjectSize()) {
2306 space = LO_SPACE;
2307 }
2308
2309 // Use AllocateRaw rather than Allocate because the object's size cannot be
2310 // determined from the map.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002311 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002312 if (result->IsFailure()) return result;
2313
2314 // Determine the map based on the string's length.
2315 Map* map;
2316 if (length <= String::kMaxShortStringSize) {
2317 map = short_string_map();
2318 } else if (length <= String::kMaxMediumStringSize) {
2319 map = medium_string_map();
2320 } else {
2321 map = long_string_map();
2322 }
2323
2324 // Partially initialize the object.
2325 HeapObject::cast(result)->set_map(map);
2326 String::cast(result)->set_length(length);
2327 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2328 return result;
2329}
2330
2331
2332Object* Heap::AllocateEmptyFixedArray() {
2333 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002334 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002335 if (result->IsFailure()) return result;
2336 // Initialize the object.
2337 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2338 reinterpret_cast<Array*>(result)->set_length(0);
2339 return result;
2340}
2341
2342
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002343Object* Heap::AllocateRawFixedArray(int length) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002344 // Use the general function if we're forced to always allocate.
2345 if (always_allocate()) return AllocateFixedArray(length, NOT_TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002346 // Allocate the raw data for a fixed array.
2347 int size = FixedArray::SizeFor(length);
2348 return (size > MaxHeapObjectSize())
2349 ? lo_space_->AllocateRawFixedArray(size)
2350 : new_space_.AllocateRaw(size);
2351}
2352
2353
2354Object* Heap::CopyFixedArray(FixedArray* src) {
2355 int len = src->length();
2356 Object* obj = AllocateRawFixedArray(len);
2357 if (obj->IsFailure()) return obj;
2358 if (Heap::InNewSpace(obj)) {
2359 HeapObject* dst = HeapObject::cast(obj);
2360 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2361 reinterpret_cast<Object**>(src->address()),
2362 FixedArray::SizeFor(len));
2363 return obj;
2364 }
2365 HeapObject::cast(obj)->set_map(src->map());
2366 FixedArray* result = FixedArray::cast(obj);
2367 result->set_length(len);
2368 // Copy the content
2369 WriteBarrierMode mode = result->GetWriteBarrierMode();
2370 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2371 return result;
2372}
2373
2374
2375Object* Heap::AllocateFixedArray(int length) {
ager@chromium.org32912102009-01-16 10:38:43 +00002376 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002377 Object* result = AllocateRawFixedArray(length);
2378 if (!result->IsFailure()) {
2379 // Initialize header.
2380 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2381 FixedArray* array = FixedArray::cast(result);
2382 array->set_length(length);
2383 Object* value = undefined_value();
2384 // Initialize body.
2385 for (int index = 0; index < length; index++) {
2386 array->set(index, value, SKIP_WRITE_BARRIER);
2387 }
2388 }
2389 return result;
2390}
2391
2392
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002393Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2394 ASSERT(empty_fixed_array()->IsFixedArray());
2395 if (length == 0) return empty_fixed_array();
2396
2397 int size = FixedArray::SizeFor(length);
2398 Object* result;
2399 if (size > MaxHeapObjectSize()) {
2400 result = lo_space_->AllocateRawFixedArray(size);
2401 } else {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002402 AllocationSpace space =
2403 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002404 result = AllocateRaw(size, space, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002405 }
2406 if (result->IsFailure()) return result;
2407
2408 // Initialize the object.
2409 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2410 FixedArray* array = FixedArray::cast(result);
2411 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002412 Object* value = undefined_value();
2413 for (int index = 0; index < length; index++) {
2414 array->set(index, value, SKIP_WRITE_BARRIER);
2415 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002416 return array;
2417}
2418
2419
2420Object* Heap::AllocateFixedArrayWithHoles(int length) {
2421 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002422 Object* result = AllocateRawFixedArray(length);
2423 if (!result->IsFailure()) {
2424 // Initialize header.
2425 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2426 FixedArray* array = FixedArray::cast(result);
2427 array->set_length(length);
2428 // Initialize body.
2429 Object* value = the_hole_value();
2430 for (int index = 0; index < length; index++) {
2431 array->set(index, value, SKIP_WRITE_BARRIER);
2432 }
2433 }
2434 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002435}
2436
2437
2438Object* Heap::AllocateHashTable(int length) {
2439 Object* result = Heap::AllocateFixedArray(length);
2440 if (result->IsFailure()) return result;
2441 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2442 ASSERT(result->IsDictionary());
2443 return result;
2444}
2445
2446
2447Object* Heap::AllocateGlobalContext() {
2448 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2449 if (result->IsFailure()) return result;
2450 Context* context = reinterpret_cast<Context*>(result);
2451 context->set_map(global_context_map());
2452 ASSERT(context->IsGlobalContext());
2453 ASSERT(result->IsContext());
2454 return result;
2455}
2456
2457
2458Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2459 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2460 Object* result = Heap::AllocateFixedArray(length);
2461 if (result->IsFailure()) return result;
2462 Context* context = reinterpret_cast<Context*>(result);
2463 context->set_map(context_map());
2464 context->set_closure(function);
2465 context->set_fcontext(context);
2466 context->set_previous(NULL);
2467 context->set_extension(NULL);
2468 context->set_global(function->context()->global());
2469 ASSERT(!context->IsGlobalContext());
2470 ASSERT(context->is_function_context());
2471 ASSERT(result->IsContext());
2472 return result;
2473}
2474
2475
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002476Object* Heap::AllocateWithContext(Context* previous,
2477 JSObject* extension,
2478 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002479 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2480 if (result->IsFailure()) return result;
2481 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00002482 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002483 context->set_closure(previous->closure());
2484 context->set_fcontext(previous->fcontext());
2485 context->set_previous(previous);
2486 context->set_extension(extension);
2487 context->set_global(previous->global());
2488 ASSERT(!context->IsGlobalContext());
2489 ASSERT(!context->is_function_context());
2490 ASSERT(result->IsContext());
2491 return result;
2492}
2493
2494
2495Object* Heap::AllocateStruct(InstanceType type) {
2496 Map* map;
2497 switch (type) {
2498#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2499STRUCT_LIST(MAKE_CASE)
2500#undef MAKE_CASE
2501 default:
2502 UNREACHABLE();
2503 return Failure::InternalError();
2504 }
2505 int size = map->instance_size();
2506 AllocationSpace space =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002507 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002508 Object* result = Heap::Allocate(map, space);
2509 if (result->IsFailure()) return result;
2510 Struct::cast(result)->InitializeBody(size);
2511 return result;
2512}
2513
2514
2515#ifdef DEBUG
2516
2517void Heap::Print() {
2518 if (!HasBeenSetup()) return;
2519 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002520 AllSpaces spaces;
2521 while (Space* space = spaces.next()) space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002522}
2523
2524
2525void Heap::ReportCodeStatistics(const char* title) {
2526 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2527 PagedSpace::ResetCodeStatistics();
2528 // We do not look for code in new space, map space, or old space. If code
2529 // somehow ends up in those spaces, we would miss it here.
2530 code_space_->CollectCodeStatistics();
2531 lo_space_->CollectCodeStatistics();
2532 PagedSpace::ReportCodeStatistics();
2533}
2534
2535
2536// This function expects that NewSpace's allocated objects histogram is
2537// populated (via a call to CollectStatistics or else as a side effect of a
2538// just-completed scavenge collection).
2539void Heap::ReportHeapStatistics(const char* title) {
2540 USE(title);
2541 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2542 title, gc_count_);
2543 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002544 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
2545 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002546
2547 PrintF("\n");
2548 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2549 GlobalHandles::PrintStats();
2550 PrintF("\n");
2551
2552 PrintF("Heap statistics : ");
2553 MemoryAllocator::ReportStatistics();
2554 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002555 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002556 PrintF("Old pointer space : ");
2557 old_pointer_space_->ReportStatistics();
2558 PrintF("Old data space : ");
2559 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002560 PrintF("Code space : ");
2561 code_space_->ReportStatistics();
2562 PrintF("Map space : ");
2563 map_space_->ReportStatistics();
2564 PrintF("Large object space : ");
2565 lo_space_->ReportStatistics();
2566 PrintF(">>>>>> ========================================= >>>>>>\n");
2567}
2568
2569#endif // DEBUG
2570
2571bool Heap::Contains(HeapObject* value) {
2572 return Contains(value->address());
2573}
2574
2575
2576bool Heap::Contains(Address addr) {
2577 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2578 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002579 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002580 old_pointer_space_->Contains(addr) ||
2581 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002582 code_space_->Contains(addr) ||
2583 map_space_->Contains(addr) ||
2584 lo_space_->SlowContains(addr));
2585}
2586
2587
2588bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2589 return InSpace(value->address(), space);
2590}
2591
2592
2593bool Heap::InSpace(Address addr, AllocationSpace space) {
2594 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2595 if (!HasBeenSetup()) return false;
2596
2597 switch (space) {
2598 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002599 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002600 case OLD_POINTER_SPACE:
2601 return old_pointer_space_->Contains(addr);
2602 case OLD_DATA_SPACE:
2603 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002604 case CODE_SPACE:
2605 return code_space_->Contains(addr);
2606 case MAP_SPACE:
2607 return map_space_->Contains(addr);
2608 case LO_SPACE:
2609 return lo_space_->SlowContains(addr);
2610 }
2611
2612 return false;
2613}
2614
2615
2616#ifdef DEBUG
2617void Heap::Verify() {
2618 ASSERT(HasBeenSetup());
2619
2620 VerifyPointersVisitor visitor;
2621 Heap::IterateRoots(&visitor);
2622
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002623 AllSpaces spaces;
2624 while (Space* space = spaces.next()) {
2625 space->Verify();
2626 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002627}
2628#endif // DEBUG
2629
2630
2631Object* Heap::LookupSymbol(Vector<const char> string) {
2632 Object* symbol = NULL;
2633 Object* new_table =
2634 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2635 if (new_table->IsFailure()) return new_table;
2636 symbol_table_ = new_table;
2637 ASSERT(symbol != NULL);
2638 return symbol;
2639}
2640
2641
2642Object* Heap::LookupSymbol(String* string) {
2643 if (string->IsSymbol()) return string;
2644 Object* symbol = NULL;
2645 Object* new_table =
2646 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2647 if (new_table->IsFailure()) return new_table;
2648 symbol_table_ = new_table;
2649 ASSERT(symbol != NULL);
2650 return symbol;
2651}
2652
2653
ager@chromium.org7c537e22008-10-16 08:43:32 +00002654bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
2655 if (string->IsSymbol()) {
2656 *symbol = string;
2657 return true;
2658 }
2659 SymbolTable* table = SymbolTable::cast(symbol_table_);
2660 return table->LookupSymbolIfExists(string, symbol);
2661}
2662
2663
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002664#ifdef DEBUG
2665void Heap::ZapFromSpace() {
2666 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002667 for (Address a = new_space_.FromSpaceLow();
2668 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002669 a += kPointerSize) {
2670 Memory::Address_at(a) = kFromSpaceZapValue;
2671 }
2672}
2673#endif // DEBUG
2674
2675
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002676int Heap::IterateRSetRange(Address object_start,
2677 Address object_end,
2678 Address rset_start,
2679 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002680 Address object_address = object_start;
2681 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002682 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002683
2684 // Loop over all the pointers in [object_start, object_end).
2685 while (object_address < object_end) {
2686 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002687 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002688 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002689 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002690 // Do not dereference pointers at or past object_end.
2691 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2692 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002693 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002694 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2695 }
2696 // If this pointer does not need to be remembered anymore, clear
2697 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002698 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002699 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002700 }
2701 object_address += kPointerSize;
2702 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002703 // Update the remembered set if it has changed.
2704 if (result_rset != rset_word) {
2705 Memory::uint32_at(rset_address) = result_rset;
2706 }
2707 } else {
2708 // No bits in the word were set. This is the common case.
2709 object_address += kPointerSize * kBitsPerInt;
2710 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002711 rset_address += kIntSize;
2712 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002713 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002714}
2715
2716
2717void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2718 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002719 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002720
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002721 static void* paged_rset_histogram = StatsTable::CreateHistogram(
2722 "V8.RSetPaged",
2723 0,
2724 Page::kObjectAreaSize / kPointerSize,
2725 30);
2726
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002727 PageIterator it(space, PageIterator::PAGES_IN_USE);
2728 while (it.has_next()) {
2729 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002730 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2731 page->RSetStart(), copy_object_func);
2732 if (paged_rset_histogram != NULL) {
2733 StatsTable::AddHistogramSample(paged_rset_histogram, count);
2734 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002735 }
2736}
2737
2738
2739#ifdef DEBUG
2740#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2741#else
2742#define SYNCHRONIZE_TAG(tag)
2743#endif
2744
2745void Heap::IterateRoots(ObjectVisitor* v) {
2746 IterateStrongRoots(v);
2747 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2748 SYNCHRONIZE_TAG("symbol_table");
2749}
2750
2751
2752void Heap::IterateStrongRoots(ObjectVisitor* v) {
2753#define ROOT_ITERATE(type, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002754 v->VisitPointer(bit_cast<Object**, type**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002755 STRONG_ROOT_LIST(ROOT_ITERATE);
2756#undef ROOT_ITERATE
2757 SYNCHRONIZE_TAG("strong_root_list");
2758
2759#define STRUCT_MAP_ITERATE(NAME, Name, name) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002760 v->VisitPointer(bit_cast<Object**, Map**>(&name##_map_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002761 STRUCT_LIST(STRUCT_MAP_ITERATE);
2762#undef STRUCT_MAP_ITERATE
2763 SYNCHRONIZE_TAG("struct_map");
2764
2765#define SYMBOL_ITERATE(name, string) \
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002766 v->VisitPointer(bit_cast<Object**, String**>(&name##_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002767 SYMBOL_LIST(SYMBOL_ITERATE)
2768#undef SYMBOL_ITERATE
ager@chromium.org3b45ab52009-03-19 22:21:34 +00002769 v->VisitPointer(bit_cast<Object**, String**>(&hidden_symbol_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002770 SYNCHRONIZE_TAG("symbol");
2771
2772 Bootstrapper::Iterate(v);
2773 SYNCHRONIZE_TAG("bootstrapper");
2774 Top::Iterate(v);
2775 SYNCHRONIZE_TAG("top");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002776
2777#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002778 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002779#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002780 SYNCHRONIZE_TAG("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002781 CompilationCache::Iterate(v);
2782 SYNCHRONIZE_TAG("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002783
2784 // Iterate over local handles in handle scopes.
2785 HandleScopeImplementer::Iterate(v);
2786 SYNCHRONIZE_TAG("handlescope");
2787
2788 // Iterate over the builtin code objects and code stubs in the heap. Note
2789 // that it is not strictly necessary to iterate over code objects on
2790 // scavenge collections. We still do it here because this same function
2791 // is used by the mark-sweep collector and the deserializer.
2792 Builtins::IterateBuiltins(v);
2793 SYNCHRONIZE_TAG("builtins");
2794
2795 // Iterate over global handles.
2796 GlobalHandles::IterateRoots(v);
2797 SYNCHRONIZE_TAG("globalhandles");
2798
2799 // Iterate over pointers being held by inactive threads.
2800 ThreadManager::Iterate(v);
2801 SYNCHRONIZE_TAG("threadmanager");
2802}
2803#undef SYNCHRONIZE_TAG
2804
2805
2806// Flag is set when the heap has been configured. The heap can be repeatedly
2807// configured through the API until it is setup.
2808static bool heap_configured = false;
2809
2810// TODO(1236194): Since the heap size is configurable on the command line
2811// and through the API, we should gracefully handle the case that the heap
2812// size is not big enough to fit all the initial objects.
2813bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2814 if (HasBeenSetup()) return false;
2815
2816 if (semispace_size > 0) semispace_size_ = semispace_size;
2817 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2818
2819 // The new space size must be a power of two to support single-bit testing
2820 // for containment.
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002821 semispace_size_ = RoundUpToPowerOf2(semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002822 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2823 young_generation_size_ = 2 * semispace_size_;
2824
2825 // The old generation is paged.
2826 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2827
2828 heap_configured = true;
2829 return true;
2830}
2831
2832
kasper.lund7276f142008-07-30 08:49:36 +00002833bool Heap::ConfigureHeapDefault() {
2834 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2835}
2836
2837
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002838int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002839 return old_pointer_space_->Size()
2840 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002841 + code_space_->Size()
2842 + map_space_->Size()
2843 + lo_space_->Size();
2844}
2845
2846
kasper.lund7276f142008-07-30 08:49:36 +00002847int Heap::PromotedExternalMemorySize() {
2848 if (amount_of_external_allocated_memory_
2849 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2850 return amount_of_external_allocated_memory_
2851 - amount_of_external_allocated_memory_at_last_global_gc_;
2852}
2853
2854
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002855bool Heap::Setup(bool create_heap_objects) {
2856 // Initialize heap spaces and initial maps and objects. Whenever something
2857 // goes wrong, just return false. The caller should check the results and
2858 // call Heap::TearDown() to release allocated memory.
2859 //
2860 // If the heap is not yet configured (eg, through the API), configure it.
2861 // Configuration is based on the flags new-space-size (really the semispace
2862 // size) and old-space-size if set or the initial values of semispace_size_
2863 // and old_generation_size_ otherwise.
2864 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002865 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002866 }
2867
2868 // Setup memory allocator and allocate an initial chunk of memory. The
2869 // initial chunk is double the size of the new space to ensure that we can
2870 // find a pair of semispaces that are contiguous and aligned to their size.
2871 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2872 void* chunk
2873 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2874 if (chunk == NULL) return false;
2875
2876 // Put the initial chunk of the old space at the start of the initial
2877 // chunk, then the two new space semispaces, then the initial chunk of
2878 // code space. Align the pair of semispaces to their size, which must be
2879 // a power of 2.
2880 ASSERT(IsPowerOf2(young_generation_size_));
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00002881 Address code_space_start = reinterpret_cast<Address>(chunk);
2882 Address new_space_start = RoundUp(code_space_start, young_generation_size_);
2883 Address old_space_start = new_space_start + young_generation_size_;
2884 int code_space_size = new_space_start - code_space_start;
2885 int old_space_size = young_generation_size_ - code_space_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002886
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002887 // Initialize new space.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002888 if (!new_space_.Setup(new_space_start, young_generation_size_)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002889
2890 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002891 // size. It will not contain code.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002892 old_pointer_space_ =
2893 new OldSpace(old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
2894 if (old_pointer_space_ == NULL) return false;
2895 if (!old_pointer_space_->Setup(old_space_start, old_space_size >> 1)) {
2896 return false;
2897 }
2898 old_data_space_ =
2899 new OldSpace(old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
2900 if (old_data_space_ == NULL) return false;
2901 if (!old_data_space_->Setup(old_space_start + (old_space_size >> 1),
2902 old_space_size >> 1)) {
2903 return false;
2904 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002905
2906 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002907 // generation size. It needs executable memory.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002908 code_space_ =
2909 new OldSpace(old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002910 if (code_space_ == NULL) return false;
2911 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2912
2913 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002914 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002915 if (map_space_ == NULL) return false;
2916 // Setting up a paged space without giving it a virtual memory range big
2917 // enough to hold at least a page will cause it to allocate.
2918 if (!map_space_->Setup(NULL, 0)) return false;
2919
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002920 // The large object code space may contain code or data. We set the memory
2921 // to be non-executable here for safety, but this means we need to enable it
2922 // explicitly when allocating large code objects.
2923 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002924 if (lo_space_ == NULL) return false;
2925 if (!lo_space_->Setup()) return false;
2926
2927 if (create_heap_objects) {
2928 // Create initial maps.
2929 if (!CreateInitialMaps()) return false;
2930 if (!CreateApiObjects()) return false;
2931
2932 // Create initial objects
2933 if (!CreateInitialObjects()) return false;
2934 }
2935
2936 LOG(IntEvent("heap-capacity", Capacity()));
2937 LOG(IntEvent("heap-available", Available()));
2938
2939 return true;
2940}
2941
2942
2943void Heap::TearDown() {
2944 GlobalHandles::TearDown();
2945
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002946 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002947
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002948 if (old_pointer_space_ != NULL) {
2949 old_pointer_space_->TearDown();
2950 delete old_pointer_space_;
2951 old_pointer_space_ = NULL;
2952 }
2953
2954 if (old_data_space_ != NULL) {
2955 old_data_space_->TearDown();
2956 delete old_data_space_;
2957 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002958 }
2959
2960 if (code_space_ != NULL) {
2961 code_space_->TearDown();
2962 delete code_space_;
2963 code_space_ = NULL;
2964 }
2965
2966 if (map_space_ != NULL) {
2967 map_space_->TearDown();
2968 delete map_space_;
2969 map_space_ = NULL;
2970 }
2971
2972 if (lo_space_ != NULL) {
2973 lo_space_->TearDown();
2974 delete lo_space_;
2975 lo_space_ = NULL;
2976 }
2977
2978 MemoryAllocator::TearDown();
2979}
2980
2981
2982void Heap::Shrink() {
2983 // Try to shrink map, old, and code spaces.
2984 map_space_->Shrink();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002985 old_pointer_space_->Shrink();
2986 old_data_space_->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002987 code_space_->Shrink();
2988}
2989
2990
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002991#ifdef ENABLE_HEAP_PROTECTION
2992
2993void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002994 if (HasBeenSetup()) {
2995 new_space_.Protect();
2996 map_space_->Protect();
2997 old_pointer_space_->Protect();
2998 old_data_space_->Protect();
2999 code_space_->Protect();
3000 lo_space_->Protect();
3001 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003002}
3003
3004
3005void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003006 if (HasBeenSetup()) {
3007 new_space_.Unprotect();
3008 map_space_->Unprotect();
3009 old_pointer_space_->Unprotect();
3010 old_data_space_->Unprotect();
3011 code_space_->Unprotect();
3012 lo_space_->Unprotect();
3013 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003014}
3015
3016#endif
3017
3018
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003019#ifdef DEBUG
3020
3021class PrintHandleVisitor: public ObjectVisitor {
3022 public:
3023 void VisitPointers(Object** start, Object** end) {
3024 for (Object** p = start; p < end; p++)
3025 PrintF(" handle %p to %p\n", p, *p);
3026 }
3027};
3028
3029void Heap::PrintHandles() {
3030 PrintF("Handles:\n");
3031 PrintHandleVisitor v;
3032 HandleScopeImplementer::Iterate(&v);
3033}
3034
3035#endif
3036
3037
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003038Space* AllSpaces::next() {
3039 switch (counter_++) {
3040 case NEW_SPACE:
3041 return Heap::new_space();
3042 case OLD_POINTER_SPACE:
3043 return Heap::old_pointer_space();
3044 case OLD_DATA_SPACE:
3045 return Heap::old_data_space();
3046 case CODE_SPACE:
3047 return Heap::code_space();
3048 case MAP_SPACE:
3049 return Heap::map_space();
3050 case LO_SPACE:
3051 return Heap::lo_space();
3052 default:
3053 return NULL;
3054 }
3055}
3056
3057
3058PagedSpace* PagedSpaces::next() {
3059 switch (counter_++) {
3060 case OLD_POINTER_SPACE:
3061 return Heap::old_pointer_space();
3062 case OLD_DATA_SPACE:
3063 return Heap::old_data_space();
3064 case CODE_SPACE:
3065 return Heap::code_space();
3066 case MAP_SPACE:
3067 return Heap::map_space();
3068 default:
3069 return NULL;
3070 }
3071}
3072
3073
3074
3075OldSpace* OldSpaces::next() {
3076 switch (counter_++) {
3077 case OLD_POINTER_SPACE:
3078 return Heap::old_pointer_space();
3079 case OLD_DATA_SPACE:
3080 return Heap::old_data_space();
3081 case CODE_SPACE:
3082 return Heap::code_space();
3083 default:
3084 return NULL;
3085 }
3086}
3087
3088
kasper.lund7276f142008-07-30 08:49:36 +00003089SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3090}
3091
3092
3093SpaceIterator::~SpaceIterator() {
3094 // Delete active iterator if any.
3095 delete iterator_;
3096}
3097
3098
3099bool SpaceIterator::has_next() {
3100 // Iterate until no more spaces.
3101 return current_space_ != LAST_SPACE;
3102}
3103
3104
3105ObjectIterator* SpaceIterator::next() {
3106 if (iterator_ != NULL) {
3107 delete iterator_;
3108 iterator_ = NULL;
3109 // Move to the next space
3110 current_space_++;
3111 if (current_space_ > LAST_SPACE) {
3112 return NULL;
3113 }
3114 }
3115
3116 // Return iterator for the new current space.
3117 return CreateIterator();
3118}
3119
3120
3121// Create an iterator for the space to iterate.
3122ObjectIterator* SpaceIterator::CreateIterator() {
3123 ASSERT(iterator_ == NULL);
3124
3125 switch (current_space_) {
3126 case NEW_SPACE:
3127 iterator_ = new SemiSpaceIterator(Heap::new_space());
3128 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003129 case OLD_POINTER_SPACE:
3130 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3131 break;
3132 case OLD_DATA_SPACE:
3133 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003134 break;
3135 case CODE_SPACE:
3136 iterator_ = new HeapObjectIterator(Heap::code_space());
3137 break;
3138 case MAP_SPACE:
3139 iterator_ = new HeapObjectIterator(Heap::map_space());
3140 break;
3141 case LO_SPACE:
3142 iterator_ = new LargeObjectIterator(Heap::lo_space());
3143 break;
3144 }
3145
3146 // Return the newly allocated iterator;
3147 ASSERT(iterator_ != NULL);
3148 return iterator_;
3149}
3150
3151
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003152HeapIterator::HeapIterator() {
3153 Init();
3154}
3155
3156
3157HeapIterator::~HeapIterator() {
3158 Shutdown();
3159}
3160
3161
3162void HeapIterator::Init() {
3163 // Start the iteration.
3164 space_iterator_ = new SpaceIterator();
3165 object_iterator_ = space_iterator_->next();
3166}
3167
3168
3169void HeapIterator::Shutdown() {
3170 // Make sure the last iterator is deallocated.
3171 delete space_iterator_;
3172 space_iterator_ = NULL;
3173 object_iterator_ = NULL;
3174}
3175
3176
3177bool HeapIterator::has_next() {
3178 // No iterator means we are done.
3179 if (object_iterator_ == NULL) return false;
3180
3181 if (object_iterator_->has_next_object()) {
3182 // If the current iterator has more objects we are fine.
3183 return true;
3184 } else {
3185 // Go though the spaces looking for one that has objects.
3186 while (space_iterator_->has_next()) {
3187 object_iterator_ = space_iterator_->next();
3188 if (object_iterator_->has_next_object()) {
3189 return true;
3190 }
3191 }
3192 }
3193 // Done with the last space.
3194 object_iterator_ = NULL;
3195 return false;
3196}
3197
3198
3199HeapObject* HeapIterator::next() {
3200 if (has_next()) {
3201 return object_iterator_->next_object();
3202 } else {
3203 return NULL;
3204 }
3205}
3206
3207
3208void HeapIterator::reset() {
3209 // Restart the iterator.
3210 Shutdown();
3211 Init();
3212}
3213
3214
3215//
3216// HeapProfiler class implementation.
3217//
3218#ifdef ENABLE_LOGGING_AND_PROFILING
3219void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
3220 InstanceType type = obj->map()->instance_type();
3221 ASSERT(0 <= type && type <= LAST_TYPE);
3222 info[type].increment_number(1);
3223 info[type].increment_bytes(obj->Size());
3224}
3225#endif
3226
3227
3228#ifdef ENABLE_LOGGING_AND_PROFILING
3229void HeapProfiler::WriteSample() {
3230 LOG(HeapSampleBeginEvent("Heap", "allocated"));
3231
3232 HistogramInfo info[LAST_TYPE+1];
3233#define DEF_TYPE_NAME(name) info[name].set_name(#name);
3234 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
3235#undef DEF_TYPE_NAME
3236
3237 HeapIterator iterator;
3238 while (iterator.has_next()) {
3239 CollectStats(iterator.next(), info);
3240 }
3241
3242 // Lump all the string types together.
3243 int string_number = 0;
3244 int string_bytes = 0;
3245#define INCREMENT_SIZE(type, size, name) \
3246 string_number += info[type].number(); \
3247 string_bytes += info[type].bytes();
3248 STRING_TYPE_LIST(INCREMENT_SIZE)
3249#undef INCREMENT_SIZE
3250 if (string_bytes > 0) {
3251 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
3252 }
3253
3254 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
3255 if (info[i].bytes() > 0) {
3256 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
3257 info[i].bytes()));
3258 }
3259 }
3260
3261 LOG(HeapSampleEndEvent("Heap", "allocated"));
3262}
3263
3264
3265#endif
3266
3267
3268
3269#ifdef DEBUG
3270
3271static bool search_for_any_global;
3272static Object* search_target;
3273static bool found_target;
3274static List<Object*> object_stack(20);
3275
3276
3277// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
3278static const int kMarkTag = 2;
3279
3280static void MarkObjectRecursively(Object** p);
3281class MarkObjectVisitor : public ObjectVisitor {
3282 public:
3283 void VisitPointers(Object** start, Object** end) {
3284 // Copy all HeapObject pointers in [start, end)
3285 for (Object** p = start; p < end; p++) {
3286 if ((*p)->IsHeapObject())
3287 MarkObjectRecursively(p);
3288 }
3289 }
3290};
3291
3292static MarkObjectVisitor mark_visitor;
3293
3294static void MarkObjectRecursively(Object** p) {
3295 if (!(*p)->IsHeapObject()) return;
3296
3297 HeapObject* obj = HeapObject::cast(*p);
3298
3299 Object* map = obj->map();
3300
3301 if (!map->IsHeapObject()) return; // visited before
3302
3303 if (found_target) return; // stop if target found
3304 object_stack.Add(obj);
3305 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
3306 (!search_for_any_global && (obj == search_target))) {
3307 found_target = true;
3308 return;
3309 }
3310
3311 if (obj->IsCode()) {
3312 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
3313 }
3314
3315 // not visited yet
3316 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
3317
3318 Address map_addr = map_p->address();
3319
3320 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
3321
3322 MarkObjectRecursively(&map);
3323
3324 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
3325 &mark_visitor);
3326
3327 if (!found_target) // don't pop if found the target
3328 object_stack.RemoveLast();
3329}
3330
3331
3332static void UnmarkObjectRecursively(Object** p);
3333class UnmarkObjectVisitor : public ObjectVisitor {
3334 public:
3335 void VisitPointers(Object** start, Object** end) {
3336 // Copy all HeapObject pointers in [start, end)
3337 for (Object** p = start; p < end; p++) {
3338 if ((*p)->IsHeapObject())
3339 UnmarkObjectRecursively(p);
3340 }
3341 }
3342};
3343
3344static UnmarkObjectVisitor unmark_visitor;
3345
3346static void UnmarkObjectRecursively(Object** p) {
3347 if (!(*p)->IsHeapObject()) return;
3348
3349 HeapObject* obj = HeapObject::cast(*p);
3350
3351 Object* map = obj->map();
3352
3353 if (map->IsHeapObject()) return; // unmarked already
3354
3355 Address map_addr = reinterpret_cast<Address>(map);
3356
3357 map_addr -= kMarkTag;
3358
3359 ASSERT_TAG_ALIGNED(map_addr);
3360
3361 HeapObject* map_p = HeapObject::FromAddress(map_addr);
3362
3363 obj->set_map(reinterpret_cast<Map*>(map_p));
3364
3365 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
3366
3367 obj->IterateBody(Map::cast(map_p)->instance_type(),
3368 obj->SizeFromMap(Map::cast(map_p)),
3369 &unmark_visitor);
3370
3371 if (obj->IsCode()) {
3372 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
3373 }
3374}
3375
3376
3377static void MarkRootObjectRecursively(Object** root) {
3378 if (search_for_any_global) {
3379 ASSERT(search_target == NULL);
3380 } else {
3381 ASSERT(search_target->IsHeapObject());
3382 }
3383 found_target = false;
3384 object_stack.Clear();
3385
3386 MarkObjectRecursively(root);
3387 UnmarkObjectRecursively(root);
3388
3389 if (found_target) {
3390 PrintF("=====================================\n");
3391 PrintF("==== Path to object ====\n");
3392 PrintF("=====================================\n\n");
3393
3394 ASSERT(!object_stack.is_empty());
3395 for (int i = 0; i < object_stack.length(); i++) {
3396 if (i > 0) PrintF("\n |\n |\n V\n\n");
3397 Object* obj = object_stack[i];
3398 obj->Print();
3399 }
3400 PrintF("=====================================\n");
3401 }
3402}
3403
3404
3405// Helper class for visiting HeapObjects recursively.
3406class MarkRootVisitor: public ObjectVisitor {
3407 public:
3408 void VisitPointers(Object** start, Object** end) {
3409 // Visit all HeapObject pointers in [start, end)
3410 for (Object** p = start; p < end; p++) {
3411 if ((*p)->IsHeapObject())
3412 MarkRootObjectRecursively(p);
3413 }
3414 }
3415};
3416
3417
3418// Triggers a depth-first traversal of reachable objects from roots
3419// and finds a path to a specific heap object and prints it.
3420void Heap::TracePathToObject() {
3421 search_target = NULL;
3422 search_for_any_global = false;
3423
3424 MarkRootVisitor root_visitor;
3425 IterateRoots(&root_visitor);
3426}
3427
3428
3429// Triggers a depth-first traversal of reachable objects from roots
3430// and finds a path to any global object and prints it. Useful for
3431// determining the source for leaks of global objects.
3432void Heap::TracePathToGlobal() {
3433 search_target = NULL;
3434 search_for_any_global = true;
3435
3436 MarkRootVisitor root_visitor;
3437 IterateRoots(&root_visitor);
3438}
3439#endif
3440
3441
kasper.lund7276f142008-07-30 08:49:36 +00003442GCTracer::GCTracer()
3443 : start_time_(0.0),
3444 start_size_(0.0),
3445 gc_count_(0),
3446 full_gc_count_(0),
3447 is_compacting_(false),
3448 marked_count_(0) {
3449 // These two fields reflect the state of the previous full collection.
3450 // Set them before they are changed by the collector.
3451 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
3452 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
3453 if (!FLAG_trace_gc) return;
3454 start_time_ = OS::TimeCurrentMillis();
3455 start_size_ = SizeOfHeapObjects();
3456}
3457
3458
3459GCTracer::~GCTracer() {
3460 if (!FLAG_trace_gc) return;
3461 // Printf ONE line iff flag is set.
3462 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
3463 CollectorString(),
3464 start_size_, SizeOfHeapObjects(),
3465 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
3466}
3467
3468
3469const char* GCTracer::CollectorString() {
3470 switch (collector_) {
3471 case SCAVENGER:
3472 return "Scavenge";
3473 case MARK_COMPACTOR:
3474 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
3475 : "Mark-sweep";
3476 }
3477 return "Unknown GC";
3478}
3479
3480
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003481#ifdef DEBUG
3482bool Heap::GarbageCollectionGreedyCheck() {
3483 ASSERT(FLAG_gc_greedy);
3484 if (Bootstrapper::IsActive()) return true;
3485 if (disallow_allocation_failure()) return true;
3486 return CollectGarbage(0, NEW_SPACE);
3487}
3488#endif
3489
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003490} } // namespace v8::internal