blob: 058c08488d9205292fa7bce0386a4897dd825b9c [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. All Rights Reserved.
2// 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"
34#include "debug.h"
35#include "global-handles.h"
36#include "jsregexp.h"
37#include "mark-compact.h"
38#include "natives.h"
39#include "scanner.h"
40#include "scopeinfo.h"
41#include "v8threads.h"
42
43namespace v8 { namespace internal {
44
45#ifdef DEBUG
46DEFINE_bool(gc_greedy, false, "perform GC prior to some allocations");
47DEFINE_bool(gc_verbose, false, "print stuff during garbage collection");
48DEFINE_bool(heap_stats, false, "report heap statistics before and after GC");
49DEFINE_bool(code_stats, false, "report code statistics after GC");
50DEFINE_bool(verify_heap, false, "verify heap pointers before and after GC");
51DEFINE_bool(print_handles, false, "report handles after GC");
52DEFINE_bool(print_global_handles, false, "report global handles after GC");
53DEFINE_bool(print_rset, false, "print remembered sets before GC");
54#endif
55
56DEFINE_int(new_space_size, 0, "size of (each semispace in) the new generation");
57DEFINE_int(old_space_size, 0, "size of the old generation");
58
59DEFINE_bool(gc_global, false, "always perform global GCs");
60DEFINE_int(gc_interval, -1, "garbage collect after <n> allocations");
61DEFINE_bool(trace_gc, false,
62 "print one trace line following each garbage collection");
63
64
65#ifdef ENABLE_LOGGING_AND_PROFILING
66DECLARE_bool(log_gc);
67#endif
68
69
70#define ROOT_ALLOCATION(type, name) type* Heap::name##_;
71 ROOT_LIST(ROOT_ALLOCATION)
72#undef ROOT_ALLOCATION
73
74
75#define STRUCT_ALLOCATION(NAME, Name, name) Map* Heap::name##_map_;
76 STRUCT_LIST(STRUCT_ALLOCATION)
77#undef STRUCT_ALLOCATION
78
79
80#define SYMBOL_ALLOCATION(name, string) String* Heap::name##_;
81 SYMBOL_LIST(SYMBOL_ALLOCATION)
82#undef SYMBOL_ALLOCATION
83
84
85NewSpace* Heap::new_space_ = NULL;
86OldSpace* Heap::old_space_ = NULL;
87OldSpace* Heap::code_space_ = NULL;
88MapSpace* Heap::map_space_ = NULL;
89LargeObjectSpace* Heap::lo_space_ = NULL;
90
91int Heap::promoted_space_limit_ = 0;
92int Heap::old_gen_exhausted_ = false;
93
kasper.lund7276f142008-07-30 08:49:36 +000094int Heap::amount_of_external_allocated_memory_ = 0;
95int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
96
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000097// semispace_size_ should be a power of 2 and old_generation_size_ should be
98// a multiple of Page::kPageSize.
99int Heap::semispace_size_ = 1*MB;
100int Heap::old_generation_size_ = 512*MB;
101int Heap::initial_semispace_size_ = 256*KB;
102
103GCCallback Heap::global_gc_prologue_callback_ = NULL;
104GCCallback Heap::global_gc_epilogue_callback_ = NULL;
105
106// Variables set based on semispace_size_ and old_generation_size_ in
107// ConfigureHeap.
108int Heap::young_generation_size_ = 0; // Will be 2 * semispace_size_.
109
110// Double the new space after this many scavenge collections.
111int Heap::new_space_growth_limit_ = 8;
112int Heap::scavenge_count_ = 0;
113Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
114
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115int Heap::mc_count_ = 0;
116int Heap::gc_count_ = 0;
117
kasper.lund7276f142008-07-30 08:49:36 +0000118#ifdef DEBUG
119bool Heap::allocation_allowed_ = true;
120
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000121int Heap::allocation_timeout_ = 0;
122bool Heap::disallow_allocation_failure_ = false;
123#endif // DEBUG
124
125
126int Heap::Capacity() {
127 if (!HasBeenSetup()) return 0;
128
129 return new_space_->Capacity() +
130 old_space_->Capacity() +
131 code_space_->Capacity() +
132 map_space_->Capacity();
133}
134
135
136int Heap::Available() {
137 if (!HasBeenSetup()) return 0;
138
139 return new_space_->Available() +
140 old_space_->Available() +
141 code_space_->Available() +
142 map_space_->Available();
143}
144
145
146bool Heap::HasBeenSetup() {
147 return new_space_ != NULL &&
148 old_space_ != NULL &&
149 code_space_ != NULL &&
150 map_space_ != NULL &&
151 lo_space_ != NULL;
152}
153
154
155GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
156 // Is global GC requested?
157 if (space != NEW_SPACE || FLAG_gc_global) {
158 Counters::gc_compactor_caused_by_request.Increment();
159 return MARK_COMPACTOR;
160 }
161
162 // Is enough data promoted to justify a global GC?
kasper.lund7276f142008-07-30 08:49:36 +0000163 if (PromotedSpaceSize() + PromotedExternalMemorySize()
164 > promoted_space_limit_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 Counters::gc_compactor_caused_by_promoted_data.Increment();
166 return MARK_COMPACTOR;
167 }
168
169 // Have allocation in OLD and LO failed?
170 if (old_gen_exhausted_) {
171 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
172 return MARK_COMPACTOR;
173 }
174
175 // Is there enough space left in OLD to guarantee that a scavenge can
176 // succeed?
177 //
178 // Note that old_space_->MaxAvailable() undercounts the memory available
179 // for object promotion. It counts only the bytes that the memory
180 // allocator has not yet allocated from the OS and assigned to any space,
181 // and does not count available bytes already in the old space or code
182 // space. Undercounting is safe---we may get an unrequested full GC when
183 // a scavenge would have succeeded.
184 if (old_space_->MaxAvailable() <= new_space_->Size()) {
185 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
186 return MARK_COMPACTOR;
187 }
188
189 // Default
190 return SCAVENGER;
191}
192
193
194// TODO(1238405): Combine the infrastructure for --heap-stats and
195// --log-gc to avoid the complicated preprocessor and flag testing.
196#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
197void Heap::ReportStatisticsBeforeGC() {
198 // Heap::ReportHeapStatistics will also log NewSpace statistics when
199 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
200 // following logic is used to avoid double logging.
201#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
202 if (FLAG_heap_stats || FLAG_log_gc) new_space_->CollectStatistics();
203 if (FLAG_heap_stats) {
204 ReportHeapStatistics("Before GC");
205 } else if (FLAG_log_gc) {
206 new_space_->ReportStatistics();
207 }
208 if (FLAG_heap_stats || FLAG_log_gc) new_space_->ClearHistograms();
209#elif defined(DEBUG)
210 if (FLAG_heap_stats) {
211 new_space_->CollectStatistics();
212 ReportHeapStatistics("Before GC");
213 new_space_->ClearHistograms();
214 }
215#elif defined(ENABLE_LOGGING_AND_PROFILING)
216 if (FLAG_log_gc) {
217 new_space_->CollectStatistics();
218 new_space_->ReportStatistics();
219 new_space_->ClearHistograms();
220 }
221#endif
222}
223
224
225// TODO(1238405): Combine the infrastructure for --heap-stats and
226// --log-gc to avoid the complicated preprocessor and flag testing.
227void Heap::ReportStatisticsAfterGC() {
228 // Similar to the before GC, we use some complicated logic to ensure that
229 // NewSpace statistics are logged exactly once when --log-gc is turned on.
230#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
231 if (FLAG_heap_stats) {
232 ReportHeapStatistics("After GC");
233 } else if (FLAG_log_gc) {
234 new_space_->ReportStatistics();
235 }
236#elif defined(DEBUG)
237 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
238#elif defined(ENABLE_LOGGING_AND_PROFILING)
239 if (FLAG_log_gc) new_space_->ReportStatistics();
240#endif
241}
242#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
243
244
245void Heap::GarbageCollectionPrologue() {
246 RegExpImpl::NewSpaceCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000247 gc_count_++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248#ifdef DEBUG
249 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
250 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000251
252 if (FLAG_verify_heap) {
253 Verify();
254 }
255
256 if (FLAG_gc_verbose) Print();
257
258 if (FLAG_print_rset) {
259 // By definition, code space does not have remembered set bits that we
260 // care about.
261 old_space_->PrintRSet();
262 map_space_->PrintRSet();
263 lo_space_->PrintRSet();
264 }
265#endif
266
267#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
268 ReportStatisticsBeforeGC();
269#endif
270}
271
272int Heap::SizeOfObjects() {
273 return new_space_->Size() +
274 old_space_->Size() +
275 code_space_->Size() +
276 map_space_->Size() +
277 lo_space_->Size();
278}
279
280void Heap::GarbageCollectionEpilogue() {
281#ifdef DEBUG
282 allow_allocation(true);
283 ZapFromSpace();
284
285 if (FLAG_verify_heap) {
286 Verify();
287 }
288
289 if (FLAG_print_global_handles) GlobalHandles::Print();
290 if (FLAG_print_handles) PrintHandles();
291 if (FLAG_gc_verbose) Print();
292 if (FLAG_code_stats) ReportCodeStatistics("After GC");
293#endif
294
295 Counters::alive_after_last_gc.Set(SizeOfObjects());
296
297 SymbolTable* symbol_table = SymbolTable::cast(Heap::symbol_table_);
298 Counters::symbol_table_capacity.Set(symbol_table->Capacity());
299 Counters::number_of_symbols.Set(symbol_table->NumberOfElements());
300#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
301 ReportStatisticsAfterGC();
302#endif
303}
304
305
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000306bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
307 // The VM is in the GC state until exiting this function.
308 VMState state(GC);
309
310#ifdef DEBUG
311 // Reset the allocation timeout to the GC interval, but make sure to
312 // allow at least a few allocations after a collection. The reason
313 // for this is that we have a lot of allocation sequences and we
314 // assume that a garbage collection will allow the subsequent
315 // allocation attempts to go through.
316 allocation_timeout_ = Max(6, FLAG_gc_interval);
317#endif
318
319 { GCTracer tracer;
320 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000321 // The GC count was incremented in the prologue. Tell the tracer about
322 // it.
323 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324
325 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000326 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000327 tracer.set_collector(collector);
328
329 StatsRate* rate = (collector == SCAVENGER)
330 ? &Counters::gc_scavenger
331 : &Counters::gc_compactor;
332 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000333 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 rate->Stop();
335
336 GarbageCollectionEpilogue();
337 }
338
339
340#ifdef ENABLE_LOGGING_AND_PROFILING
341 if (FLAG_log_gc) HeapProfiler::WriteSample();
342#endif
343
344 switch (space) {
345 case NEW_SPACE:
346 return new_space_->Available() >= requested_size;
347 case OLD_SPACE:
348 return old_space_->Available() >= requested_size;
349 case CODE_SPACE:
350 return code_space_->Available() >= requested_size;
351 case MAP_SPACE:
352 return map_space_->Available() >= requested_size;
353 case LO_SPACE:
354 return lo_space_->Available() >= requested_size;
355 }
356 return false;
357}
358
359
kasper.lund7276f142008-07-30 08:49:36 +0000360void Heap::PerformScavenge() {
361 GCTracer tracer;
362 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
363}
364
365
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000366void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000367 GarbageCollector collector,
368 GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000369 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
370 ASSERT(!allocation_allowed_);
371 global_gc_prologue_callback_();
372 }
373
374 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000375 MarkCompact(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000376
377 int promoted_space_size = PromotedSpaceSize();
378 promoted_space_limit_ =
379 promoted_space_size + Max(2 * MB, (promoted_space_size/100) * 35);
380 old_gen_exhausted_ = false;
381
382 // If we have used the mark-compact collector to collect the new
383 // space, and it has not compacted the new space, we force a
384 // separate scavenge collection. THIS IS A HACK. It covers the
385 // case where (1) a new space collection was requested, (2) the
386 // collector selection policy selected the mark-compact collector,
387 // and (3) the mark-compact collector policy selected not to
388 // compact the new space. In that case, there is no more (usable)
389 // free space in the new space after the collection compared to
390 // before.
391 if (space == NEW_SPACE && !MarkCompactCollector::HasCompacted()) {
392 Scavenge();
393 }
394 } else {
395 Scavenge();
396 }
397 Counters::objs_since_last_young.Set(0);
398
399 // Process weak handles post gc.
400 GlobalHandles::PostGarbageCollectionProcessing();
401
kasper.lund7276f142008-07-30 08:49:36 +0000402 if (collector == MARK_COMPACTOR) {
403 // Register the amount of external allocated memory.
404 amount_of_external_allocated_memory_at_last_global_gc_ =
405 amount_of_external_allocated_memory_;
406 }
407
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000408 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
409 ASSERT(!allocation_allowed_);
410 global_gc_epilogue_callback_();
411 }
412}
413
414
kasper.lund7276f142008-07-30 08:49:36 +0000415void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000416 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000417 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000418 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000419 LOG(ResourceEvent("markcompact", "begin"));
420
421 MarkCompactPrologue();
422
kasper.lund7276f142008-07-30 08:49:36 +0000423 MarkCompactCollector::CollectGarbage(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000424
425 MarkCompactEpilogue();
426
427 LOG(ResourceEvent("markcompact", "end"));
428
429 gc_state_ = NOT_IN_GC;
430
431 Shrink();
432
433 Counters::objs_since_last_full.Set(0);
434}
435
436
437void Heap::MarkCompactPrologue() {
438 RegExpImpl::OldSpaceCollectionPrologue();
439 Top::MarkCompactPrologue();
440 ThreadManager::MarkCompactPrologue();
441}
442
443
444void Heap::MarkCompactEpilogue() {
445 Top::MarkCompactEpilogue();
446 ThreadManager::MarkCompactEpilogue();
447}
448
449
450Object* Heap::FindCodeObject(Address a) {
451 Object* obj = code_space_->FindObject(a);
452 if (obj->IsFailure()) {
453 obj = lo_space_->FindObject(a);
454 }
kasper.lund7276f142008-07-30 08:49:36 +0000455 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000456 return obj;
457}
458
459
460// Helper class for copying HeapObjects
461class CopyVisitor: public ObjectVisitor {
462 public:
463
464 void VisitPointer(Object** p) {
465 CopyObject(p);
466 }
467
468 void VisitPointers(Object** start, Object** end) {
469 // Copy all HeapObject pointers in [start, end)
470 for (Object** p = start; p < end; p++) CopyObject(p);
471 }
472
473 private:
474 void CopyObject(Object** p) {
475 if (!Heap::InFromSpace(*p)) return;
476 Heap::CopyObject(reinterpret_cast<HeapObject**>(p));
477 }
478};
479
480
481// Shared state read by the scavenge collector and set by CopyObject.
482static Address promoted_top = NULL;
483
484
485#ifdef DEBUG
486// Visitor class to verify pointers in code space do not point into
487// new space.
488class VerifyCodeSpacePointersVisitor: public ObjectVisitor {
489 public:
490 void VisitPointers(Object** start, Object**end) {
491 for (Object** current = start; current < end; current++) {
492 if ((*current)->IsHeapObject()) {
493 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
494 }
495 }
496 }
497};
498#endif
499
500void Heap::Scavenge() {
501#ifdef DEBUG
502 if (FLAG_enable_slow_asserts) {
503 VerifyCodeSpacePointersVisitor v;
504 HeapObjectIterator it(code_space_);
505 while (it.has_next()) {
506 HeapObject* object = it.next();
507 if (object->IsCode()) {
508 Code::cast(object)->ConvertICTargetsFromAddressToObject();
509 }
510 object->Iterate(&v);
511 if (object->IsCode()) {
512 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
513 }
514 }
515 }
516#endif
517
518 gc_state_ = SCAVENGE;
519
520 // Implements Cheney's copying algorithm
521 LOG(ResourceEvent("scavenge", "begin"));
522
523 scavenge_count_++;
524 if (new_space_->Capacity() < new_space_->MaximumCapacity() &&
525 scavenge_count_ > new_space_growth_limit_) {
526 // Double the size of the new space, and double the limit. The next
527 // doubling attempt will occur after the current new_space_growth_limit_
528 // more collections.
529 // TODO(1240712): NewSpace::Double has a return value which is
530 // ignored here.
531 new_space_->Double();
532 new_space_growth_limit_ *= 2;
533 }
534
535 // Flip the semispaces. After flipping, to space is empty, from space has
536 // live objects.
537 new_space_->Flip();
538 new_space_->ResetAllocationInfo();
539
540 // We need to sweep newly copied objects which can be in either the to space
541 // or the old space. For to space objects, we use a mark. Newly copied
542 // objects lie between the mark and the allocation top. For objects
543 // promoted to old space, we write their addresses downward from the top of
544 // the new space. Sweeping newly promoted objects requires an allocation
545 // pointer and a mark. Note that the allocation pointer 'top' actually
546 // moves downward from the high address in the to space.
547 //
548 // There is guaranteed to be enough room at the top of the to space for the
549 // addresses of promoted objects: every object promoted frees up its size in
550 // bytes from the top of the new space, and objects are at least one pointer
551 // in size. Using the new space to record promoted addresses makes the
552 // scavenge collector agnostic to the allocation strategy (eg, linear or
553 // free-list) used in old space.
554 Address new_mark = new_space_->ToSpaceLow();
555 Address promoted_mark = new_space_->ToSpaceHigh();
556 promoted_top = new_space_->ToSpaceHigh();
557
558 CopyVisitor copy_visitor;
559 // Copy roots.
560 IterateRoots(&copy_visitor);
561
562 // Copy objects reachable from the old generation. By definition, there
563 // are no intergenerational pointers in code space.
564 IterateRSet(old_space_, &CopyObject);
565 IterateRSet(map_space_, &CopyObject);
566 lo_space_->IterateRSet(&CopyObject);
567
568 bool has_processed_weak_pointers = false;
569
570 while (true) {
571 ASSERT(new_mark <= new_space_->top());
572 ASSERT(promoted_mark >= promoted_top);
573
574 // Copy objects reachable from newly copied objects.
575 while (new_mark < new_space_->top() || promoted_mark > promoted_top) {
576 // Sweep newly copied objects in the to space. The allocation pointer
577 // can change during sweeping.
578 Address previous_top = new_space_->top();
579 SemiSpaceIterator new_it(new_space_, new_mark);
580 while (new_it.has_next()) {
581 new_it.next()->Iterate(&copy_visitor);
582 }
583 new_mark = previous_top;
584
585 // Sweep newly copied objects in the old space. The promotion 'top'
586 // pointer could change during sweeping.
587 previous_top = promoted_top;
588 for (Address current = promoted_mark - kPointerSize;
589 current >= previous_top;
590 current -= kPointerSize) {
591 HeapObject* object = HeapObject::cast(Memory::Object_at(current));
592 object->Iterate(&copy_visitor);
593 UpdateRSet(object);
594 }
595 promoted_mark = previous_top;
596 }
597
598 if (has_processed_weak_pointers) break; // We are done.
599 // Copy objects reachable from weak pointers.
600 GlobalHandles::IterateWeakRoots(&copy_visitor);
601 has_processed_weak_pointers = true;
602 }
603
604 // Set age mark.
605 new_space_->set_age_mark(new_mark);
606
607 LOG(ResourceEvent("scavenge", "end"));
608
609 gc_state_ = NOT_IN_GC;
610}
611
612
613void Heap::ClearRSetRange(Address start, int size_in_bytes) {
614 uint32_t start_bit;
615 Address start_word_address =
616 Page::ComputeRSetBitPosition(start, 0, &start_bit);
617 uint32_t end_bit;
618 Address end_word_address =
619 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
620 0,
621 &end_bit);
622
623 // We want to clear the bits in the starting word starting with the
624 // first bit, and in the ending word up to and including the last
625 // bit. Build a pair of bitmasks to do that.
626 uint32_t start_bitmask = start_bit - 1;
627 uint32_t end_bitmask = ~((end_bit << 1) - 1);
628
629 // If the start address and end address are the same, we mask that
630 // word once, otherwise mask the starting and ending word
631 // separately and all the ones in between.
632 if (start_word_address == end_word_address) {
633 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
634 } else {
635 Memory::uint32_at(start_word_address) &= start_bitmask;
636 Memory::uint32_at(end_word_address) &= end_bitmask;
637 start_word_address += kIntSize;
638 memset(start_word_address, 0, end_word_address - start_word_address);
639 }
640}
641
642
643class UpdateRSetVisitor: public ObjectVisitor {
644 public:
645
646 void VisitPointer(Object** p) {
647 UpdateRSet(p);
648 }
649
650 void VisitPointers(Object** start, Object** end) {
651 // Update a store into slots [start, end), used (a) to update remembered
652 // set when promoting a young object to old space or (b) to rebuild
653 // remembered sets after a mark-compact collection.
654 for (Object** p = start; p < end; p++) UpdateRSet(p);
655 }
656 private:
657
658 void UpdateRSet(Object** p) {
659 // The remembered set should not be set. It should be clear for objects
660 // newly copied to old space, and it is cleared before rebuilding in the
661 // mark-compact collector.
662 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
663 if (Heap::InNewSpace(*p)) {
664 Page::SetRSet(reinterpret_cast<Address>(p), 0);
665 }
666 }
667};
668
669
670int Heap::UpdateRSet(HeapObject* obj) {
671 ASSERT(!InNewSpace(obj));
672 // Special handling of fixed arrays to iterate the body based on the start
673 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
674 // will not work because Page::SetRSet needs to have the start of the
675 // object.
676 if (obj->IsFixedArray()) {
677 FixedArray* array = FixedArray::cast(obj);
678 int length = array->length();
679 for (int i = 0; i < length; i++) {
680 int offset = FixedArray::kHeaderSize + i * kPointerSize;
681 ASSERT(!Page::IsRSetSet(obj->address(), offset));
682 if (Heap::InNewSpace(array->get(i))) {
683 Page::SetRSet(obj->address(), offset);
684 }
685 }
686 } else if (!obj->IsCode()) {
687 // Skip code object, we know it does not contain inter-generational
688 // pointers.
689 UpdateRSetVisitor v;
690 obj->Iterate(&v);
691 }
692 return obj->Size();
693}
694
695
696void Heap::RebuildRSets() {
697 // By definition, we do not care about remembered set bits in code space.
698 map_space_->ClearRSet();
699 RebuildRSets(map_space_);
700
701 old_space_->ClearRSet();
702 RebuildRSets(old_space_);
703
704 Heap::lo_space_->ClearRSet();
705 RebuildRSets(lo_space_);
706}
707
708
709void Heap::RebuildRSets(PagedSpace* space) {
710 HeapObjectIterator it(space);
711 while (it.has_next()) Heap::UpdateRSet(it.next());
712}
713
714
715void Heap::RebuildRSets(LargeObjectSpace* space) {
716 LargeObjectIterator it(space);
717 while (it.has_next()) Heap::UpdateRSet(it.next());
718}
719
720
721#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
722void Heap::RecordCopiedObject(HeapObject* obj) {
723 bool should_record = false;
724#ifdef DEBUG
725 should_record = FLAG_heap_stats;
726#endif
727#ifdef ENABLE_LOGGING_AND_PROFILING
728 should_record = should_record || FLAG_log_gc;
729#endif
730 if (should_record) {
731 if (new_space_->Contains(obj)) {
732 new_space_->RecordAllocation(obj);
733 } else {
734 new_space_->RecordPromotion(obj);
735 }
736 }
737}
738#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
739
740
741HeapObject* Heap::MigrateObject(HeapObject** source_p,
742 HeapObject* target,
743 int size) {
744 void** src = reinterpret_cast<void**>((*source_p)->address());
745 void** dst = reinterpret_cast<void**>(target->address());
746 int counter = size/kPointerSize - 1;
747 do {
748 *dst++ = *src++;
749 } while (counter-- > 0);
750
kasper.lund7276f142008-07-30 08:49:36 +0000751 // Set the forwarding address.
752 (*source_p)->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753
754 // Update NewSpace stats if necessary.
755#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
756 RecordCopiedObject(target);
757#endif
758
759 return target;
760}
761
762
763void Heap::CopyObject(HeapObject** p) {
764 ASSERT(InFromSpace(*p));
765
766 HeapObject* object = *p;
767
kasper.lund7276f142008-07-30 08:49:36 +0000768 // We use the first word (where the map pointer usually is) of a heap
769 // object to record the forwarding pointer. A forwarding pointer can
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770 // point to the old space, the code space, or the to space of the new
771 // generation.
kasper.lund7276f142008-07-30 08:49:36 +0000772 MapWord first_word = object->map_word();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773
kasper.lund7276f142008-07-30 08:49:36 +0000774 // If the first word is a forwarding address, the object has already been
775 // copied.
776 if (first_word.IsForwardingAddress()) {
777 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000778 return;
779 }
780
781 // Optimization: Bypass ConsString objects where the right-hand side is
782 // Heap::empty_string(). We do not use object->IsConsString because we
783 // already know that object has the heap object tag.
kasper.lund7276f142008-07-30 08:49:36 +0000784 InstanceType type = first_word.ToMap()->instance_type();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000785 if (type < FIRST_NONSTRING_TYPE &&
786 String::cast(object)->representation_tag() == kConsStringTag &&
787 ConsString::cast(object)->second() == Heap::empty_string()) {
788 object = HeapObject::cast(ConsString::cast(object)->first());
789 *p = object;
790 // After patching *p we have to repeat the checks that object is in the
791 // active semispace of the young generation and not already copied.
792 if (!InFromSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +0000793 first_word = object->map_word();
794 if (first_word.IsForwardingAddress()) {
795 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796 return;
797 }
kasper.lund7276f142008-07-30 08:49:36 +0000798 type = first_word.ToMap()->instance_type();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000799 }
800
kasper.lund7276f142008-07-30 08:49:36 +0000801 int object_size = object->SizeFromMap(first_word.ToMap());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000802 Object* result;
803 // If the object should be promoted, we try to copy it to old space.
804 if (ShouldBePromoted(object->address(), object_size)) {
kasper.lund7276f142008-07-30 08:49:36 +0000805 AllocationSpace target_space = Heap::TargetSpace(object);
806 if (target_space == OLD_SPACE) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000807 result = old_space_->AllocateRaw(object_size);
808 } else {
kasper.lund7276f142008-07-30 08:49:36 +0000809 ASSERT(target_space == CODE_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000810 result = code_space_->AllocateRaw(object_size);
811 }
812
813 if (!result->IsFailure()) {
814 *p = MigrateObject(p, HeapObject::cast(result), object_size);
kasper.lund7276f142008-07-30 08:49:36 +0000815 if (target_space == OLD_SPACE) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816 // Record the object's address at the top of the to space, to allow
817 // it to be swept by the scavenger.
818 promoted_top -= kPointerSize;
819 Memory::Object_at(promoted_top) = *p;
820 } else {
821#ifdef DEBUG
822 // Objects promoted to the code space should not have pointers to
823 // new space.
824 VerifyCodeSpacePointersVisitor v;
825 (*p)->Iterate(&v);
826#endif
827 }
828 return;
829 }
830 }
831
832 // The object should remain in new space or the old space allocation failed.
833 result = new_space_->AllocateRaw(object_size);
834 // Failed allocation at this point is utterly unexpected.
835 ASSERT(!result->IsFailure());
836 *p = MigrateObject(p, HeapObject::cast(result), object_size);
837}
838
839
840Object* Heap::AllocatePartialMap(InstanceType instance_type,
841 int instance_size) {
842 Object* result = AllocateRawMap(Map::kSize);
843 if (result->IsFailure()) return result;
844
845 // Map::cast cannot be used due to uninitialized map field.
846 reinterpret_cast<Map*>(result)->set_map(meta_map());
847 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
848 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
849 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
850 return result;
851}
852
853
854Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
855 Object* result = AllocateRawMap(Map::kSize);
856 if (result->IsFailure()) return result;
857
858 Map* map = reinterpret_cast<Map*>(result);
859 map->set_map(meta_map());
860 map->set_instance_type(instance_type);
861 map->set_prototype(null_value());
862 map->set_constructor(null_value());
863 map->set_instance_size(instance_size);
864 map->set_instance_descriptors(DescriptorArray::cast(empty_fixed_array()));
865 map->set_code_cache(empty_fixed_array());
866 map->set_unused_property_fields(0);
867 map->set_bit_field(0);
868 return map;
869}
870
871
872bool Heap::CreateInitialMaps() {
873 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
874 if (obj->IsFailure()) return false;
875
876 // Map::cast cannot be used due to uninitialized map field.
877 meta_map_ = reinterpret_cast<Map*>(obj);
878 meta_map()->set_map(meta_map());
879
880 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, Array::kHeaderSize);
881 if (obj->IsFailure()) return false;
882 fixed_array_map_ = Map::cast(obj);
883
884 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
885 if (obj->IsFailure()) return false;
886 oddball_map_ = Map::cast(obj);
887
888 // Allocate the empty array
889 obj = AllocateEmptyFixedArray();
890 if (obj->IsFailure()) return false;
891 empty_fixed_array_ = FixedArray::cast(obj);
892
893 obj = Allocate(oddball_map(), CODE_SPACE);
894 if (obj->IsFailure()) return false;
895 null_value_ = obj;
896
897 // Fix the instance_descriptors for the existing maps.
898 DescriptorArray* empty_descriptors =
899 DescriptorArray::cast(empty_fixed_array());
900
901 meta_map()->set_instance_descriptors(empty_descriptors);
902 meta_map()->set_code_cache(empty_fixed_array());
903
904 fixed_array_map()->set_instance_descriptors(empty_descriptors);
905 fixed_array_map()->set_code_cache(empty_fixed_array());
906
907 oddball_map()->set_instance_descriptors(empty_descriptors);
908 oddball_map()->set_code_cache(empty_fixed_array());
909
910 // Fix prototype object for existing maps.
911 meta_map()->set_prototype(null_value());
912 meta_map()->set_constructor(null_value());
913
914 fixed_array_map()->set_prototype(null_value());
915 fixed_array_map()->set_constructor(null_value());
916 oddball_map()->set_prototype(null_value());
917 oddball_map()->set_constructor(null_value());
918
919 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
920 if (obj->IsFailure()) return false;
921 heap_number_map_ = Map::cast(obj);
922
923 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
924 if (obj->IsFailure()) return false;
925 proxy_map_ = Map::cast(obj);
926
927#define ALLOCATE_STRING_MAP(type, size, name) \
928 obj = AllocateMap(type, size); \
929 if (obj->IsFailure()) return false; \
930 name##_map_ = Map::cast(obj);
931 STRING_TYPE_LIST(ALLOCATE_STRING_MAP);
932#undef ALLOCATE_STRING_MAP
933
934 obj = AllocateMap(SHORT_STRING_TYPE, TwoByteString::kHeaderSize);
935 if (obj->IsFailure()) return false;
936 undetectable_short_string_map_ = Map::cast(obj);
937 undetectable_short_string_map_->set_is_undetectable();
938
939 obj = AllocateMap(MEDIUM_STRING_TYPE, TwoByteString::kHeaderSize);
940 if (obj->IsFailure()) return false;
941 undetectable_medium_string_map_ = Map::cast(obj);
942 undetectable_medium_string_map_->set_is_undetectable();
943
944 obj = AllocateMap(LONG_STRING_TYPE, TwoByteString::kHeaderSize);
945 if (obj->IsFailure()) return false;
946 undetectable_long_string_map_ = Map::cast(obj);
947 undetectable_long_string_map_->set_is_undetectable();
948
949 obj = AllocateMap(SHORT_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
950 if (obj->IsFailure()) return false;
951 undetectable_short_ascii_string_map_ = Map::cast(obj);
952 undetectable_short_ascii_string_map_->set_is_undetectable();
953
954 obj = AllocateMap(MEDIUM_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
955 if (obj->IsFailure()) return false;
956 undetectable_medium_ascii_string_map_ = Map::cast(obj);
957 undetectable_medium_ascii_string_map_->set_is_undetectable();
958
959 obj = AllocateMap(LONG_ASCII_STRING_TYPE, AsciiString::kHeaderSize);
960 if (obj->IsFailure()) return false;
961 undetectable_long_ascii_string_map_ = Map::cast(obj);
962 undetectable_long_ascii_string_map_->set_is_undetectable();
963
964 obj = AllocateMap(BYTE_ARRAY_TYPE, Array::kHeaderSize);
965 if (obj->IsFailure()) return false;
966 byte_array_map_ = Map::cast(obj);
967
968 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
969 if (obj->IsFailure()) return false;
970 code_map_ = Map::cast(obj);
971
972 obj = AllocateMap(FILLER_TYPE, kPointerSize);
973 if (obj->IsFailure()) return false;
974 one_word_filler_map_ = Map::cast(obj);
975
976 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
977 if (obj->IsFailure()) return false;
978 two_word_filler_map_ = Map::cast(obj);
979
980#define ALLOCATE_STRUCT_MAP(NAME, Name, name) \
981 obj = AllocateMap(NAME##_TYPE, Name::kSize); \
982 if (obj->IsFailure()) return false; \
983 name##_map_ = Map::cast(obj);
984 STRUCT_LIST(ALLOCATE_STRUCT_MAP)
985#undef ALLOCATE_STRUCT_MAP
986
987 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
988 if (obj->IsFailure()) return false;
989 hash_table_map_ = Map::cast(obj);
990
991 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
992 if (obj->IsFailure()) return false;
993 context_map_ = Map::cast(obj);
994
995 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kSize);
996 if (obj->IsFailure()) return false;
997 global_context_map_ = Map::cast(obj);
998
999 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1000 if (obj->IsFailure()) return false;
1001 boilerplate_function_map_ = Map::cast(obj);
1002
1003 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE, SharedFunctionInfo::kSize);
1004 if (obj->IsFailure()) return false;
1005 shared_function_info_map_ = Map::cast(obj);
1006
1007 return true;
1008}
1009
1010
1011Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1012 // Statically ensure that it is safe to allocate heap numbers in paged
1013 // spaces.
1014 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1015 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
1016 Object* result = AllocateRaw(HeapNumber::kSize, space);
1017 if (result->IsFailure()) return result;
1018
1019 HeapObject::cast(result)->set_map(heap_number_map());
1020 HeapNumber::cast(result)->set_value(value);
1021 return result;
1022}
1023
1024
1025Object* Heap::AllocateHeapNumber(double value) {
1026 // This version of AllocateHeapNumber is optimized for
1027 // allocation in new space.
1028 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1029 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1030 Object* result = new_space_->AllocateRaw(HeapNumber::kSize);
1031 if (result->IsFailure()) return result;
1032 HeapObject::cast(result)->set_map(heap_number_map());
1033 HeapNumber::cast(result)->set_value(value);
1034 return result;
1035}
1036
1037
1038Object* Heap::CreateOddball(Map* map,
1039 const char* to_string,
1040 Object* to_number) {
1041 Object* result = Allocate(map, CODE_SPACE);
1042 if (result->IsFailure()) return result;
1043 return Oddball::cast(result)->Initialize(to_string, to_number);
1044}
1045
1046
1047bool Heap::CreateApiObjects() {
1048 Object* obj;
1049
1050 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1051 if (obj->IsFailure()) return false;
1052 neander_map_ = Map::cast(obj);
1053
1054 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1055 if (obj->IsFailure()) return false;
1056 Object* elements = AllocateFixedArray(2);
1057 if (elements->IsFailure()) return false;
1058 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1059 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1060 message_listeners_ = JSObject::cast(obj);
1061
1062 obj = Heap::AllocateJSObjectFromMap(neander_map_);
1063 if (obj->IsFailure()) return false;
1064 elements = AllocateFixedArray(2);
1065 if (elements->IsFailure()) return false;
1066 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1067 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1068 debug_event_listeners_ = JSObject::cast(obj);
1069
1070 return true;
1071}
1072
1073void Heap::CreateFixedStubs() {
1074 // Here we create roots for fixed stubs. They are needed at GC
1075 // for cooking and uncooking (check out frames.cc).
1076 // The eliminates the need for doing dictionary lookup in the
1077 // stub cache for these stubs.
1078 HandleScope scope;
1079 {
1080 CEntryStub stub;
1081 c_entry_code_ = *stub.GetCode();
1082 }
1083 {
1084 CEntryDebugBreakStub stub;
1085 c_entry_debug_break_code_ = *stub.GetCode();
1086 }
1087 {
1088 JSEntryStub stub;
1089 js_entry_code_ = *stub.GetCode();
1090 }
1091 {
1092 JSConstructEntryStub stub;
1093 js_construct_entry_code_ = *stub.GetCode();
1094 }
1095}
1096
1097
1098bool Heap::CreateInitialObjects() {
1099 Object* obj;
1100
1101 // The -0 value must be set before NumberFromDouble works.
1102 obj = AllocateHeapNumber(-0.0, TENURED);
1103 if (obj->IsFailure()) return false;
1104 minus_zero_value_ = obj;
1105 ASSERT(signbit(minus_zero_value_->Number()) != 0);
1106
1107 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1108 if (obj->IsFailure()) return false;
1109 nan_value_ = obj;
1110
1111 obj = NumberFromDouble(INFINITY, TENURED);
1112 if (obj->IsFailure()) return false;
1113 infinity_value_ = obj;
1114
1115 obj = NumberFromDouble(-INFINITY, TENURED);
1116 if (obj->IsFailure()) return false;
1117 negative_infinity_value_ = obj;
1118
1119 obj = NumberFromDouble(DBL_MAX, TENURED);
1120 if (obj->IsFailure()) return false;
1121 number_max_value_ = obj;
1122
1123 // C++ doesn't provide a constant for the smallest denormalized
1124 // double (approx. 5e-324) but only the smallest normalized one
1125 // which is somewhat bigger (approx. 2e-308). So we have to do
1126 // this raw conversion hack.
1127 uint64_t min_value_bits = 1L;
1128 double min_value = *reinterpret_cast<double*>(&min_value_bits);
1129 obj = NumberFromDouble(min_value, TENURED);
1130 if (obj->IsFailure()) return false;
1131 number_min_value_ = obj;
1132
1133 obj = Allocate(oddball_map(), CODE_SPACE);
1134 if (obj->IsFailure()) return false;
1135 undefined_value_ = obj;
1136 ASSERT(!InNewSpace(undefined_value()));
1137
1138 // Allocate initial symbol table.
1139 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1140 if (obj->IsFailure()) return false;
1141 symbol_table_ = obj;
1142
1143 // Assign the print strings for oddballs after creating symboltable.
1144 Object* symbol = LookupAsciiSymbol("undefined");
1145 if (symbol->IsFailure()) return false;
1146 Oddball::cast(undefined_value_)->set_to_string(String::cast(symbol));
1147 Oddball::cast(undefined_value_)->set_to_number(nan_value_);
1148
1149 // Assign the print strings for oddballs after creating symboltable.
1150 symbol = LookupAsciiSymbol("null");
1151 if (symbol->IsFailure()) return false;
1152 Oddball::cast(null_value_)->set_to_string(String::cast(symbol));
1153 Oddball::cast(null_value_)->set_to_number(Smi::FromInt(0));
1154
1155 // Allocate the null_value
1156 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1157 if (obj->IsFailure()) return false;
1158
1159 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1160 if (obj->IsFailure()) return false;
1161 true_value_ = obj;
1162
1163 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1164 if (obj->IsFailure()) return false;
1165 false_value_ = obj;
1166
1167 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1168 if (obj->IsFailure()) return false;
1169 the_hole_value_ = obj;
1170
1171 // Allocate the empty string.
1172 obj = AllocateRawAsciiString(0, TENURED);
1173 if (obj->IsFailure()) return false;
1174 empty_string_ = String::cast(obj);
1175
1176#define SYMBOL_INITIALIZE(name, string) \
1177 obj = LookupAsciiSymbol(string); \
1178 if (obj->IsFailure()) return false; \
1179 (name##_) = String::cast(obj);
1180 SYMBOL_LIST(SYMBOL_INITIALIZE)
1181#undef SYMBOL_INITIALIZE
1182
1183 // Allocate the proxy for __proto__.
1184 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1185 if (obj->IsFailure()) return false;
1186 prototype_accessors_ = Proxy::cast(obj);
1187
1188 // Allocate the code_stubs dictionary.
1189 obj = Dictionary::Allocate(4);
1190 if (obj->IsFailure()) return false;
1191 code_stubs_ = Dictionary::cast(obj);
1192
1193 // Allocate the non_monomorphic_cache used in stub-cache.cc
1194 obj = Dictionary::Allocate(4);
1195 if (obj->IsFailure()) return false;
1196 non_monomorphic_cache_ = Dictionary::cast(obj);
1197
1198 CreateFixedStubs();
1199
1200 // Allocate the number->string conversion cache
1201 obj = AllocateFixedArray(kNumberStringCacheSize * 2);
1202 if (obj->IsFailure()) return false;
1203 number_string_cache_ = FixedArray::cast(obj);
1204
1205 // Allocate cache for single character strings.
1206 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1);
1207 if (obj->IsFailure()) return false;
1208 single_character_string_cache_ = FixedArray::cast(obj);
1209
1210 // Allocate cache for external strings pointing to native source code.
1211 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1212 if (obj->IsFailure()) return false;
1213 natives_source_cache_ = FixedArray::cast(obj);
1214
1215 return true;
1216}
1217
1218
1219static inline int double_get_hash(double d) {
1220 DoubleRepresentation rep(d);
1221 return ((static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) &
1222 (Heap::kNumberStringCacheSize - 1));
1223}
1224
1225
1226static inline int smi_get_hash(Smi* smi) {
1227 return (smi->value() & (Heap::kNumberStringCacheSize - 1));
1228}
1229
1230
1231
1232Object* Heap::GetNumberStringCache(Object* number) {
1233 int hash;
1234 if (number->IsSmi()) {
1235 hash = smi_get_hash(Smi::cast(number));
1236 } else {
1237 hash = double_get_hash(number->Number());
1238 }
1239 Object* key = number_string_cache_->get(hash * 2);
1240 if (key == number) {
1241 return String::cast(number_string_cache_->get(hash * 2 + 1));
1242 } else if (key->IsHeapNumber() &&
1243 number->IsHeapNumber() &&
1244 key->Number() == number->Number()) {
1245 return String::cast(number_string_cache_->get(hash * 2 + 1));
1246 }
1247 return undefined_value();
1248}
1249
1250
1251void Heap::SetNumberStringCache(Object* number, String* string) {
1252 int hash;
1253 if (number->IsSmi()) {
1254 hash = smi_get_hash(Smi::cast(number));
1255 number_string_cache_->set(hash * 2, number, FixedArray::SKIP_WRITE_BARRIER);
1256 } else {
1257 hash = double_get_hash(number->Number());
1258 number_string_cache_->set(hash * 2, number);
1259 }
1260 number_string_cache_->set(hash * 2 + 1, string);
1261}
1262
1263
1264Object* Heap::SmiOrNumberFromDouble(double value,
1265 bool new_object,
1266 PretenureFlag pretenure) {
1267 // We need to distinguish the minus zero value and this cannot be
1268 // done after conversion to int. Doing this by comparing bit
1269 // patterns is faster than using fpclassify() et al.
1270 static const DoubleRepresentation plus_zero(0.0);
1271 static const DoubleRepresentation minus_zero(-0.0);
1272 static const DoubleRepresentation nan(OS::nan_value());
1273 ASSERT(minus_zero_value_ != NULL);
1274 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1275
1276 DoubleRepresentation rep(value);
1277 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1278 if (rep.bits == minus_zero.bits) {
1279 return new_object ? AllocateHeapNumber(-0.0, pretenure)
1280 : minus_zero_value_;
1281 }
1282 if (rep.bits == nan.bits) {
1283 return new_object
1284 ? AllocateHeapNumber(OS::nan_value(), pretenure)
1285 : nan_value_;
1286 }
1287
1288 // Try to represent the value as a tagged small integer.
1289 int int_value = FastD2I(value);
1290 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1291 return Smi::FromInt(int_value);
1292 }
1293
1294 // Materialize the value in the heap.
1295 return AllocateHeapNumber(value, pretenure);
1296}
1297
1298
1299Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1300 return SmiOrNumberFromDouble(value,
1301 true /* number object must be new */,
1302 pretenure);
1303}
1304
1305
1306Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1307 return SmiOrNumberFromDouble(value,
1308 false /* use preallocated NaN, -0.0 */,
1309 pretenure);
1310}
1311
1312
1313Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1314 // Statically ensure that it is safe to allocate proxies in paged spaces.
1315 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
1316 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1317 Object* result = Allocate(proxy_map(), space);
1318 if (result->IsFailure()) return result;
1319
1320 Proxy::cast(result)->set_proxy(proxy);
1321 return result;
1322}
1323
1324
1325Object* Heap::AllocateSharedFunctionInfo(Object* name) {
1326 Object* result = Allocate(shared_function_info_map(), NEW_SPACE);
1327 if (result->IsFailure()) return result;
1328
1329 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1330 share->set_name(name);
1331 Code* illegal = Builtins::builtin(Builtins::Illegal);
1332 share->set_code(illegal);
1333 share->set_expected_nof_properties(0);
1334 share->set_length(0);
1335 share->set_formal_parameter_count(0);
1336 share->set_instance_class_name(Object_symbol());
1337 share->set_function_data(undefined_value());
1338 share->set_lazy_load_data(undefined_value());
1339 share->set_script(undefined_value());
1340 share->set_start_position_and_type(0);
1341 share->set_debug_info(undefined_value());
1342 return result;
1343}
1344
1345
1346Object* Heap::AllocateConsString(String* first, String* second) {
1347 int length = first->length() + second->length();
1348 bool is_ascii = first->is_ascii() && second->is_ascii();
1349
1350 // If the resulting string is small make a flat string.
1351 if (length < ConsString::kMinLength) {
1352 Object* result = is_ascii
1353 ? AllocateRawAsciiString(length)
1354 : AllocateRawTwoByteString(length);
1355 if (result->IsFailure()) return result;
1356 // Copy the characters into the new object.
1357 String* string_result = String::cast(result);
1358 int first_length = first->length();
1359 // Copy the content of the first string.
1360 for (int i = 0; i < first_length; i++) {
1361 string_result->Set(i, first->Get(i));
1362 }
1363 int second_length = second->length();
1364 // Copy the content of the first string.
1365 for (int i = 0; i < second_length; i++) {
1366 string_result->Set(first_length + i, second->Get(i));
1367 }
1368 return result;
1369 }
1370
1371 Map* map;
1372 if (length <= String::kMaxShortStringSize) {
1373 map = is_ascii ? short_cons_ascii_string_map()
1374 : short_cons_string_map();
1375 } else if (length <= String::kMaxMediumStringSize) {
1376 map = is_ascii ? medium_cons_ascii_string_map()
1377 : medium_cons_string_map();
1378 } else {
1379 map = is_ascii ? long_cons_ascii_string_map()
1380 : long_cons_string_map();
1381 }
1382
1383 Object* result = Allocate(map, NEW_SPACE);
1384 if (result->IsFailure()) return result;
1385
1386 ConsString* cons_string = ConsString::cast(result);
1387 cons_string->set_first(first);
1388 cons_string->set_second(second);
1389 cons_string->set_length(length);
1390
1391 return result;
1392}
1393
1394
1395Object* Heap::AllocateSlicedString(String* buffer, int start, int end) {
1396 int length = end - start;
1397
1398 // If the resulting string is small make a sub string.
1399 if (end - start <= SlicedString::kMinLength) {
1400 return Heap::AllocateSubString(buffer, start, end);
1401 }
1402
1403 Map* map;
1404 if (length <= String::kMaxShortStringSize) {
1405 map = buffer->is_ascii() ? short_sliced_ascii_string_map()
1406 : short_sliced_string_map();
1407 } else if (length <= String::kMaxMediumStringSize) {
1408 map = buffer->is_ascii() ? medium_sliced_ascii_string_map()
1409 : medium_sliced_string_map();
1410 } else {
1411 map = buffer->is_ascii() ? long_sliced_ascii_string_map()
1412 : long_sliced_string_map();
1413 }
1414
1415 Object* result = Allocate(map, NEW_SPACE);
1416 if (result->IsFailure()) return result;
1417
1418 SlicedString* sliced_string = SlicedString::cast(result);
1419 sliced_string->set_buffer(buffer);
1420 sliced_string->set_start(start);
1421 sliced_string->set_length(length);
1422
1423 return result;
1424}
1425
1426
1427Object* Heap::AllocateSubString(String* buffer, int start, int end) {
1428 int length = end - start;
1429
1430 // Make an attempt to flatten the buffer to reduce access time.
1431 buffer->TryFlatten();
1432
1433 Object* result = buffer->is_ascii()
1434 ? AllocateRawAsciiString(length)
1435 : AllocateRawTwoByteString(length);
1436 if (result->IsFailure()) return result;
1437
1438 // Copy the characters into the new object.
1439 String* string_result = String::cast(result);
1440 for (int i = 0; i < length; i++) {
1441 string_result->Set(i, buffer->Get(start + i));
1442 }
1443 return result;
1444}
1445
1446
1447Object* Heap::AllocateExternalStringFromAscii(
1448 ExternalAsciiString::Resource* resource) {
1449 Map* map;
1450 int length = resource->length();
1451 if (length <= String::kMaxShortStringSize) {
1452 map = short_external_ascii_string_map();
1453 } else if (length <= String::kMaxMediumStringSize) {
1454 map = medium_external_ascii_string_map();
1455 } else {
1456 map = long_external_ascii_string_map();
1457 }
1458
1459 Object* result = Allocate(map, NEW_SPACE);
1460 if (result->IsFailure()) return result;
1461
1462 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
1463 external_string->set_length(length);
1464 external_string->set_resource(resource);
1465
1466 return result;
1467}
1468
1469
1470Object* Heap::AllocateExternalStringFromTwoByte(
1471 ExternalTwoByteString::Resource* resource) {
1472 Map* map;
1473 int length = resource->length();
1474 if (length <= String::kMaxShortStringSize) {
1475 map = short_external_string_map();
1476 } else if (length <= String::kMaxMediumStringSize) {
1477 map = medium_external_string_map();
1478 } else {
1479 map = long_external_string_map();
1480 }
1481
1482 Object* result = Allocate(map, NEW_SPACE);
1483 if (result->IsFailure()) return result;
1484
1485 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
1486 external_string->set_length(length);
1487 external_string->set_resource(resource);
1488
1489 return result;
1490}
1491
1492
1493Object* Heap:: LookupSingleCharacterStringFromCode(uint16_t code) {
1494 if (code <= String::kMaxAsciiCharCode) {
1495 Object* value = Heap::single_character_string_cache()->get(code);
1496 if (value != Heap::undefined_value()) return value;
1497 Object* result = Heap::AllocateRawAsciiString(1);
1498 if (result->IsFailure()) return result;
1499 String::cast(result)->Set(0, code);
1500 Heap::single_character_string_cache()->set(code, result);
1501 return result;
1502 }
1503 Object* result = Heap::AllocateRawTwoByteString(1);
1504 if (result->IsFailure()) return result;
1505 String::cast(result)->Set(0, code);
1506 return result;
1507}
1508
1509
1510Object* Heap::AllocateByteArray(int length) {
1511 int size = ByteArray::SizeFor(length);
1512 AllocationSpace space = size > MaxHeapObjectSize() ? LO_SPACE : NEW_SPACE;
1513
1514 Object* result = AllocateRaw(size, space);
1515 if (result->IsFailure()) return result;
1516
1517 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
1518 reinterpret_cast<Array*>(result)->set_length(length);
1519 return result;
1520}
1521
1522
1523Object* Heap::CreateCode(const CodeDesc& desc,
1524 ScopeInfo<>* sinfo,
1525 Code::Flags flags) {
1526 // Compute size
1527 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
1528 int sinfo_size = 0;
1529 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
1530 int obj_size = Code::SizeFor(body_size, sinfo_size);
1531 AllocationSpace space =
1532 (obj_size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1533
1534 Object* result = AllocateRaw(obj_size, space);
1535 if (result->IsFailure()) return result;
1536
1537 // Initialize the object
1538 HeapObject::cast(result)->set_map(code_map());
1539 Code* code = Code::cast(result);
1540 code->set_instruction_size(desc.instr_size);
1541 code->set_relocation_size(desc.reloc_size);
1542 code->set_sinfo_size(sinfo_size);
1543 code->set_flags(flags);
1544 code->set_ic_flag(Code::IC_TARGET_IS_ADDRESS);
1545 code->CopyFrom(desc); // migrate generated code
1546 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
1547
1548#ifdef DEBUG
1549 code->Verify();
1550#endif
1551
1552 CPU::FlushICache(code->instruction_start(), code->instruction_size());
1553
1554 return code;
1555}
1556
1557
1558Object* Heap::CopyCode(Code* code) {
1559 // Allocate an object the same size as the code object.
1560 int obj_size = code->Size();
1561 AllocationSpace space =
1562 (obj_size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1563 Object* result = AllocateRaw(obj_size, space);
1564 if (result->IsFailure()) return result;
1565
1566 // Copy code object.
1567 Address old_addr = code->address();
1568 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
1569 memcpy(new_addr, old_addr, obj_size);
1570
1571 // Relocate the copy.
1572 Code* new_code = Code::cast(result);
1573 new_code->Relocate(new_addr - old_addr);
1574
1575 CPU::FlushICache(new_code->instruction_start(), new_code->instruction_size());
1576
1577 return new_code;
1578}
1579
1580
1581Object* Heap::Allocate(Map* map, AllocationSpace space) {
1582 ASSERT(gc_state_ == NOT_IN_GC);
1583 ASSERT(map->instance_type() != MAP_TYPE);
1584 Object* result = AllocateRaw(map->instance_size(), space);
1585 if (result->IsFailure()) return result;
1586 HeapObject::cast(result)->set_map(map);
1587 return result;
1588}
1589
1590
1591Object* Heap::InitializeFunction(JSFunction* function,
1592 SharedFunctionInfo* shared,
1593 Object* prototype) {
1594 ASSERT(!prototype->IsMap());
1595 function->initialize_properties();
1596 function->initialize_elements();
1597 function->set_shared(shared);
1598 function->set_prototype_or_initial_map(prototype);
1599 function->set_context(undefined_value());
1600 function->set_literals(empty_fixed_array());
1601 return function;
1602}
1603
1604
1605Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
1606 // Allocate the prototype.
1607 Object* prototype =
1608 AllocateJSObject(Top::context()->global_context()->object_function());
1609 if (prototype->IsFailure()) return prototype;
1610 // When creating the prototype for the function we must set its
1611 // constructor to the function.
1612 Object* result =
1613 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
1614 function,
1615 DONT_ENUM);
1616 if (result->IsFailure()) return result;
1617 return prototype;
1618}
1619
1620
1621Object* Heap::AllocateFunction(Map* function_map,
1622 SharedFunctionInfo* shared,
1623 Object* prototype) {
1624 Object* result = Allocate(function_map, OLD_SPACE);
1625 if (result->IsFailure()) return result;
1626 return InitializeFunction(JSFunction::cast(result), shared, prototype);
1627}
1628
1629
1630Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
1631 // This allocation is odd since allocate an argument object
1632 // based on the arguments_boilerplate.
1633 // We do this to ensure fast allocation and map sharing.
1634
1635 // This calls Copy directly rather than using Heap::AllocateRaw so we
1636 // duplicate the check here.
1637 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
1638
1639 JSObject* boilerplate =
1640 Top::context()->global_context()->arguments_boilerplate();
1641 Object* result = boilerplate->Copy();
1642 if (result->IsFailure()) return result;
1643
1644 Object* obj = JSObject::cast(result)->properties();
1645 FixedArray::cast(obj)->set(arguments_callee_index, callee);
1646 FixedArray::cast(obj)->set(arguments_length_index, Smi::FromInt(length));
1647
1648 // Allocate the fixed array.
1649 obj = Heap::AllocateFixedArray(length);
1650 if (obj->IsFailure()) return obj;
1651 JSObject::cast(result)->set_elements(FixedArray::cast(obj));
1652
1653 // Check the state of the object
1654 ASSERT(JSObject::cast(result)->HasFastProperties());
1655 ASSERT(JSObject::cast(result)->HasFastElements());
1656
1657 return result;
1658}
1659
1660
1661Object* Heap::AllocateInitialMap(JSFunction* fun) {
1662 ASSERT(!fun->has_initial_map());
1663
1664 // First create a new map.
1665 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1666 if (map_obj->IsFailure()) return map_obj;
1667
1668 // Fetch or allocate prototype.
1669 Object* prototype;
1670 if (fun->has_instance_prototype()) {
1671 prototype = fun->instance_prototype();
1672 } else {
1673 prototype = AllocateFunctionPrototype(fun);
1674 if (prototype->IsFailure()) return prototype;
1675 }
1676 Map* map = Map::cast(map_obj);
1677 map->set_unused_property_fields(fun->shared()->expected_nof_properties());
1678 map->set_prototype(prototype);
1679 return map;
1680}
1681
1682
1683void Heap::InitializeJSObjectFromMap(JSObject* obj,
1684 FixedArray* properties,
1685 Map* map) {
1686 obj->set_properties(properties);
1687 obj->initialize_elements();
1688 // TODO(1240798): Initialize the object's body using valid initial values
1689 // according to the object's initial map. For example, if the map's
1690 // instance type is JS_ARRAY_TYPE, the length field should be initialized
1691 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
1692 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
1693 // verification code has to cope with (temporarily) invalid objects. See
1694 // for example, JSArray::JSArrayVerify).
1695 obj->InitializeBody(map->instance_size());
1696}
1697
1698
1699Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
1700 // JSFunctions should be allocated using AllocateFunction to be
1701 // properly initialized.
1702 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
1703
1704 // Allocate the backing storage for the properties.
1705 Object* properties = AllocatePropertyStorageForMap(map);
1706 if (properties->IsFailure()) return properties;
1707
1708 // Allocate the JSObject.
1709 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
1710 if (map->instance_size() > MaxHeapObjectSize()) space = LO_SPACE;
1711 Object* obj = Allocate(map, space);
1712 if (obj->IsFailure()) return obj;
1713
1714 // Initialize the JSObject.
1715 InitializeJSObjectFromMap(JSObject::cast(obj),
1716 FixedArray::cast(properties),
1717 map);
1718 return obj;
1719}
1720
1721
1722Object* Heap::AllocateJSObject(JSFunction* constructor,
1723 PretenureFlag pretenure) {
1724 // Allocate the initial map if absent.
1725 if (!constructor->has_initial_map()) {
1726 Object* initial_map = AllocateInitialMap(constructor);
1727 if (initial_map->IsFailure()) return initial_map;
1728 constructor->set_initial_map(Map::cast(initial_map));
1729 Map::cast(initial_map)->set_constructor(constructor);
1730 }
1731 // Allocate the object based on the constructors initial map.
1732 return AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
1733}
1734
1735
1736Object* Heap::ReinitializeJSGlobalObject(JSFunction* constructor,
1737 JSGlobalObject* object) {
1738 // Allocate initial map if absent.
1739 if (!constructor->has_initial_map()) {
1740 Object* initial_map = AllocateInitialMap(constructor);
1741 if (initial_map->IsFailure()) return initial_map;
1742 constructor->set_initial_map(Map::cast(initial_map));
1743 Map::cast(initial_map)->set_constructor(constructor);
1744 }
1745
1746 Map* map = constructor->initial_map();
1747
1748 // Check that the already allocated object has the same size as
1749 // objects allocated using the constructor.
1750 ASSERT(map->instance_size() == object->map()->instance_size());
1751
1752 // Allocate the backing storage for the properties.
1753 Object* properties = AllocatePropertyStorageForMap(map);
1754 if (properties->IsFailure()) return properties;
1755
1756 // Reset the map for the object.
1757 object->set_map(constructor->initial_map());
1758
1759 // Reinitialize the object from the constructor map.
1760 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
1761 return object;
1762}
1763
1764
1765Object* Heap::AllocateStringFromAscii(Vector<const char> string,
1766 PretenureFlag pretenure) {
1767 Object* result = AllocateRawAsciiString(string.length(), pretenure);
1768 if (result->IsFailure()) return result;
1769
1770 // Copy the characters into the new object.
1771 AsciiString* string_result = AsciiString::cast(result);
1772 for (int i = 0; i < string.length(); i++) {
1773 string_result->AsciiStringSet(i, string[i]);
1774 }
1775 return result;
1776}
1777
1778
1779Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
1780 PretenureFlag pretenure) {
1781 // Count the number of characters in the UTF-8 string and check if
1782 // it is an ASCII string.
1783 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
1784 decoder->Reset(string.start(), string.length());
1785 int chars = 0;
1786 bool is_ascii = true;
1787 while (decoder->has_more()) {
1788 uc32 r = decoder->GetNext();
1789 if (r > String::kMaxAsciiCharCode) is_ascii = false;
1790 chars++;
1791 }
1792
1793 // If the string is ascii, we do not need to convert the characters
1794 // since UTF8 is backwards compatible with ascii.
1795 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
1796
1797 Object* result = AllocateRawTwoByteString(chars, pretenure);
1798 if (result->IsFailure()) return result;
1799
1800 // Convert and copy the characters into the new object.
1801 String* string_result = String::cast(result);
1802 decoder->Reset(string.start(), string.length());
1803 for (int i = 0; i < chars; i++) {
1804 uc32 r = decoder->GetNext();
1805 string_result->Set(i, r);
1806 }
1807 return result;
1808}
1809
1810
1811Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
1812 PretenureFlag pretenure) {
1813 // Check if the string is an ASCII string.
1814 int i = 0;
1815 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
1816
1817 Object* result;
1818 if (i == string.length()) { // It's an ASCII string.
1819 result = AllocateRawAsciiString(string.length(), pretenure);
1820 } else { // It's not an ASCII string.
1821 result = AllocateRawTwoByteString(string.length(), pretenure);
1822 }
1823 if (result->IsFailure()) return result;
1824
1825 // Copy the characters into the new object, which may be either ASCII or
1826 // UTF-16.
1827 String* string_result = String::cast(result);
1828 for (int i = 0; i < string.length(); i++) {
1829 string_result->Set(i, string[i]);
1830 }
1831 return result;
1832}
1833
1834
1835Map* Heap::SymbolMapForString(String* string) {
1836 // If the string is in new space it cannot be used as a symbol.
1837 if (InNewSpace(string)) return NULL;
1838
1839 // Find the corresponding symbol map for strings.
1840 Map* map = string->map();
1841
1842 if (map == short_ascii_string_map()) return short_ascii_symbol_map();
1843 if (map == medium_ascii_string_map()) return medium_ascii_symbol_map();
1844 if (map == long_ascii_string_map()) return long_ascii_symbol_map();
1845
1846 if (map == short_string_map()) return short_symbol_map();
1847 if (map == medium_string_map()) return medium_symbol_map();
1848 if (map == long_string_map()) return long_symbol_map();
1849
1850 if (map == short_cons_string_map()) return short_cons_symbol_map();
1851 if (map == medium_cons_string_map()) return medium_cons_symbol_map();
1852 if (map == long_cons_string_map()) return long_cons_symbol_map();
1853
1854 if (map == short_cons_ascii_string_map()) {
1855 return short_cons_ascii_symbol_map();
1856 }
1857 if (map == medium_cons_ascii_string_map()) {
1858 return medium_cons_ascii_symbol_map();
1859 }
1860 if (map == long_cons_ascii_string_map()) {
1861 return long_cons_ascii_symbol_map();
1862 }
1863
1864 if (map == short_sliced_string_map()) return short_sliced_symbol_map();
1865 if (map == medium_sliced_string_map()) return short_sliced_symbol_map();
1866 if (map == long_sliced_string_map()) return short_sliced_symbol_map();
1867
1868 if (map == short_sliced_ascii_string_map()) {
1869 return short_sliced_ascii_symbol_map();
1870 }
1871 if (map == medium_sliced_ascii_string_map()) {
1872 return short_sliced_ascii_symbol_map();
1873 }
1874 if (map == long_sliced_ascii_string_map()) {
1875 return short_sliced_ascii_symbol_map();
1876 }
1877
1878 if (map == short_external_string_map()) return short_external_string_map();
1879 if (map == medium_external_string_map()) return medium_external_string_map();
1880 if (map == long_external_string_map()) return long_external_string_map();
1881
1882 if (map == short_external_ascii_string_map()) {
1883 return short_external_ascii_string_map();
1884 }
1885 if (map == medium_external_ascii_string_map()) {
1886 return medium_external_ascii_string_map();
1887 }
1888 if (map == long_external_ascii_string_map()) {
1889 return long_external_ascii_string_map();
1890 }
1891
1892 // No match found.
1893 return NULL;
1894}
1895
1896
1897Object* Heap::AllocateSymbol(unibrow::CharacterStream* buffer,
1898 int chars,
1899 int hash) {
1900 // Ensure the chars matches the number of characters in the buffer.
1901 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
1902 // Determine whether the string is ascii.
1903 bool is_ascii = true;
1904 while (buffer->has_more()) {
1905 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) is_ascii = false;
1906 }
1907 buffer->Rewind();
1908
1909 // Compute map and object size.
1910 int size;
1911 Map* map;
1912
1913 if (is_ascii) {
1914 if (chars <= String::kMaxShortStringSize) {
1915 map = short_ascii_symbol_map();
1916 } else if (chars <= String::kMaxMediumStringSize) {
1917 map = medium_ascii_symbol_map();
1918 } else {
1919 map = long_ascii_symbol_map();
1920 }
1921 size = AsciiString::SizeFor(chars);
1922 } else {
1923 if (chars <= String::kMaxShortStringSize) {
1924 map = short_symbol_map();
1925 } else if (chars <= String::kMaxMediumStringSize) {
1926 map = medium_symbol_map();
1927 } else {
1928 map = long_symbol_map();
1929 }
1930 size = TwoByteString::SizeFor(chars);
1931 }
1932
1933 // Allocate string.
1934 AllocationSpace space = (size > MaxHeapObjectSize()) ? LO_SPACE : CODE_SPACE;
1935 Object* result = AllocateRaw(size, space);
1936 if (result->IsFailure()) return result;
1937
1938 reinterpret_cast<HeapObject*>(result)->set_map(map);
1939 // The hash value contains the length of the string.
1940 String::cast(result)->set_length_field(hash);
1941
1942 ASSERT_EQ(size, String::cast(result)->Size());
1943
1944 // Fill in the characters.
1945 for (int i = 0; i < chars; i++) {
1946 String::cast(result)->Set(i, buffer->GetNext());
1947 }
1948 return result;
1949}
1950
1951
1952Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
1953 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
1954 int size = AsciiString::SizeFor(length);
1955 if (size > MaxHeapObjectSize()) {
1956 space = LO_SPACE;
1957 }
1958
1959 // Use AllocateRaw rather than Allocate because the object's size cannot be
1960 // determined from the map.
1961 Object* result = AllocateRaw(size, space);
1962 if (result->IsFailure()) return result;
1963
1964 // Determine the map based on the string's length.
1965 Map* map;
1966 if (length <= String::kMaxShortStringSize) {
1967 map = short_ascii_string_map();
1968 } else if (length <= String::kMaxMediumStringSize) {
1969 map = medium_ascii_string_map();
1970 } else {
1971 map = long_ascii_string_map();
1972 }
1973
1974 // Partially initialize the object.
1975 HeapObject::cast(result)->set_map(map);
1976 String::cast(result)->set_length(length);
1977 ASSERT_EQ(size, HeapObject::cast(result)->Size());
1978 return result;
1979}
1980
1981
1982Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
1983 AllocationSpace space = (pretenure == TENURED) ? CODE_SPACE : NEW_SPACE;
1984 int size = TwoByteString::SizeFor(length);
1985 if (size > MaxHeapObjectSize()) {
1986 space = LO_SPACE;
1987 }
1988
1989 // Use AllocateRaw rather than Allocate because the object's size cannot be
1990 // determined from the map.
1991 Object* result = AllocateRaw(size, space);
1992 if (result->IsFailure()) return result;
1993
1994 // Determine the map based on the string's length.
1995 Map* map;
1996 if (length <= String::kMaxShortStringSize) {
1997 map = short_string_map();
1998 } else if (length <= String::kMaxMediumStringSize) {
1999 map = medium_string_map();
2000 } else {
2001 map = long_string_map();
2002 }
2003
2004 // Partially initialize the object.
2005 HeapObject::cast(result)->set_map(map);
2006 String::cast(result)->set_length(length);
2007 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2008 return result;
2009}
2010
2011
2012Object* Heap::AllocateEmptyFixedArray() {
2013 int size = FixedArray::SizeFor(0);
2014 Object* result = AllocateRaw(size, CODE_SPACE);
2015 if (result->IsFailure()) return result;
2016 // Initialize the object.
2017 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2018 reinterpret_cast<Array*>(result)->set_length(0);
2019 return result;
2020}
2021
2022
2023Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
2024 ASSERT(empty_fixed_array()->IsFixedArray());
2025 if (length == 0) return empty_fixed_array();
2026
2027 int size = FixedArray::SizeFor(length);
2028 Object* result;
2029 if (size > MaxHeapObjectSize()) {
2030 result = lo_space_->AllocateRawFixedArray(size);
2031 } else {
2032 AllocationSpace space = (pretenure == TENURED) ? OLD_SPACE : NEW_SPACE;
2033 result = AllocateRaw(size, space);
2034 }
2035 if (result->IsFailure()) return result;
2036
2037 // Initialize the object.
2038 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2039 FixedArray* array = FixedArray::cast(result);
2040 array->set_length(length);
2041 for (int index = 0; index < length; index++) array->set_undefined(index);
2042 return array;
2043}
2044
2045
2046Object* Heap::AllocateFixedArrayWithHoles(int length) {
2047 if (length == 0) return empty_fixed_array();
2048 int size = FixedArray::SizeFor(length);
2049 Object* result = size > MaxHeapObjectSize()
2050 ? lo_space_->AllocateRawFixedArray(size)
2051 : AllocateRaw(size, NEW_SPACE);
2052 if (result->IsFailure()) return result;
2053
2054 // Initialize the object.
2055 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2056 FixedArray* array = FixedArray::cast(result);
2057 array->set_length(length);
2058 for (int index = 0; index < length; index++) array->set_the_hole(index);
2059 return array;
2060}
2061
2062
2063Object* Heap::AllocateHashTable(int length) {
2064 Object* result = Heap::AllocateFixedArray(length);
2065 if (result->IsFailure()) return result;
2066 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
2067 ASSERT(result->IsDictionary());
2068 return result;
2069}
2070
2071
2072Object* Heap::AllocateGlobalContext() {
2073 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
2074 if (result->IsFailure()) return result;
2075 Context* context = reinterpret_cast<Context*>(result);
2076 context->set_map(global_context_map());
2077 ASSERT(context->IsGlobalContext());
2078 ASSERT(result->IsContext());
2079 return result;
2080}
2081
2082
2083Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
2084 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
2085 Object* result = Heap::AllocateFixedArray(length);
2086 if (result->IsFailure()) return result;
2087 Context* context = reinterpret_cast<Context*>(result);
2088 context->set_map(context_map());
2089 context->set_closure(function);
2090 context->set_fcontext(context);
2091 context->set_previous(NULL);
2092 context->set_extension(NULL);
2093 context->set_global(function->context()->global());
2094 ASSERT(!context->IsGlobalContext());
2095 ASSERT(context->is_function_context());
2096 ASSERT(result->IsContext());
2097 return result;
2098}
2099
2100
2101Object* Heap::AllocateWithContext(Context* previous, JSObject* extension) {
2102 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
2103 if (result->IsFailure()) return result;
2104 Context* context = reinterpret_cast<Context*>(result);
2105 context->set_map(context_map());
2106 context->set_closure(previous->closure());
2107 context->set_fcontext(previous->fcontext());
2108 context->set_previous(previous);
2109 context->set_extension(extension);
2110 context->set_global(previous->global());
2111 ASSERT(!context->IsGlobalContext());
2112 ASSERT(!context->is_function_context());
2113 ASSERT(result->IsContext());
2114 return result;
2115}
2116
2117
2118Object* Heap::AllocateStruct(InstanceType type) {
2119 Map* map;
2120 switch (type) {
2121#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
2122STRUCT_LIST(MAKE_CASE)
2123#undef MAKE_CASE
2124 default:
2125 UNREACHABLE();
2126 return Failure::InternalError();
2127 }
2128 int size = map->instance_size();
2129 AllocationSpace space =
2130 (size > MaxHeapObjectSize()) ? LO_SPACE : OLD_SPACE;
2131 Object* result = Heap::Allocate(map, space);
2132 if (result->IsFailure()) return result;
2133 Struct::cast(result)->InitializeBody(size);
2134 return result;
2135}
2136
2137
2138#ifdef DEBUG
2139
2140void Heap::Print() {
2141 if (!HasBeenSetup()) return;
2142 Top::PrintStack();
2143 new_space_->Print();
2144 old_space_->Print();
2145 code_space_->Print();
2146 map_space_->Print();
2147 lo_space_->Print();
2148}
2149
2150
2151void Heap::ReportCodeStatistics(const char* title) {
2152 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
2153 PagedSpace::ResetCodeStatistics();
2154 // We do not look for code in new space, map space, or old space. If code
2155 // somehow ends up in those spaces, we would miss it here.
2156 code_space_->CollectCodeStatistics();
2157 lo_space_->CollectCodeStatistics();
2158 PagedSpace::ReportCodeStatistics();
2159}
2160
2161
2162// This function expects that NewSpace's allocated objects histogram is
2163// populated (via a call to CollectStatistics or else as a side effect of a
2164// just-completed scavenge collection).
2165void Heap::ReportHeapStatistics(const char* title) {
2166 USE(title);
2167 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
2168 title, gc_count_);
2169 PrintF("mark-compact GC : %d\n", mc_count_);
2170 PrintF("promoted_space_limit_ %d\n", promoted_space_limit_);
2171
2172 PrintF("\n");
2173 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
2174 GlobalHandles::PrintStats();
2175 PrintF("\n");
2176
2177 PrintF("Heap statistics : ");
2178 MemoryAllocator::ReportStatistics();
2179 PrintF("To space : ");
2180 new_space_->ReportStatistics();
2181 PrintF("Old space : ");
2182 old_space_->ReportStatistics();
2183 PrintF("Code space : ");
2184 code_space_->ReportStatistics();
2185 PrintF("Map space : ");
2186 map_space_->ReportStatistics();
2187 PrintF("Large object space : ");
2188 lo_space_->ReportStatistics();
2189 PrintF(">>>>>> ========================================= >>>>>>\n");
2190}
2191
2192#endif // DEBUG
2193
2194bool Heap::Contains(HeapObject* value) {
2195 return Contains(value->address());
2196}
2197
2198
2199bool Heap::Contains(Address addr) {
2200 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2201 return HasBeenSetup() &&
2202 (new_space_->ToSpaceContains(addr) ||
2203 old_space_->Contains(addr) ||
2204 code_space_->Contains(addr) ||
2205 map_space_->Contains(addr) ||
2206 lo_space_->SlowContains(addr));
2207}
2208
2209
2210bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
2211 return InSpace(value->address(), space);
2212}
2213
2214
2215bool Heap::InSpace(Address addr, AllocationSpace space) {
2216 if (OS::IsOutsideAllocatedSpace(addr)) return false;
2217 if (!HasBeenSetup()) return false;
2218
2219 switch (space) {
2220 case NEW_SPACE:
2221 return new_space_->ToSpaceContains(addr);
2222 case OLD_SPACE:
2223 return old_space_->Contains(addr);
2224 case CODE_SPACE:
2225 return code_space_->Contains(addr);
2226 case MAP_SPACE:
2227 return map_space_->Contains(addr);
2228 case LO_SPACE:
2229 return lo_space_->SlowContains(addr);
2230 }
2231
2232 return false;
2233}
2234
2235
2236#ifdef DEBUG
2237void Heap::Verify() {
2238 ASSERT(HasBeenSetup());
2239
2240 VerifyPointersVisitor visitor;
2241 Heap::IterateRoots(&visitor);
2242
2243 Heap::new_space_->Verify();
2244 Heap::old_space_->Verify();
2245 Heap::code_space_->Verify();
2246 Heap::map_space_->Verify();
2247 Heap::lo_space_->Verify();
2248}
2249#endif // DEBUG
2250
2251
2252Object* Heap::LookupSymbol(Vector<const char> string) {
2253 Object* symbol = NULL;
2254 Object* new_table =
2255 SymbolTable::cast(symbol_table_)->LookupSymbol(string, &symbol);
2256 if (new_table->IsFailure()) return new_table;
2257 symbol_table_ = new_table;
2258 ASSERT(symbol != NULL);
2259 return symbol;
2260}
2261
2262
2263Object* Heap::LookupSymbol(String* string) {
2264 if (string->IsSymbol()) return string;
2265 Object* symbol = NULL;
2266 Object* new_table =
2267 SymbolTable::cast(symbol_table_)->LookupString(string, &symbol);
2268 if (new_table->IsFailure()) return new_table;
2269 symbol_table_ = new_table;
2270 ASSERT(symbol != NULL);
2271 return symbol;
2272}
2273
2274
2275#ifdef DEBUG
2276void Heap::ZapFromSpace() {
2277 ASSERT(HAS_HEAP_OBJECT_TAG(kFromSpaceZapValue));
2278 for (Address a = new_space_->FromSpaceLow();
2279 a < new_space_->FromSpaceHigh();
2280 a += kPointerSize) {
2281 Memory::Address_at(a) = kFromSpaceZapValue;
2282 }
2283}
2284#endif // DEBUG
2285
2286
2287void Heap::IterateRSetRange(Address object_start,
2288 Address object_end,
2289 Address rset_start,
2290 ObjectSlotCallback copy_object_func) {
2291 Address object_address = object_start;
2292 Address rset_address = rset_start;
2293
2294 // Loop over all the pointers in [object_start, object_end).
2295 while (object_address < object_end) {
2296 uint32_t rset_word = Memory::uint32_at(rset_address);
2297
2298 if (rset_word != 0) {
2299 // Bits were set.
2300 uint32_t result_rset = rset_word;
2301
2302 // Loop over all the bits in the remembered set word. Though
2303 // remembered sets are sparse, faster (eg, binary) search for
2304 // set bits does not seem to help much here.
2305 for (int bit_offset = 0; bit_offset < kBitsPerInt; bit_offset++) {
2306 uint32_t bitmask = 1 << bit_offset;
2307 // Do not dereference pointers at or past object_end.
2308 if ((rset_word & bitmask) != 0 && object_address < object_end) {
2309 Object** object_p = reinterpret_cast<Object**>(object_address);
2310 if (Heap::InFromSpace(*object_p)) {
2311 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
2312 }
2313 // If this pointer does not need to be remembered anymore, clear
2314 // the remembered set bit.
2315 if (!Heap::InToSpace(*object_p)) result_rset &= ~bitmask;
2316 }
2317 object_address += kPointerSize;
2318 }
2319
2320 // Update the remembered set if it has changed.
2321 if (result_rset != rset_word) {
2322 Memory::uint32_at(rset_address) = result_rset;
2323 }
2324 } else {
2325 // No bits in the word were set. This is the common case.
2326 object_address += kPointerSize * kBitsPerInt;
2327 }
2328
2329 rset_address += kIntSize;
2330 }
2331}
2332
2333
2334void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
2335 ASSERT(Page::is_rset_in_use());
2336 ASSERT(space == old_space_ || space == map_space_);
2337
2338 PageIterator it(space, PageIterator::PAGES_IN_USE);
2339 while (it.has_next()) {
2340 Page* page = it.next();
2341 IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
2342 page->RSetStart(), copy_object_func);
2343 }
2344}
2345
2346
2347#ifdef DEBUG
2348#define SYNCHRONIZE_TAG(tag) v->Synchronize(tag)
2349#else
2350#define SYNCHRONIZE_TAG(tag)
2351#endif
2352
2353void Heap::IterateRoots(ObjectVisitor* v) {
2354 IterateStrongRoots(v);
2355 v->VisitPointer(reinterpret_cast<Object**>(&symbol_table_));
2356 SYNCHRONIZE_TAG("symbol_table");
2357}
2358
2359
2360void Heap::IterateStrongRoots(ObjectVisitor* v) {
2361#define ROOT_ITERATE(type, name) \
2362 v->VisitPointer(reinterpret_cast<Object**>(&name##_));
2363 STRONG_ROOT_LIST(ROOT_ITERATE);
2364#undef ROOT_ITERATE
2365 SYNCHRONIZE_TAG("strong_root_list");
2366
2367#define STRUCT_MAP_ITERATE(NAME, Name, name) \
2368 v->VisitPointer(reinterpret_cast<Object**>(&name##_map_));
2369 STRUCT_LIST(STRUCT_MAP_ITERATE);
2370#undef STRUCT_MAP_ITERATE
2371 SYNCHRONIZE_TAG("struct_map");
2372
2373#define SYMBOL_ITERATE(name, string) \
2374 v->VisitPointer(reinterpret_cast<Object**>(&name##_));
2375 SYMBOL_LIST(SYMBOL_ITERATE)
2376#undef SYMBOL_ITERATE
2377 SYNCHRONIZE_TAG("symbol");
2378
2379 Bootstrapper::Iterate(v);
2380 SYNCHRONIZE_TAG("bootstrapper");
2381 Top::Iterate(v);
2382 SYNCHRONIZE_TAG("top");
2383 Debug::Iterate(v);
2384 SYNCHRONIZE_TAG("debug");
2385
2386 // Iterate over local handles in handle scopes.
2387 HandleScopeImplementer::Iterate(v);
2388 SYNCHRONIZE_TAG("handlescope");
2389
2390 // Iterate over the builtin code objects and code stubs in the heap. Note
2391 // that it is not strictly necessary to iterate over code objects on
2392 // scavenge collections. We still do it here because this same function
2393 // is used by the mark-sweep collector and the deserializer.
2394 Builtins::IterateBuiltins(v);
2395 SYNCHRONIZE_TAG("builtins");
2396
2397 // Iterate over global handles.
2398 GlobalHandles::IterateRoots(v);
2399 SYNCHRONIZE_TAG("globalhandles");
2400
2401 // Iterate over pointers being held by inactive threads.
2402 ThreadManager::Iterate(v);
2403 SYNCHRONIZE_TAG("threadmanager");
2404}
2405#undef SYNCHRONIZE_TAG
2406
2407
2408// Flag is set when the heap has been configured. The heap can be repeatedly
2409// configured through the API until it is setup.
2410static bool heap_configured = false;
2411
2412// TODO(1236194): Since the heap size is configurable on the command line
2413// and through the API, we should gracefully handle the case that the heap
2414// size is not big enough to fit all the initial objects.
2415bool Heap::ConfigureHeap(int semispace_size, int old_gen_size) {
2416 if (HasBeenSetup()) return false;
2417
2418 if (semispace_size > 0) semispace_size_ = semispace_size;
2419 if (old_gen_size > 0) old_generation_size_ = old_gen_size;
2420
2421 // The new space size must be a power of two to support single-bit testing
2422 // for containment.
2423 semispace_size_ = NextPowerOf2(semispace_size_);
2424 initial_semispace_size_ = Min(initial_semispace_size_, semispace_size_);
2425 young_generation_size_ = 2 * semispace_size_;
2426
2427 // The old generation is paged.
2428 old_generation_size_ = RoundUp(old_generation_size_, Page::kPageSize);
2429
2430 heap_configured = true;
2431 return true;
2432}
2433
2434
kasper.lund7276f142008-07-30 08:49:36 +00002435bool Heap::ConfigureHeapDefault() {
2436 return ConfigureHeap(FLAG_new_space_size, FLAG_old_space_size);
2437}
2438
2439
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002440int Heap::PromotedSpaceSize() {
2441 return old_space_->Size()
2442 + code_space_->Size()
2443 + map_space_->Size()
2444 + lo_space_->Size();
2445}
2446
2447
kasper.lund7276f142008-07-30 08:49:36 +00002448int Heap::PromotedExternalMemorySize() {
2449 if (amount_of_external_allocated_memory_
2450 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
2451 return amount_of_external_allocated_memory_
2452 - amount_of_external_allocated_memory_at_last_global_gc_;
2453}
2454
2455
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002456bool Heap::Setup(bool create_heap_objects) {
2457 // Initialize heap spaces and initial maps and objects. Whenever something
2458 // goes wrong, just return false. The caller should check the results and
2459 // call Heap::TearDown() to release allocated memory.
2460 //
2461 // If the heap is not yet configured (eg, through the API), configure it.
2462 // Configuration is based on the flags new-space-size (really the semispace
2463 // size) and old-space-size if set or the initial values of semispace_size_
2464 // and old_generation_size_ otherwise.
2465 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00002466 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002467 }
2468
2469 // Setup memory allocator and allocate an initial chunk of memory. The
2470 // initial chunk is double the size of the new space to ensure that we can
2471 // find a pair of semispaces that are contiguous and aligned to their size.
2472 if (!MemoryAllocator::Setup(MaxCapacity())) return false;
2473 void* chunk
2474 = MemoryAllocator::ReserveInitialChunk(2 * young_generation_size_);
2475 if (chunk == NULL) return false;
2476
2477 // Put the initial chunk of the old space at the start of the initial
2478 // chunk, then the two new space semispaces, then the initial chunk of
2479 // code space. Align the pair of semispaces to their size, which must be
2480 // a power of 2.
2481 ASSERT(IsPowerOf2(young_generation_size_));
2482 Address old_space_start = reinterpret_cast<Address>(chunk);
2483 Address new_space_start = RoundUp(old_space_start, young_generation_size_);
2484 Address code_space_start = new_space_start + young_generation_size_;
2485 int old_space_size = new_space_start - old_space_start;
2486 int code_space_size = young_generation_size_ - old_space_size;
2487
kasper.lund7276f142008-07-30 08:49:36 +00002488 // Initialize new space. It will not contain code.
2489 new_space_ = new NewSpace(initial_semispace_size_,
2490 semispace_size_,
2491 NEW_SPACE,
2492 false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002493 if (new_space_ == NULL) return false;
2494 if (!new_space_->Setup(new_space_start, young_generation_size_)) return false;
2495
2496 // Initialize old space, set the maximum capacity to the old generation
kasper.lund7276f142008-07-30 08:49:36 +00002497 // size. It will not contain code.
2498 old_space_ = new OldSpace(old_generation_size_, OLD_SPACE, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002499 if (old_space_ == NULL) return false;
2500 if (!old_space_->Setup(old_space_start, old_space_size)) return false;
2501
2502 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00002503 // generation size. It needs executable memory.
2504 code_space_ = new OldSpace(old_generation_size_, CODE_SPACE, true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002505 if (code_space_ == NULL) return false;
2506 if (!code_space_->Setup(code_space_start, code_space_size)) return false;
2507
2508 // Initialize map space.
kasper.lund7276f142008-07-30 08:49:36 +00002509 map_space_ = new MapSpace(kMaxMapSpaceSize, MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002510 if (map_space_ == NULL) return false;
2511 // Setting up a paged space without giving it a virtual memory range big
2512 // enough to hold at least a page will cause it to allocate.
2513 if (!map_space_->Setup(NULL, 0)) return false;
2514
kasper.lund7276f142008-07-30 08:49:36 +00002515 // The large object space may contain code, so it needs executable memory.
2516 lo_space_ = new LargeObjectSpace(LO_SPACE, true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002517 if (lo_space_ == NULL) return false;
2518 if (!lo_space_->Setup()) return false;
2519
2520 if (create_heap_objects) {
2521 // Create initial maps.
2522 if (!CreateInitialMaps()) return false;
2523 if (!CreateApiObjects()) return false;
2524
2525 // Create initial objects
2526 if (!CreateInitialObjects()) return false;
2527 }
2528
2529 LOG(IntEvent("heap-capacity", Capacity()));
2530 LOG(IntEvent("heap-available", Available()));
2531
2532 return true;
2533}
2534
2535
2536void Heap::TearDown() {
2537 GlobalHandles::TearDown();
2538
2539 if (new_space_ != NULL) {
2540 new_space_->TearDown();
2541 delete new_space_;
2542 new_space_ = NULL;
2543 }
2544
2545 if (old_space_ != NULL) {
2546 old_space_->TearDown();
2547 delete old_space_;
2548 old_space_ = NULL;
2549 }
2550
2551 if (code_space_ != NULL) {
2552 code_space_->TearDown();
2553 delete code_space_;
2554 code_space_ = NULL;
2555 }
2556
2557 if (map_space_ != NULL) {
2558 map_space_->TearDown();
2559 delete map_space_;
2560 map_space_ = NULL;
2561 }
2562
2563 if (lo_space_ != NULL) {
2564 lo_space_->TearDown();
2565 delete lo_space_;
2566 lo_space_ = NULL;
2567 }
2568
2569 MemoryAllocator::TearDown();
2570}
2571
2572
2573void Heap::Shrink() {
2574 // Try to shrink map, old, and code spaces.
2575 map_space_->Shrink();
2576 old_space_->Shrink();
2577 code_space_->Shrink();
2578}
2579
2580
2581#ifdef DEBUG
2582
2583class PrintHandleVisitor: public ObjectVisitor {
2584 public:
2585 void VisitPointers(Object** start, Object** end) {
2586 for (Object** p = start; p < end; p++)
2587 PrintF(" handle %p to %p\n", p, *p);
2588 }
2589};
2590
2591void Heap::PrintHandles() {
2592 PrintF("Handles:\n");
2593 PrintHandleVisitor v;
2594 HandleScopeImplementer::Iterate(&v);
2595}
2596
2597#endif
2598
2599
kasper.lund7276f142008-07-30 08:49:36 +00002600SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
2601}
2602
2603
2604SpaceIterator::~SpaceIterator() {
2605 // Delete active iterator if any.
2606 delete iterator_;
2607}
2608
2609
2610bool SpaceIterator::has_next() {
2611 // Iterate until no more spaces.
2612 return current_space_ != LAST_SPACE;
2613}
2614
2615
2616ObjectIterator* SpaceIterator::next() {
2617 if (iterator_ != NULL) {
2618 delete iterator_;
2619 iterator_ = NULL;
2620 // Move to the next space
2621 current_space_++;
2622 if (current_space_ > LAST_SPACE) {
2623 return NULL;
2624 }
2625 }
2626
2627 // Return iterator for the new current space.
2628 return CreateIterator();
2629}
2630
2631
2632// Create an iterator for the space to iterate.
2633ObjectIterator* SpaceIterator::CreateIterator() {
2634 ASSERT(iterator_ == NULL);
2635
2636 switch (current_space_) {
2637 case NEW_SPACE:
2638 iterator_ = new SemiSpaceIterator(Heap::new_space());
2639 break;
2640 case OLD_SPACE:
2641 iterator_ = new HeapObjectIterator(Heap::old_space());
2642 break;
2643 case CODE_SPACE:
2644 iterator_ = new HeapObjectIterator(Heap::code_space());
2645 break;
2646 case MAP_SPACE:
2647 iterator_ = new HeapObjectIterator(Heap::map_space());
2648 break;
2649 case LO_SPACE:
2650 iterator_ = new LargeObjectIterator(Heap::lo_space());
2651 break;
2652 }
2653
2654 // Return the newly allocated iterator;
2655 ASSERT(iterator_ != NULL);
2656 return iterator_;
2657}
2658
2659
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002660HeapIterator::HeapIterator() {
2661 Init();
2662}
2663
2664
2665HeapIterator::~HeapIterator() {
2666 Shutdown();
2667}
2668
2669
2670void HeapIterator::Init() {
2671 // Start the iteration.
2672 space_iterator_ = new SpaceIterator();
2673 object_iterator_ = space_iterator_->next();
2674}
2675
2676
2677void HeapIterator::Shutdown() {
2678 // Make sure the last iterator is deallocated.
2679 delete space_iterator_;
2680 space_iterator_ = NULL;
2681 object_iterator_ = NULL;
2682}
2683
2684
2685bool HeapIterator::has_next() {
2686 // No iterator means we are done.
2687 if (object_iterator_ == NULL) return false;
2688
2689 if (object_iterator_->has_next_object()) {
2690 // If the current iterator has more objects we are fine.
2691 return true;
2692 } else {
2693 // Go though the spaces looking for one that has objects.
2694 while (space_iterator_->has_next()) {
2695 object_iterator_ = space_iterator_->next();
2696 if (object_iterator_->has_next_object()) {
2697 return true;
2698 }
2699 }
2700 }
2701 // Done with the last space.
2702 object_iterator_ = NULL;
2703 return false;
2704}
2705
2706
2707HeapObject* HeapIterator::next() {
2708 if (has_next()) {
2709 return object_iterator_->next_object();
2710 } else {
2711 return NULL;
2712 }
2713}
2714
2715
2716void HeapIterator::reset() {
2717 // Restart the iterator.
2718 Shutdown();
2719 Init();
2720}
2721
2722
2723//
2724// HeapProfiler class implementation.
2725//
2726#ifdef ENABLE_LOGGING_AND_PROFILING
2727void HeapProfiler::CollectStats(HeapObject* obj, HistogramInfo* info) {
2728 InstanceType type = obj->map()->instance_type();
2729 ASSERT(0 <= type && type <= LAST_TYPE);
2730 info[type].increment_number(1);
2731 info[type].increment_bytes(obj->Size());
2732}
2733#endif
2734
2735
2736#ifdef ENABLE_LOGGING_AND_PROFILING
2737void HeapProfiler::WriteSample() {
2738 LOG(HeapSampleBeginEvent("Heap", "allocated"));
2739
2740 HistogramInfo info[LAST_TYPE+1];
2741#define DEF_TYPE_NAME(name) info[name].set_name(#name);
2742 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
2743#undef DEF_TYPE_NAME
2744
2745 HeapIterator iterator;
2746 while (iterator.has_next()) {
2747 CollectStats(iterator.next(), info);
2748 }
2749
2750 // Lump all the string types together.
2751 int string_number = 0;
2752 int string_bytes = 0;
2753#define INCREMENT_SIZE(type, size, name) \
2754 string_number += info[type].number(); \
2755 string_bytes += info[type].bytes();
2756 STRING_TYPE_LIST(INCREMENT_SIZE)
2757#undef INCREMENT_SIZE
2758 if (string_bytes > 0) {
2759 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
2760 }
2761
2762 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
2763 if (info[i].bytes() > 0) {
2764 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
2765 info[i].bytes()));
2766 }
2767 }
2768
2769 LOG(HeapSampleEndEvent("Heap", "allocated"));
2770}
2771
2772
2773#endif
2774
2775
2776
2777#ifdef DEBUG
2778
2779static bool search_for_any_global;
2780static Object* search_target;
2781static bool found_target;
2782static List<Object*> object_stack(20);
2783
2784
2785// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
2786static const int kMarkTag = 2;
2787
2788static void MarkObjectRecursively(Object** p);
2789class MarkObjectVisitor : public ObjectVisitor {
2790 public:
2791 void VisitPointers(Object** start, Object** end) {
2792 // Copy all HeapObject pointers in [start, end)
2793 for (Object** p = start; p < end; p++) {
2794 if ((*p)->IsHeapObject())
2795 MarkObjectRecursively(p);
2796 }
2797 }
2798};
2799
2800static MarkObjectVisitor mark_visitor;
2801
2802static void MarkObjectRecursively(Object** p) {
2803 if (!(*p)->IsHeapObject()) return;
2804
2805 HeapObject* obj = HeapObject::cast(*p);
2806
2807 Object* map = obj->map();
2808
2809 if (!map->IsHeapObject()) return; // visited before
2810
2811 if (found_target) return; // stop if target found
2812 object_stack.Add(obj);
2813 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
2814 (!search_for_any_global && (obj == search_target))) {
2815 found_target = true;
2816 return;
2817 }
2818
2819 if (obj->IsCode()) {
2820 Code::cast(obj)->ConvertICTargetsFromAddressToObject();
2821 }
2822
2823 // not visited yet
2824 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
2825
2826 Address map_addr = map_p->address();
2827
2828 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
2829
2830 MarkObjectRecursively(&map);
2831
2832 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
2833 &mark_visitor);
2834
2835 if (!found_target) // don't pop if found the target
2836 object_stack.RemoveLast();
2837}
2838
2839
2840static void UnmarkObjectRecursively(Object** p);
2841class UnmarkObjectVisitor : public ObjectVisitor {
2842 public:
2843 void VisitPointers(Object** start, Object** end) {
2844 // Copy all HeapObject pointers in [start, end)
2845 for (Object** p = start; p < end; p++) {
2846 if ((*p)->IsHeapObject())
2847 UnmarkObjectRecursively(p);
2848 }
2849 }
2850};
2851
2852static UnmarkObjectVisitor unmark_visitor;
2853
2854static void UnmarkObjectRecursively(Object** p) {
2855 if (!(*p)->IsHeapObject()) return;
2856
2857 HeapObject* obj = HeapObject::cast(*p);
2858
2859 Object* map = obj->map();
2860
2861 if (map->IsHeapObject()) return; // unmarked already
2862
2863 Address map_addr = reinterpret_cast<Address>(map);
2864
2865 map_addr -= kMarkTag;
2866
2867 ASSERT_TAG_ALIGNED(map_addr);
2868
2869 HeapObject* map_p = HeapObject::FromAddress(map_addr);
2870
2871 obj->set_map(reinterpret_cast<Map*>(map_p));
2872
2873 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
2874
2875 obj->IterateBody(Map::cast(map_p)->instance_type(),
2876 obj->SizeFromMap(Map::cast(map_p)),
2877 &unmark_visitor);
2878
2879 if (obj->IsCode()) {
2880 Code::cast(obj)->ConvertICTargetsFromObjectToAddress();
2881 }
2882}
2883
2884
2885static void MarkRootObjectRecursively(Object** root) {
2886 if (search_for_any_global) {
2887 ASSERT(search_target == NULL);
2888 } else {
2889 ASSERT(search_target->IsHeapObject());
2890 }
2891 found_target = false;
2892 object_stack.Clear();
2893
2894 MarkObjectRecursively(root);
2895 UnmarkObjectRecursively(root);
2896
2897 if (found_target) {
2898 PrintF("=====================================\n");
2899 PrintF("==== Path to object ====\n");
2900 PrintF("=====================================\n\n");
2901
2902 ASSERT(!object_stack.is_empty());
2903 for (int i = 0; i < object_stack.length(); i++) {
2904 if (i > 0) PrintF("\n |\n |\n V\n\n");
2905 Object* obj = object_stack[i];
2906 obj->Print();
2907 }
2908 PrintF("=====================================\n");
2909 }
2910}
2911
2912
2913// Helper class for visiting HeapObjects recursively.
2914class MarkRootVisitor: public ObjectVisitor {
2915 public:
2916 void VisitPointers(Object** start, Object** end) {
2917 // Visit all HeapObject pointers in [start, end)
2918 for (Object** p = start; p < end; p++) {
2919 if ((*p)->IsHeapObject())
2920 MarkRootObjectRecursively(p);
2921 }
2922 }
2923};
2924
2925
2926// Triggers a depth-first traversal of reachable objects from roots
2927// and finds a path to a specific heap object and prints it.
2928void Heap::TracePathToObject() {
2929 search_target = NULL;
2930 search_for_any_global = false;
2931
2932 MarkRootVisitor root_visitor;
2933 IterateRoots(&root_visitor);
2934}
2935
2936
2937// Triggers a depth-first traversal of reachable objects from roots
2938// and finds a path to any global object and prints it. Useful for
2939// determining the source for leaks of global objects.
2940void Heap::TracePathToGlobal() {
2941 search_target = NULL;
2942 search_for_any_global = true;
2943
2944 MarkRootVisitor root_visitor;
2945 IterateRoots(&root_visitor);
2946}
2947#endif
2948
2949
kasper.lund7276f142008-07-30 08:49:36 +00002950GCTracer::GCTracer()
2951 : start_time_(0.0),
2952 start_size_(0.0),
2953 gc_count_(0),
2954 full_gc_count_(0),
2955 is_compacting_(false),
2956 marked_count_(0) {
2957 // These two fields reflect the state of the previous full collection.
2958 // Set them before they are changed by the collector.
2959 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
2960 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
2961 if (!FLAG_trace_gc) return;
2962 start_time_ = OS::TimeCurrentMillis();
2963 start_size_ = SizeOfHeapObjects();
2964}
2965
2966
2967GCTracer::~GCTracer() {
2968 if (!FLAG_trace_gc) return;
2969 // Printf ONE line iff flag is set.
2970 PrintF("%s %.1f -> %.1f MB, %d ms.\n",
2971 CollectorString(),
2972 start_size_, SizeOfHeapObjects(),
2973 static_cast<int>(OS::TimeCurrentMillis() - start_time_));
2974}
2975
2976
2977const char* GCTracer::CollectorString() {
2978 switch (collector_) {
2979 case SCAVENGER:
2980 return "Scavenge";
2981 case MARK_COMPACTOR:
2982 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
2983 : "Mark-sweep";
2984 }
2985 return "Unknown GC";
2986}
2987
2988
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002989} } // namespace v8::internal