blob: 1f1599a79bf6c8f0f0a8482a082e1c32807e6fb2 [file] [log] [blame]
ager@chromium.org71daaf62009-04-01 07:22:49 +00001// Copyright 2009 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "bootstrapper.h"
33#include "codegen-inl.h"
kasperl@chromium.orgb9123622008-09-17 14:05:56 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "debug.h"
christian.plesner.hansen@gmail.com2bc58ef2009-09-22 10:00:30 +000036#include "heap-profiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037#include "global-handles.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000038#include "mark-compact.h"
39#include "natives.h"
40#include "scanner.h"
41#include "scopeinfo.h"
ager@chromium.org3811b432009-10-28 14:53:37 +000042#include "snapshot.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043#include "v8threads.h"
ager@chromium.org18ad94b2009-09-02 08:22:29 +000044#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
45#include "regexp-macro-assembler.h"
ager@chromium.org3811b432009-10-28 14:53:37 +000046#include "arm/regexp-macro-assembler-arm.h"
ager@chromium.org18ad94b2009-09-02 08:22:29 +000047#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000048
ager@chromium.orgce5e87b2010-03-10 10:24:18 +000049
kasperl@chromium.org71affb52009-05-26 05:44:31 +000050namespace v8 {
51namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000053
ager@chromium.org3b45ab52009-03-19 22:21:34 +000054String* Heap::hidden_symbol_;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000055Object* Heap::roots_[Heap::kRootListLength];
56
ager@chromium.org3b45ab52009-03-19 22:21:34 +000057
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000058NewSpace Heap::new_space_;
ager@chromium.org9258b6b2008-09-11 09:11:10 +000059OldSpace* Heap::old_pointer_space_ = NULL;
60OldSpace* Heap::old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000061OldSpace* Heap::code_space_ = NULL;
62MapSpace* Heap::map_space_ = NULL;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +000063CellSpace* Heap::cell_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000064LargeObjectSpace* Heap::lo_space_ = NULL;
65
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +000066static const int kMinimumPromotionLimit = 2*MB;
67static const int kMinimumAllocationLimit = 8*MB;
68
69int Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
70int Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
71
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000072int Heap::old_gen_exhausted_ = false;
73
kasper.lund7276f142008-07-30 08:49:36 +000074int Heap::amount_of_external_allocated_memory_ = 0;
75int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
76
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000077// semispace_size_ should be a power of 2 and old_generation_size_ should be
78// a multiple of Page::kPageSize.
kasperl@chromium.orge959c182009-07-27 08:59:04 +000079#if defined(ANDROID)
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000080int Heap::max_semispace_size_ = 2*MB;
81int Heap::max_old_generation_size_ = 192*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000082int Heap::initial_semispace_size_ = 128*KB;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000083size_t Heap::code_range_size_ = 0;
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +000084#elif defined(V8_TARGET_ARCH_X64)
ager@chromium.org3811b432009-10-28 14:53:37 +000085int Heap::max_semispace_size_ = 16*MB;
86int Heap::max_old_generation_size_ = 1*GB;
sgjesse@chromium.org911335c2009-08-19 12:59:44 +000087int Heap::initial_semispace_size_ = 1*MB;
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +000088size_t Heap::code_range_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000089#else
ager@chromium.org3811b432009-10-28 14:53:37 +000090int Heap::max_semispace_size_ = 8*MB;
91int Heap::max_old_generation_size_ = 512*MB;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000092int Heap::initial_semispace_size_ = 512*KB;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000093size_t Heap::code_range_size_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +000094#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000095
ager@chromium.org3811b432009-10-28 14:53:37 +000096// The snapshot semispace size will be the default semispace size if
97// snapshotting is used and will be the requested semispace size as
98// set up by ConfigureHeap otherwise.
99int Heap::reserved_semispace_size_ = Heap::max_semispace_size_;
100
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000101List<Heap::GCPrologueCallbackPair> Heap::gc_prologue_callbacks_;
102List<Heap::GCEpilogueCallbackPair> Heap::gc_epilogue_callbacks_;
103
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000104GCCallback Heap::global_gc_prologue_callback_ = NULL;
105GCCallback Heap::global_gc_epilogue_callback_ = NULL;
106
107// Variables set based on semispace_size_ and old_generation_size_ in
108// ConfigureHeap.
ager@chromium.org3811b432009-10-28 14:53:37 +0000109
110// Will be 4 * reserved_semispace_size_ to ensure that young
111// generation can be aligned to its size.
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000112int Heap::survived_since_last_expansion_ = 0;
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000113int Heap::external_allocation_limit_ = 0;
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000114
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
116
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117int Heap::mc_count_ = 0;
118int Heap::gc_count_ = 0;
119
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000120int Heap::unflattened_strings_length_ = 0;
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000121
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000122int Heap::always_allocate_scope_depth_ = 0;
ager@chromium.org3811b432009-10-28 14:53:37 +0000123int Heap::linear_allocation_scope_depth_ = 0;
kasperl@chromium.org8b2bb262010-03-01 09:46:28 +0000124int Heap::contexts_disposed_ = 0;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000125
kasper.lund7276f142008-07-30 08:49:36 +0000126#ifdef DEBUG
127bool Heap::allocation_allowed_ = true;
128
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129int Heap::allocation_timeout_ = 0;
130bool Heap::disallow_allocation_failure_ = false;
131#endif // DEBUG
132
133
134int Heap::Capacity() {
135 if (!HasBeenSetup()) return 0;
136
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000137 return new_space_.Capacity() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000138 old_pointer_space_->Capacity() +
139 old_data_space_->Capacity() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000140 code_space_->Capacity() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000141 map_space_->Capacity() +
142 cell_space_->Capacity();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000143}
144
145
ager@chromium.org3811b432009-10-28 14:53:37 +0000146int Heap::CommittedMemory() {
147 if (!HasBeenSetup()) return 0;
148
149 return new_space_.CommittedMemory() +
150 old_pointer_space_->CommittedMemory() +
151 old_data_space_->CommittedMemory() +
152 code_space_->CommittedMemory() +
153 map_space_->CommittedMemory() +
154 cell_space_->CommittedMemory() +
155 lo_space_->Size();
156}
157
158
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000159int Heap::Available() {
160 if (!HasBeenSetup()) return 0;
161
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000162 return new_space_.Available() +
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000163 old_pointer_space_->Available() +
164 old_data_space_->Available() +
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 code_space_->Available() +
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000166 map_space_->Available() +
167 cell_space_->Available();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000168}
169
170
171bool Heap::HasBeenSetup() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000172 return old_pointer_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000173 old_data_space_ != NULL &&
174 code_space_ != NULL &&
175 map_space_ != NULL &&
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000176 cell_space_ != NULL &&
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000177 lo_space_ != NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000178}
179
180
181GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
182 // Is global GC requested?
183 if (space != NEW_SPACE || FLAG_gc_global) {
184 Counters::gc_compactor_caused_by_request.Increment();
185 return MARK_COMPACTOR;
186 }
187
188 // Is enough data promoted to justify a global GC?
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000189 if (OldGenerationPromotionLimitReached()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000190 Counters::gc_compactor_caused_by_promoted_data.Increment();
191 return MARK_COMPACTOR;
192 }
193
194 // Have allocation in OLD and LO failed?
195 if (old_gen_exhausted_) {
196 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
197 return MARK_COMPACTOR;
198 }
199
200 // Is there enough space left in OLD to guarantee that a scavenge can
201 // succeed?
202 //
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000203 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000204 // for object promotion. It counts only the bytes that the memory
205 // allocator has not yet allocated from the OS and assigned to any space,
206 // and does not count available bytes already in the old space or code
207 // space. Undercounting is safe---we may get an unrequested full GC when
208 // a scavenge would have succeeded.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000209 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000210 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
211 return MARK_COMPACTOR;
212 }
213
214 // Default
215 return SCAVENGER;
216}
217
218
219// TODO(1238405): Combine the infrastructure for --heap-stats and
220// --log-gc to avoid the complicated preprocessor and flag testing.
221#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
222void Heap::ReportStatisticsBeforeGC() {
223 // Heap::ReportHeapStatistics will also log NewSpace statistics when
224 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
225 // following logic is used to avoid double logging.
226#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000227 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228 if (FLAG_heap_stats) {
229 ReportHeapStatistics("Before GC");
230 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000231 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000232 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000233 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000234#elif defined(DEBUG)
235 if (FLAG_heap_stats) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000236 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000237 ReportHeapStatistics("Before GC");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000238 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000239 }
240#elif defined(ENABLE_LOGGING_AND_PROFILING)
241 if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000242 new_space_.CollectStatistics();
243 new_space_.ReportStatistics();
244 new_space_.ClearHistograms();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 }
246#endif
247}
248
249
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000250#if defined(ENABLE_LOGGING_AND_PROFILING)
251void Heap::PrintShortHeapStatistics() {
252 if (!FLAG_trace_gc_verbose) return;
253 PrintF("Memory allocator, used: %8d, available: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000254 MemoryAllocator::Size(),
255 MemoryAllocator::Available());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000256 PrintF("New space, used: %8d, available: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000257 Heap::new_space_.Size(),
258 new_space_.Available());
259 PrintF("Old pointers, used: %8d, available: %8d, waste: %8d\n",
260 old_pointer_space_->Size(),
261 old_pointer_space_->Available(),
262 old_pointer_space_->Waste());
263 PrintF("Old data space, used: %8d, available: %8d, waste: %8d\n",
264 old_data_space_->Size(),
265 old_data_space_->Available(),
266 old_data_space_->Waste());
267 PrintF("Code space, used: %8d, available: %8d, waste: %8d\n",
268 code_space_->Size(),
269 code_space_->Available(),
270 code_space_->Waste());
271 PrintF("Map space, used: %8d, available: %8d, waste: %8d\n",
272 map_space_->Size(),
273 map_space_->Available(),
274 map_space_->Waste());
275 PrintF("Cell space, used: %8d, available: %8d, waste: %8d\n",
276 cell_space_->Size(),
277 cell_space_->Available(),
278 cell_space_->Waste());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000279 PrintF("Large object space, used: %8d, avaialble: %8d\n",
ager@chromium.org3811b432009-10-28 14:53:37 +0000280 lo_space_->Size(),
281 lo_space_->Available());
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000282}
283#endif
284
285
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000286// TODO(1238405): Combine the infrastructure for --heap-stats and
287// --log-gc to avoid the complicated preprocessor and flag testing.
288void Heap::ReportStatisticsAfterGC() {
289 // Similar to the before GC, we use some complicated logic to ensure that
290 // NewSpace statistics are logged exactly once when --log-gc is turned on.
291#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
292 if (FLAG_heap_stats) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +0000293 new_space_.CollectStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000294 ReportHeapStatistics("After GC");
295 } else if (FLAG_log_gc) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000296 new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000297 }
298#elif defined(DEBUG)
299 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
300#elif defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000301 if (FLAG_log_gc) new_space_.ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000302#endif
303}
304#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
305
306
307void Heap::GarbageCollectionPrologue() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000308 TranscendentalCache::Clear();
kasper.lund7276f142008-07-30 08:49:36 +0000309 gc_count_++;
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000310 unflattened_strings_length_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000311#ifdef DEBUG
312 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
313 allow_allocation(false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000314
315 if (FLAG_verify_heap) {
316 Verify();
317 }
318
319 if (FLAG_gc_verbose) Print();
320
321 if (FLAG_print_rset) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000322 // Not all spaces have remembered set bits that we care about.
323 old_pointer_space_->PrintRSet();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 map_space_->PrintRSet();
325 lo_space_->PrintRSet();
326 }
327#endif
328
329#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
330 ReportStatisticsBeforeGC();
331#endif
332}
333
334int Heap::SizeOfObjects() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000335 int total = 0;
336 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000337 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000338 total += space->Size();
339 }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000340 return total;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341}
342
343void Heap::GarbageCollectionEpilogue() {
344#ifdef DEBUG
345 allow_allocation(true);
346 ZapFromSpace();
347
348 if (FLAG_verify_heap) {
349 Verify();
350 }
351
352 if (FLAG_print_global_handles) GlobalHandles::Print();
353 if (FLAG_print_handles) PrintHandles();
354 if (FLAG_gc_verbose) Print();
355 if (FLAG_code_stats) ReportCodeStatistics("After GC");
356#endif
357
358 Counters::alive_after_last_gc.Set(SizeOfObjects());
359
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000360 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
361 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000362#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
363 ReportStatisticsAfterGC();
364#endif
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000365#ifdef ENABLE_DEBUGGER_SUPPORT
366 Debug::AfterGarbageCollection();
367#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368}
369
370
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000371void Heap::CollectAllGarbage(bool force_compaction) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000372 // Since we are ignoring the return value, the exact choice of space does
373 // not matter, so long as we do not specify NEW_SPACE, which would not
374 // cause a full GC.
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000375 MarkCompactCollector::SetForceCompaction(force_compaction);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000376 CollectGarbage(0, OLD_POINTER_SPACE);
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +0000377 MarkCompactCollector::SetForceCompaction(false);
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000378}
379
380
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000381bool Heap::CollectGarbage(int requested_size, AllocationSpace space) {
382 // The VM is in the GC state until exiting this function.
383 VMState state(GC);
384
385#ifdef DEBUG
386 // Reset the allocation timeout to the GC interval, but make sure to
387 // allow at least a few allocations after a collection. The reason
388 // for this is that we have a lot of allocation sequences and we
389 // assume that a garbage collection will allow the subsequent
390 // allocation attempts to go through.
391 allocation_timeout_ = Max(6, FLAG_gc_interval);
392#endif
393
394 { GCTracer tracer;
395 GarbageCollectionPrologue();
kasper.lund7276f142008-07-30 08:49:36 +0000396 // The GC count was incremented in the prologue. Tell the tracer about
397 // it.
398 tracer.set_gc_count(gc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000399
400 GarbageCollector collector = SelectGarbageCollector(space);
kasper.lund7276f142008-07-30 08:49:36 +0000401 // Tell the tracer which collector we've selected.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000402 tracer.set_collector(collector);
403
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000404 HistogramTimer* rate = (collector == SCAVENGER)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000405 ? &Counters::gc_scavenger
406 : &Counters::gc_compactor;
407 rate->Start();
kasper.lund7276f142008-07-30 08:49:36 +0000408 PerformGarbageCollection(space, collector, &tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000409 rate->Stop();
410
411 GarbageCollectionEpilogue();
412 }
413
414
415#ifdef ENABLE_LOGGING_AND_PROFILING
416 if (FLAG_log_gc) HeapProfiler::WriteSample();
417#endif
418
419 switch (space) {
420 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000421 return new_space_.Available() >= requested_size;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000422 case OLD_POINTER_SPACE:
423 return old_pointer_space_->Available() >= requested_size;
424 case OLD_DATA_SPACE:
425 return old_data_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000426 case CODE_SPACE:
427 return code_space_->Available() >= requested_size;
428 case MAP_SPACE:
429 return map_space_->Available() >= requested_size;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000430 case CELL_SPACE:
431 return cell_space_->Available() >= requested_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432 case LO_SPACE:
433 return lo_space_->Available() >= requested_size;
434 }
435 return false;
436}
437
438
kasper.lund7276f142008-07-30 08:49:36 +0000439void Heap::PerformScavenge() {
440 GCTracer tracer;
441 PerformGarbageCollection(NEW_SPACE, SCAVENGER, &tracer);
442}
443
444
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000445#ifdef DEBUG
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000446// Helper class for verifying the symbol table.
447class SymbolTableVerifier : public ObjectVisitor {
448 public:
449 SymbolTableVerifier() { }
450 void VisitPointers(Object** start, Object** end) {
451 // Visit all HeapObject pointers in [start, end).
452 for (Object** p = start; p < end; p++) {
453 if ((*p)->IsHeapObject()) {
454 // Check that the symbol is actually a symbol.
455 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000456 }
457 }
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000458 }
459};
460#endif // DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000461
kasperl@chromium.org416c5b02009-04-14 14:03:52 +0000462
463static void VerifySymbolTable() {
464#ifdef DEBUG
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000465 SymbolTableVerifier verifier;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000466 Heap::symbol_table()->IterateElements(&verifier);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000467#endif // DEBUG
468}
469
470
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000471void Heap::ReserveSpace(
472 int new_space_size,
473 int pointer_space_size,
474 int data_space_size,
475 int code_space_size,
476 int map_space_size,
477 int cell_space_size,
478 int large_object_size) {
479 NewSpace* new_space = Heap::new_space();
480 PagedSpace* old_pointer_space = Heap::old_pointer_space();
481 PagedSpace* old_data_space = Heap::old_data_space();
482 PagedSpace* code_space = Heap::code_space();
483 PagedSpace* map_space = Heap::map_space();
484 PagedSpace* cell_space = Heap::cell_space();
485 LargeObjectSpace* lo_space = Heap::lo_space();
486 bool gc_performed = true;
487 while (gc_performed) {
488 gc_performed = false;
489 if (!new_space->ReserveSpace(new_space_size)) {
490 Heap::CollectGarbage(new_space_size, NEW_SPACE);
491 gc_performed = true;
492 }
493 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
494 Heap::CollectGarbage(pointer_space_size, OLD_POINTER_SPACE);
495 gc_performed = true;
496 }
497 if (!(old_data_space->ReserveSpace(data_space_size))) {
498 Heap::CollectGarbage(data_space_size, OLD_DATA_SPACE);
499 gc_performed = true;
500 }
501 if (!(code_space->ReserveSpace(code_space_size))) {
502 Heap::CollectGarbage(code_space_size, CODE_SPACE);
503 gc_performed = true;
504 }
505 if (!(map_space->ReserveSpace(map_space_size))) {
506 Heap::CollectGarbage(map_space_size, MAP_SPACE);
507 gc_performed = true;
508 }
509 if (!(cell_space->ReserveSpace(cell_space_size))) {
510 Heap::CollectGarbage(cell_space_size, CELL_SPACE);
511 gc_performed = true;
512 }
513 // We add a slack-factor of 2 in order to have space for the remembered
514 // set and a series of large-object allocations that are only just larger
515 // than the page size.
516 large_object_size *= 2;
517 // The ReserveSpace method on the large object space checks how much
518 // we can expand the old generation. This includes expansion caused by
519 // allocation in the other spaces.
520 large_object_size += cell_space_size + map_space_size + code_space_size +
521 data_space_size + pointer_space_size;
522 if (!(lo_space->ReserveSpace(large_object_size))) {
523 Heap::CollectGarbage(large_object_size, LO_SPACE);
524 gc_performed = true;
525 }
526 }
527}
528
529
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000530void Heap::EnsureFromSpaceIsCommitted() {
531 if (new_space_.CommitFromSpaceIfNeeded()) return;
532
533 // Committing memory to from space failed.
534 // Try shrinking and try again.
535 Shrink();
536 if (new_space_.CommitFromSpaceIfNeeded()) return;
537
538 // Committing memory to from space failed again.
539 // Memory is exhausted and we will die.
540 V8::FatalProcessOutOfMemory("Committing semi space failed.");
541}
542
543
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544void Heap::PerformGarbageCollection(AllocationSpace space,
kasper.lund7276f142008-07-30 08:49:36 +0000545 GarbageCollector collector,
546 GCTracer* tracer) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000547 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
549 ASSERT(!allocation_allowed_);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000550 GCTracer::ExternalScope scope(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551 global_gc_prologue_callback_();
552 }
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000553
554 GCType gc_type =
555 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
556
557 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
558 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
559 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
560 }
561 }
562
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000563 EnsureFromSpaceIsCommitted();
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000564
565 // Perform mark-sweep with optional compaction.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566 if (collector == MARK_COMPACTOR) {
kasper.lund7276f142008-07-30 08:49:36 +0000567 MarkCompact(tracer);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000568 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000569
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000570 // Always perform a scavenge to make room in new space.
571 Scavenge();
572
573 // Update the old space promotion limits after the scavenge due to
574 // promotions during scavenge.
575 if (collector == MARK_COMPACTOR) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +0000576 int old_gen_size = PromotedSpaceSize();
577 old_gen_promotion_limit_ =
578 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
579 old_gen_allocation_limit_ =
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000580 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000581 old_gen_exhausted_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000582 }
ager@chromium.org439e85a2009-08-26 13:15:29 +0000583
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000584 Counters::objs_since_last_young.Set(0);
585
ager@chromium.org3811b432009-10-28 14:53:37 +0000586 if (collector == MARK_COMPACTOR) {
587 DisableAssertNoAllocation allow_allocation;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000588 GCTracer::ExternalScope scope(tracer);
ager@chromium.org3811b432009-10-28 14:53:37 +0000589 GlobalHandles::PostGarbageCollectionProcessing();
590 }
591
592 // Update relocatables.
593 Relocatable::PostGarbageCollectionProcessing();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594
kasper.lund7276f142008-07-30 08:49:36 +0000595 if (collector == MARK_COMPACTOR) {
596 // Register the amount of external allocated memory.
597 amount_of_external_allocated_memory_at_last_global_gc_ =
598 amount_of_external_allocated_memory_;
599 }
600
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000601 GCCallbackFlags callback_flags = tracer->is_compacting()
602 ? kGCCallbackFlagCompacted
603 : kNoGCCallbackFlags;
604 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
605 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
606 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
607 }
608 }
609
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000610 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
611 ASSERT(!allocation_allowed_);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000612 GCTracer::ExternalScope scope(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000613 global_gc_epilogue_callback_();
614 }
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +0000615 VerifySymbolTable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000616}
617
618
kasper.lund7276f142008-07-30 08:49:36 +0000619void Heap::MarkCompact(GCTracer* tracer) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000620 gc_state_ = MARK_COMPACT;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000621 mc_count_++;
kasper.lund7276f142008-07-30 08:49:36 +0000622 tracer->set_full_gc_count(mc_count_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000623 LOG(ResourceEvent("markcompact", "begin"));
624
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000625 MarkCompactCollector::Prepare(tracer);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000626
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000627 bool is_compacting = MarkCompactCollector::IsCompacting();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000628
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000629 MarkCompactPrologue(is_compacting);
630
631 MarkCompactCollector::CollectGarbage();
632
633 MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000634
635 LOG(ResourceEvent("markcompact", "end"));
636
637 gc_state_ = NOT_IN_GC;
638
639 Shrink();
640
641 Counters::objs_since_last_full.Set(0);
kasperl@chromium.org8b2bb262010-03-01 09:46:28 +0000642
643 contexts_disposed_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000644}
645
646
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000647void Heap::MarkCompactPrologue(bool is_compacting) {
648 // At any old GC clear the keyed lookup cache to enable collection of unused
649 // maps.
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000650 KeyedLookupCache::Clear();
651 ContextSlotCache::Clear();
652 DescriptorLookupCache::Clear();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000653
kasperl@chromium.orgb9123622008-09-17 14:05:56 +0000654 CompilationCache::MarkCompactPrologue();
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000655
656 Top::MarkCompactPrologue(is_compacting);
657 ThreadManager::MarkCompactPrologue(is_compacting);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000658
659 if (is_compacting) FlushNumberStringCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000660}
661
662
kasperl@chromium.org061ef742009-02-27 12:16:20 +0000663void Heap::MarkCompactEpilogue(bool is_compacting) {
664 Top::MarkCompactEpilogue(is_compacting);
665 ThreadManager::MarkCompactEpilogue(is_compacting);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000666}
667
668
669Object* Heap::FindCodeObject(Address a) {
670 Object* obj = code_space_->FindObject(a);
671 if (obj->IsFailure()) {
672 obj = lo_space_->FindObject(a);
673 }
kasper.lund7276f142008-07-30 08:49:36 +0000674 ASSERT(!obj->IsFailure());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000675 return obj;
676}
677
678
679// Helper class for copying HeapObjects
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000680class ScavengeVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681 public:
682
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000683 void VisitPointer(Object** p) { ScavengePointer(p); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684
685 void VisitPointers(Object** start, Object** end) {
686 // Copy all HeapObject pointers in [start, end)
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000687 for (Object** p = start; p < end; p++) ScavengePointer(p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000688 }
689
690 private:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000691 void ScavengePointer(Object** p) {
692 Object* object = *p;
693 if (!Heap::InNewSpace(object)) return;
694 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
695 reinterpret_cast<HeapObject*>(object));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000696 }
697};
698
699
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000700// A queue of pointers and maps of to-be-promoted objects during a
701// scavenge collection.
702class PromotionQueue {
703 public:
704 void Initialize(Address start_address) {
705 front_ = rear_ = reinterpret_cast<HeapObject**>(start_address);
706 }
707
708 bool is_empty() { return front_ <= rear_; }
709
710 void insert(HeapObject* object, Map* map) {
711 *(--rear_) = object;
712 *(--rear_) = map;
713 // Assert no overflow into live objects.
714 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
715 }
716
717 void remove(HeapObject** object, Map** map) {
718 *object = *(--front_);
719 *map = Map::cast(*(--front_));
720 // Assert no underflow.
721 ASSERT(front_ >= rear_);
722 }
723
724 private:
725 // The front of the queue is higher in memory than the rear.
726 HeapObject** front_;
727 HeapObject** rear_;
728};
729
730
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000731// Shared state read by the scavenge collector and set by ScavengeObject.
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000732static PromotionQueue promotion_queue;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000733
734
735#ifdef DEBUG
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000736// Visitor class to verify pointers in code or data space do not point into
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737// new space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000738class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 public:
740 void VisitPointers(Object** start, Object**end) {
741 for (Object** current = start; current < end; current++) {
742 if ((*current)->IsHeapObject()) {
743 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
744 }
745 }
746 }
747};
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000748
749
750static void VerifyNonPointerSpacePointers() {
751 // Verify that there are no pointers to new space in spaces where we
752 // do not expect them.
753 VerifyNonPointerSpacePointersVisitor v;
754 HeapObjectIterator code_it(Heap::code_space());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000755 for (HeapObject* object = code_it.next();
756 object != NULL; object = code_it.next())
christian.plesner.hansen@gmail.com2bc58ef2009-09-22 10:00:30 +0000757 object->Iterate(&v);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000758
759 HeapObjectIterator data_it(Heap::old_data_space());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000760 for (HeapObject* object = data_it.next();
761 object != NULL; object = data_it.next())
762 object->Iterate(&v);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000763}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000764#endif
765
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000766
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000767void Heap::Scavenge() {
768#ifdef DEBUG
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000769 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770#endif
771
772 gc_state_ = SCAVENGE;
773
774 // Implements Cheney's copying algorithm
775 LOG(ResourceEvent("scavenge", "begin"));
776
ager@chromium.org5aa501c2009-06-23 07:57:28 +0000777 // Clear descriptor cache.
778 DescriptorLookupCache::Clear();
779
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000780 // Used for updating survived_since_last_expansion_ at function end.
781 int survived_watermark = PromotedSpaceSize();
782
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000783 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000784 survived_since_last_expansion_ > new_space_.Capacity()) {
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000785 // Grow the size of new space if there is room to grow and enough
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000786 // data has survived scavenge since the last expansion.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000787 new_space_.Grow();
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000788 survived_since_last_expansion_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000789 }
790
791 // Flip the semispaces. After flipping, to space is empty, from space has
792 // live objects.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000793 new_space_.Flip();
794 new_space_.ResetAllocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000795
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000796 // We need to sweep newly copied objects which can be either in the
797 // to space or promoted to the old generation. For to-space
798 // objects, we treat the bottom of the to space as a queue. Newly
799 // copied and unswept objects lie between a 'front' mark and the
800 // allocation pointer.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000801 //
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000802 // Promoted objects can go into various old-generation spaces, and
803 // can be allocated internally in the spaces (from the free list).
804 // We treat the top of the to space as a queue of addresses of
805 // promoted objects. The addresses of newly promoted and unswept
806 // objects lie between a 'front' mark and a 'rear' mark that is
807 // updated as a side effect of promoting an object.
808 //
809 // There is guaranteed to be enough room at the top of the to space
810 // for the addresses of promoted objects: every object promoted
811 // frees up its size in bytes from the top of the new space, and
812 // objects are at least one pointer in size.
813 Address new_space_front = new_space_.ToSpaceLow();
814 promotion_queue.Initialize(new_space_.ToSpaceHigh());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000815
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000816 ScavengeVisitor scavenge_visitor;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 // Copy roots.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000818 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000819
820 // Copy objects reachable from the old generation. By definition,
821 // there are no intergenerational pointers in code or data spaces.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000822 IterateRSet(old_pointer_space_, &ScavengePointer);
823 IterateRSet(map_space_, &ScavengePointer);
824 lo_space_->IterateRSet(&ScavengePointer);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000825
826 // Copy objects reachable from cells by scavenging cell values directly.
827 HeapObjectIterator cell_iterator(cell_space_);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +0000828 for (HeapObject* cell = cell_iterator.next();
829 cell != NULL; cell = cell_iterator.next()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000830 if (cell->IsJSGlobalPropertyCell()) {
831 Address value_address =
832 reinterpret_cast<Address>(cell) +
833 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
834 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
835 }
836 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000837
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000838 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
839
840 ScavengeExternalStringTable();
841 ASSERT(new_space_front == new_space_.top());
842
843 // Set age mark.
844 new_space_.set_age_mark(new_space_.top());
845
846 // Update how much has survived scavenge.
847 survived_since_last_expansion_ +=
848 (PromotedSpaceSize() - survived_watermark) + new_space_.Size();
849
850 LOG(ResourceEvent("scavenge", "end"));
851
852 gc_state_ = NOT_IN_GC;
853}
854
855
856void Heap::ScavengeExternalStringTable() {
857 ExternalStringTable::Verify();
858
859 if (ExternalStringTable::new_space_strings_.is_empty()) return;
860
861 Object** start = &ExternalStringTable::new_space_strings_[0];
862 Object** end = start + ExternalStringTable::new_space_strings_.length();
863 Object** last = start;
864
865 for (Object** p = start; p < end; ++p) {
866 ASSERT(Heap::InFromSpace(*p));
867 MapWord first_word = HeapObject::cast(*p)->map_word();
868
869 if (!first_word.IsForwardingAddress()) {
870 // Unreachable external string can be finalized.
871 FinalizeExternalString(String::cast(*p));
872 continue;
873 }
874
875 // String is still reachable.
876 String* target = String::cast(first_word.ToForwardingAddress());
877 ASSERT(target->IsExternalString());
878
879 if (Heap::InNewSpace(target)) {
880 // String is still in new space. Update the table entry.
881 *last = target;
882 ++last;
883 } else {
884 // String got promoted. Move it to the old string list.
885 ExternalStringTable::AddOldString(target);
886 }
887 }
888
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000889 ASSERT(last <= end);
890 ExternalStringTable::ShrinkNewStrings(static_cast<int>(last - start));
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000891}
892
893
894Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
895 Address new_space_front) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000896 do {
897 ASSERT(new_space_front <= new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000899 // The addresses new_space_front and new_space_.top() define a
900 // queue of unprocessed copied objects. Process them until the
901 // queue is empty.
902 while (new_space_front < new_space_.top()) {
903 HeapObject* object = HeapObject::FromAddress(new_space_front);
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000904 object->Iterate(scavenge_visitor);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000905 new_space_front += object->Size();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000906 }
907
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000908 // Promote and process all the to-be-promoted objects.
909 while (!promotion_queue.is_empty()) {
910 HeapObject* source;
911 Map* map;
912 promotion_queue.remove(&source, &map);
913 // Copy the from-space object to its new location (given by the
914 // forwarding address) and fix its map.
915 HeapObject* target = source->map_word().ToForwardingAddress();
916 CopyBlock(reinterpret_cast<Object**>(target->address()),
917 reinterpret_cast<Object**>(source->address()),
918 source->SizeFromMap(map));
919 target->set_map(map);
920
921#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
922 // Update NewSpace stats if necessary.
923 RecordCopiedObject(target);
924#endif
925 // Visit the newly copied object for pointers to new space.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000926 target->Iterate(scavenge_visitor);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000927 UpdateRSet(target);
928 }
929
930 // Take another spin if there are now unswept objects in new space
931 // (there are currently no more unswept promoted objects).
932 } while (new_space_front < new_space_.top());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000933
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000934 return new_space_front;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000935}
936
937
938void Heap::ClearRSetRange(Address start, int size_in_bytes) {
939 uint32_t start_bit;
940 Address start_word_address =
941 Page::ComputeRSetBitPosition(start, 0, &start_bit);
942 uint32_t end_bit;
943 Address end_word_address =
944 Page::ComputeRSetBitPosition(start + size_in_bytes - kIntSize,
945 0,
946 &end_bit);
947
948 // We want to clear the bits in the starting word starting with the
949 // first bit, and in the ending word up to and including the last
950 // bit. Build a pair of bitmasks to do that.
951 uint32_t start_bitmask = start_bit - 1;
952 uint32_t end_bitmask = ~((end_bit << 1) - 1);
953
954 // If the start address and end address are the same, we mask that
955 // word once, otherwise mask the starting and ending word
956 // separately and all the ones in between.
957 if (start_word_address == end_word_address) {
958 Memory::uint32_at(start_word_address) &= (start_bitmask | end_bitmask);
959 } else {
960 Memory::uint32_at(start_word_address) &= start_bitmask;
961 Memory::uint32_at(end_word_address) &= end_bitmask;
962 start_word_address += kIntSize;
963 memset(start_word_address, 0, end_word_address - start_word_address);
964 }
965}
966
967
968class UpdateRSetVisitor: public ObjectVisitor {
969 public:
970
971 void VisitPointer(Object** p) {
972 UpdateRSet(p);
973 }
974
975 void VisitPointers(Object** start, Object** end) {
976 // Update a store into slots [start, end), used (a) to update remembered
977 // set when promoting a young object to old space or (b) to rebuild
978 // remembered sets after a mark-compact collection.
979 for (Object** p = start; p < end; p++) UpdateRSet(p);
980 }
981 private:
982
983 void UpdateRSet(Object** p) {
984 // The remembered set should not be set. It should be clear for objects
985 // newly copied to old space, and it is cleared before rebuilding in the
986 // mark-compact collector.
987 ASSERT(!Page::IsRSetSet(reinterpret_cast<Address>(p), 0));
988 if (Heap::InNewSpace(*p)) {
989 Page::SetRSet(reinterpret_cast<Address>(p), 0);
990 }
991 }
992};
993
994
995int Heap::UpdateRSet(HeapObject* obj) {
996 ASSERT(!InNewSpace(obj));
997 // Special handling of fixed arrays to iterate the body based on the start
998 // address and offset. Just iterating the pointers as in UpdateRSetVisitor
999 // will not work because Page::SetRSet needs to have the start of the
sgjesse@chromium.orgb9d7da12009-08-05 08:38:10 +00001000 // object for large object pages.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001001 if (obj->IsFixedArray()) {
1002 FixedArray* array = FixedArray::cast(obj);
1003 int length = array->length();
1004 for (int i = 0; i < length; i++) {
1005 int offset = FixedArray::kHeaderSize + i * kPointerSize;
1006 ASSERT(!Page::IsRSetSet(obj->address(), offset));
1007 if (Heap::InNewSpace(array->get(i))) {
1008 Page::SetRSet(obj->address(), offset);
1009 }
1010 }
1011 } else if (!obj->IsCode()) {
1012 // Skip code object, we know it does not contain inter-generational
1013 // pointers.
1014 UpdateRSetVisitor v;
1015 obj->Iterate(&v);
1016 }
1017 return obj->Size();
1018}
1019
1020
1021void Heap::RebuildRSets() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001022 // By definition, we do not care about remembered set bits in code,
1023 // data, or cell spaces.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024 map_space_->ClearRSet();
1025 RebuildRSets(map_space_);
1026
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001027 old_pointer_space_->ClearRSet();
1028 RebuildRSets(old_pointer_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001029
1030 Heap::lo_space_->ClearRSet();
1031 RebuildRSets(lo_space_);
1032}
1033
1034
1035void Heap::RebuildRSets(PagedSpace* space) {
1036 HeapObjectIterator it(space);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001037 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1038 Heap::UpdateRSet(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001039}
1040
1041
1042void Heap::RebuildRSets(LargeObjectSpace* space) {
1043 LargeObjectIterator it(space);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001044 for (HeapObject* obj = it.next(); obj != NULL; obj = it.next())
1045 Heap::UpdateRSet(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046}
1047
1048
1049#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1050void Heap::RecordCopiedObject(HeapObject* obj) {
1051 bool should_record = false;
1052#ifdef DEBUG
1053 should_record = FLAG_heap_stats;
1054#endif
1055#ifdef ENABLE_LOGGING_AND_PROFILING
1056 should_record = should_record || FLAG_log_gc;
1057#endif
1058 if (should_record) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001059 if (new_space_.Contains(obj)) {
1060 new_space_.RecordAllocation(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061 } else {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001062 new_space_.RecordPromotion(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001063 }
1064 }
1065}
1066#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1067
1068
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001069
1070HeapObject* Heap::MigrateObject(HeapObject* source,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001071 HeapObject* target,
1072 int size) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001073 // Copy the content of source to target.
1074 CopyBlock(reinterpret_cast<Object**>(target->address()),
1075 reinterpret_cast<Object**>(source->address()),
1076 size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001077
kasper.lund7276f142008-07-30 08:49:36 +00001078 // Set the forwarding address.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001079 source->set_map_word(MapWord::FromForwardingAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001080
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001081#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001082 // Update NewSpace stats if necessary.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001083 RecordCopiedObject(target);
1084#endif
1085
1086 return target;
1087}
1088
1089
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001090static inline bool IsShortcutCandidate(HeapObject* object, Map* map) {
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001091 STATIC_ASSERT(kNotStringTag != 0 && kSymbolTag != 0);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001092 ASSERT(object->map() == map);
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001093 InstanceType type = map->instance_type();
1094 if ((type & kShortcutTypeMask) != kShortcutTypeTag) return false;
1095 ASSERT(object->IsString() && !object->IsSymbol());
1096 return ConsString::cast(object)->unchecked_second() == Heap::empty_string();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001097}
1098
1099
1100void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1101 ASSERT(InFromSpace(object));
1102 MapWord first_word = object->map_word();
1103 ASSERT(!first_word.IsForwardingAddress());
1104
1105 // Optimization: Bypass flattened ConsString objects.
1106 if (IsShortcutCandidate(object, first_word.ToMap())) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00001107 object = HeapObject::cast(ConsString::cast(object)->unchecked_first());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001108 *p = object;
1109 // After patching *p we have to repeat the checks that object is in the
1110 // active semispace of the young generation and not already copied.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001111 if (!InNewSpace(object)) return;
kasper.lund7276f142008-07-30 08:49:36 +00001112 first_word = object->map_word();
1113 if (first_word.IsForwardingAddress()) {
1114 *p = first_word.ToForwardingAddress();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001115 return;
1116 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001117 }
1118
kasper.lund7276f142008-07-30 08:49:36 +00001119 int object_size = object->SizeFromMap(first_word.ToMap());
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001120 // We rely on live objects in new space to be at least two pointers,
1121 // so we can store the from-space address and map pointer of promoted
1122 // objects in the to space.
1123 ASSERT(object_size >= 2 * kPointerSize);
1124
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001125 // If the object should be promoted, we try to copy it to old space.
1126 if (ShouldBePromoted(object->address(), object_size)) {
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001127 Object* result;
1128 if (object_size > MaxObjectSizeInPagedSpace()) {
1129 result = lo_space_->AllocateRawFixedArray(object_size);
1130 if (!result->IsFailure()) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001131 // Save the from-space object pointer and its map pointer at the
1132 // top of the to space to be swept and copied later. Write the
1133 // forwarding address over the map word of the from-space
1134 // object.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001135 HeapObject* target = HeapObject::cast(result);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +00001136 promotion_queue.insert(object, first_word.ToMap());
1137 object->set_map_word(MapWord::FromForwardingAddress(target));
1138
1139 // Give the space allocated for the result a proper map by
1140 // treating it as a free list node (not linked into the free
1141 // list).
1142 FreeListNode* node = FreeListNode::FromAddress(target->address());
1143 node->set_size(object_size);
1144
1145 *p = target;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001146 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001147 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001148 } else {
1149 OldSpace* target_space = Heap::TargetSpace(object);
1150 ASSERT(target_space == Heap::old_pointer_space_ ||
1151 target_space == Heap::old_data_space_);
1152 result = target_space->AllocateRaw(object_size);
1153 if (!result->IsFailure()) {
1154 HeapObject* target = HeapObject::cast(result);
1155 if (target_space == Heap::old_pointer_space_) {
1156 // Save the from-space object pointer and its map pointer at the
1157 // top of the to space to be swept and copied later. Write the
1158 // forwarding address over the map word of the from-space
1159 // object.
1160 promotion_queue.insert(object, first_word.ToMap());
1161 object->set_map_word(MapWord::FromForwardingAddress(target));
1162
1163 // Give the space allocated for the result a proper map by
1164 // treating it as a free list node (not linked into the free
1165 // list).
1166 FreeListNode* node = FreeListNode::FromAddress(target->address());
1167 node->set_size(object_size);
1168
1169 *p = target;
1170 } else {
1171 // Objects promoted to the data space can be copied immediately
1172 // and not revisited---we will never sweep that space for
1173 // pointers and the copied objects do not contain pointers to
1174 // new space objects.
1175 *p = MigrateObject(object, target, object_size);
1176#ifdef DEBUG
1177 VerifyNonPointerSpacePointersVisitor v;
1178 (*p)->Iterate(&v);
1179#endif
1180 }
1181 return;
1182 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001183 }
1184 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001185 // The object should remain in new space or the old space allocation failed.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001186 Object* result = new_space_.AllocateRaw(object_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001187 // Failed allocation at this point is utterly unexpected.
1188 ASSERT(!result->IsFailure());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001189 *p = MigrateObject(object, HeapObject::cast(result), object_size);
1190}
1191
1192
1193void Heap::ScavengePointer(HeapObject** p) {
1194 ScavengeObject(p, *p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001195}
1196
1197
1198Object* Heap::AllocatePartialMap(InstanceType instance_type,
1199 int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001200 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001201 if (result->IsFailure()) return result;
1202
1203 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001204 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001205 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1206 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001207 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001208 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001209 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001210 reinterpret_cast<Map*>(result)->set_bit_field(0);
1211 reinterpret_cast<Map*>(result)->set_bit_field2(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001212 return result;
1213}
1214
1215
1216Object* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001217 Object* result = AllocateRawMap();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001218 if (result->IsFailure()) return result;
1219
1220 Map* map = reinterpret_cast<Map*>(result);
1221 map->set_map(meta_map());
1222 map->set_instance_type(instance_type);
1223 map->set_prototype(null_value());
1224 map->set_constructor(null_value());
1225 map->set_instance_size(instance_size);
ager@chromium.org7c537e22008-10-16 08:43:32 +00001226 map->set_inobject_properties(0);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001227 map->set_pre_allocated_property_fields(0);
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001228 map->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001229 map->set_code_cache(empty_fixed_array());
1230 map->set_unused_property_fields(0);
1231 map->set_bit_field(0);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001232 map->set_bit_field2(1 << Map::kIsExtensible);
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00001233
1234 // If the map object is aligned fill the padding area with Smi 0 objects.
1235 if (Map::kPadStart < Map::kSize) {
1236 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1237 0,
1238 Map::kSize - Map::kPadStart);
1239 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001240 return map;
1241}
1242
1243
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001244Object* Heap::AllocateCodeCache() {
1245 Object* result = AllocateStruct(CODE_CACHE_TYPE);
1246 if (result->IsFailure()) return result;
1247 CodeCache* code_cache = CodeCache::cast(result);
1248 code_cache->set_default_cache(empty_fixed_array());
1249 code_cache->set_normal_type_cache(undefined_value());
1250 return code_cache;
1251}
1252
1253
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001254const Heap::StringTypeTable Heap::string_type_table[] = {
1255#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1256 {type, size, k##camel_name##MapRootIndex},
1257 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1258#undef STRING_TYPE_ELEMENT
1259};
1260
1261
1262const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1263#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1264 {contents, k##name##RootIndex},
1265 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1266#undef CONSTANT_SYMBOL_ELEMENT
1267};
1268
1269
1270const Heap::StructTable Heap::struct_table[] = {
1271#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1272 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1273 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1274#undef STRUCT_TABLE_ELEMENT
1275};
1276
1277
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001278bool Heap::CreateInitialMaps() {
1279 Object* obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1280 if (obj->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001281 // Map::cast cannot be used due to uninitialized map field.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001282 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1283 set_meta_map(new_meta_map);
1284 new_meta_map->set_map(new_meta_map);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001285
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001286 obj = AllocatePartialMap(FIXED_ARRAY_TYPE, FixedArray::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001287 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001288 set_fixed_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001289
1290 obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1291 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001292 set_oddball_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001293
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00001294 // Allocate the empty array.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001295 obj = AllocateEmptyFixedArray();
1296 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001297 set_empty_fixed_array(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001298
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001299 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001300 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001301 set_null_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001302
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001303 // Allocate the empty descriptor array.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001304 obj = AllocateEmptyFixedArray();
1305 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001306 set_empty_descriptor_array(DescriptorArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001307
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001308 // Fix the instance_descriptors for the existing maps.
1309 meta_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001310 meta_map()->set_code_cache(empty_fixed_array());
1311
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001312 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001313 fixed_array_map()->set_code_cache(empty_fixed_array());
1314
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001315 oddball_map()->set_instance_descriptors(empty_descriptor_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001316 oddball_map()->set_code_cache(empty_fixed_array());
1317
1318 // Fix prototype object for existing maps.
1319 meta_map()->set_prototype(null_value());
1320 meta_map()->set_constructor(null_value());
1321
1322 fixed_array_map()->set_prototype(null_value());
1323 fixed_array_map()->set_constructor(null_value());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001324
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001325 oddball_map()->set_prototype(null_value());
1326 oddball_map()->set_constructor(null_value());
1327
1328 obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1329 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001330 set_heap_number_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001331
1332 obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1333 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001334 set_proxy_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001335
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001336 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1337 const StringTypeTable& entry = string_type_table[i];
1338 obj = AllocateMap(entry.type, entry.size);
1339 if (obj->IsFailure()) return false;
1340 roots_[entry.index] = Map::cast(obj);
1341 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001342
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001343 obj = AllocateMap(STRING_TYPE, SeqTwoByteString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001344 if (obj->IsFailure()) return false;
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001345 set_undetectable_string_map(Map::cast(obj));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001346 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001347
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001348 obj = AllocateMap(ASCII_STRING_TYPE, SeqAsciiString::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001349 if (obj->IsFailure()) return false;
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001350 set_undetectable_ascii_string_map(Map::cast(obj));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001351 Map::cast(obj)->set_is_undetectable();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001352
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001353 obj = AllocateMap(BYTE_ARRAY_TYPE, ByteArray::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001354 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001355 set_byte_array_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001356
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001357 obj = AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1358 if (obj->IsFailure()) return false;
1359 set_pixel_array_map(Map::cast(obj));
1360
ager@chromium.org3811b432009-10-28 14:53:37 +00001361 obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1362 ExternalArray::kAlignedSize);
1363 if (obj->IsFailure()) return false;
1364 set_external_byte_array_map(Map::cast(obj));
1365
1366 obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1367 ExternalArray::kAlignedSize);
1368 if (obj->IsFailure()) return false;
1369 set_external_unsigned_byte_array_map(Map::cast(obj));
1370
1371 obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1372 ExternalArray::kAlignedSize);
1373 if (obj->IsFailure()) return false;
1374 set_external_short_array_map(Map::cast(obj));
1375
1376 obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1377 ExternalArray::kAlignedSize);
1378 if (obj->IsFailure()) return false;
1379 set_external_unsigned_short_array_map(Map::cast(obj));
1380
1381 obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1382 ExternalArray::kAlignedSize);
1383 if (obj->IsFailure()) return false;
1384 set_external_int_array_map(Map::cast(obj));
1385
1386 obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1387 ExternalArray::kAlignedSize);
1388 if (obj->IsFailure()) return false;
1389 set_external_unsigned_int_array_map(Map::cast(obj));
1390
1391 obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1392 ExternalArray::kAlignedSize);
1393 if (obj->IsFailure()) return false;
1394 set_external_float_array_map(Map::cast(obj));
1395
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396 obj = AllocateMap(CODE_TYPE, Code::kHeaderSize);
1397 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001398 set_code_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001400 obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1401 JSGlobalPropertyCell::kSize);
1402 if (obj->IsFailure()) return false;
1403 set_global_property_cell_map(Map::cast(obj));
1404
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001405 obj = AllocateMap(FILLER_TYPE, kPointerSize);
1406 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001407 set_one_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001408
1409 obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1410 if (obj->IsFailure()) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001411 set_two_pointer_filler_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001412
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001413 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1414 const StructTable& entry = struct_table[i];
1415 obj = AllocateMap(entry.type, entry.size);
1416 if (obj->IsFailure()) return false;
1417 roots_[entry.index] = Map::cast(obj);
1418 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001419
ager@chromium.org236ad962008-09-25 09:45:57 +00001420 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001421 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001422 set_hash_table_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001423
ager@chromium.org236ad962008-09-25 09:45:57 +00001424 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001425 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001426 set_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001427
ager@chromium.org236ad962008-09-25 09:45:57 +00001428 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001429 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001430 set_catch_context_map(Map::cast(obj));
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001431
1432 obj = AllocateMap(FIXED_ARRAY_TYPE, HeapObject::kHeaderSize);
1433 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001434 set_global_context_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001435
1436 obj = AllocateMap(JS_FUNCTION_TYPE, JSFunction::kSize);
1437 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001438 set_boilerplate_function_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001439
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00001440 obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
1441 SharedFunctionInfo::kAlignedSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001442 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001443 set_shared_function_info_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001444
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001445 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001446 return true;
1447}
1448
1449
1450Object* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
1451 // Statically ensure that it is safe to allocate heap numbers in paged
1452 // spaces.
1453 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001454 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001455
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001456 Object* result = AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001457 if (result->IsFailure()) return result;
1458
1459 HeapObject::cast(result)->set_map(heap_number_map());
1460 HeapNumber::cast(result)->set_value(value);
1461 return result;
1462}
1463
1464
1465Object* Heap::AllocateHeapNumber(double value) {
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001466 // Use general version, if we're forced to always allocate.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001467 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1468
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001469 // This version of AllocateHeapNumber is optimized for
1470 // allocation in new space.
1471 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1472 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001473 Object* result = new_space_.AllocateRaw(HeapNumber::kSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001474 if (result->IsFailure()) return result;
1475 HeapObject::cast(result)->set_map(heap_number_map());
1476 HeapNumber::cast(result)->set_value(value);
1477 return result;
1478}
1479
1480
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001481Object* Heap::AllocateJSGlobalPropertyCell(Object* value) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001482 Object* result = AllocateRawCell();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001483 if (result->IsFailure()) return result;
1484 HeapObject::cast(result)->set_map(global_property_cell_map());
1485 JSGlobalPropertyCell::cast(result)->set_value(value);
1486 return result;
1487}
1488
1489
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001490Object* Heap::CreateOddball(Map* map,
1491 const char* to_string,
1492 Object* to_number) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001493 Object* result = Allocate(map, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494 if (result->IsFailure()) return result;
1495 return Oddball::cast(result)->Initialize(to_string, to_number);
1496}
1497
1498
1499bool Heap::CreateApiObjects() {
1500 Object* obj;
1501
1502 obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1503 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001504 set_neander_map(Map::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001505
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001506 obj = Heap::AllocateJSObjectFromMap(neander_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001507 if (obj->IsFailure()) return false;
1508 Object* elements = AllocateFixedArray(2);
1509 if (elements->IsFailure()) return false;
1510 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1511 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001512 set_message_listeners(JSObject::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001513
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001514 return true;
1515}
1516
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001517
1518void Heap::CreateCEntryStub() {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001519 CEntryStub stub(1);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001520 set_c_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001521}
1522
1523
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001524#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1525void Heap::CreateRegExpCEntryStub() {
1526 RegExpCEntryStub stub;
1527 set_re_c_entry_code(*stub.GetCode());
1528}
1529#endif
1530
1531
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001532void Heap::CreateJSEntryStub() {
1533 JSEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001534 set_js_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001535}
1536
1537
1538void Heap::CreateJSConstructEntryStub() {
1539 JSConstructEntryStub stub;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001540 set_js_construct_entry_code(*stub.GetCode());
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001541}
1542
1543
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001544void Heap::CreateFixedStubs() {
1545 // Here we create roots for fixed stubs. They are needed at GC
1546 // for cooking and uncooking (check out frames.cc).
1547 // The eliminates the need for doing dictionary lookup in the
1548 // stub cache for these stubs.
1549 HandleScope scope;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001550 // gcc-4.4 has problem generating correct code of following snippet:
1551 // { CEntryStub stub;
1552 // c_entry_code_ = *stub.GetCode();
1553 // }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001554 // { DebuggerStatementStub stub;
1555 // debugger_statement_code_ = *stub.GetCode();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001556 // }
1557 // To workaround the problem, make separate functions without inlining.
1558 Heap::CreateCEntryStub();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001559 Heap::CreateJSEntryStub();
1560 Heap::CreateJSConstructEntryStub();
ager@chromium.org18ad94b2009-09-02 08:22:29 +00001561#if V8_TARGET_ARCH_ARM && V8_NATIVE_REGEXP
1562 Heap::CreateRegExpCEntryStub();
1563#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001564}
1565
1566
1567bool Heap::CreateInitialObjects() {
1568 Object* obj;
1569
1570 // The -0 value must be set before NumberFromDouble works.
1571 obj = AllocateHeapNumber(-0.0, TENURED);
1572 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001573 set_minus_zero_value(obj);
1574 ASSERT(signbit(minus_zero_value()->Number()) != 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575
1576 obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1577 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001578 set_nan_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001579
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001580 obj = Allocate(oddball_map(), OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001581 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001582 set_undefined_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001583 ASSERT(!InNewSpace(undefined_value()));
1584
1585 // Allocate initial symbol table.
1586 obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1587 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001588 // Don't use set_symbol_table() due to asserts.
1589 roots_[kSymbolTableRootIndex] = obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001590
1591 // Assign the print strings for oddballs after creating symboltable.
1592 Object* symbol = LookupAsciiSymbol("undefined");
1593 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001594 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
1595 Oddball::cast(undefined_value())->set_to_number(nan_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001596
1597 // Assign the print strings for oddballs after creating symboltable.
1598 symbol = LookupAsciiSymbol("null");
1599 if (symbol->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001600 Oddball::cast(null_value())->set_to_string(String::cast(symbol));
1601 Oddball::cast(null_value())->set_to_number(Smi::FromInt(0));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001602
1603 // Allocate the null_value
1604 obj = Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
1605 if (obj->IsFailure()) return false;
1606
1607 obj = CreateOddball(oddball_map(), "true", Smi::FromInt(1));
1608 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001609 set_true_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001610
1611 obj = CreateOddball(oddball_map(), "false", Smi::FromInt(0));
1612 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001613 set_false_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001614
1615 obj = CreateOddball(oddball_map(), "hole", Smi::FromInt(-1));
1616 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001617 set_the_hole_value(obj);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001619 obj = CreateOddball(
1620 oddball_map(), "no_interceptor_result_sentinel", Smi::FromInt(-2));
1621 if (obj->IsFailure()) return false;
1622 set_no_interceptor_result_sentinel(obj);
1623
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001624 obj = CreateOddball(oddball_map(), "termination_exception", Smi::FromInt(-3));
1625 if (obj->IsFailure()) return false;
1626 set_termination_exception(obj);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001627
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628 // Allocate the empty string.
1629 obj = AllocateRawAsciiString(0, TENURED);
1630 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001631 set_empty_string(String::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001632
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001633 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
1634 obj = LookupAsciiSymbol(constant_symbol_table[i].contents);
1635 if (obj->IsFailure()) return false;
1636 roots_[constant_symbol_table[i].index] = String::cast(obj);
1637 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001638
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001639 // Allocate the hidden symbol which is used to identify the hidden properties
1640 // in JSObjects. The hash code has a special value so that it will not match
1641 // the empty string when searching for the property. It cannot be part of the
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001642 // loop above because it needs to be allocated manually with the special
ager@chromium.org3b45ab52009-03-19 22:21:34 +00001643 // hash code in place. The hash code for the hidden_symbol is zero to ensure
1644 // that it will always be at the first entry in property descriptors.
1645 obj = AllocateSymbol(CStrVector(""), 0, String::kHashComputedMask);
1646 if (obj->IsFailure()) return false;
1647 hidden_symbol_ = String::cast(obj);
1648
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001649 // Allocate the proxy for __proto__.
1650 obj = AllocateProxy((Address) &Accessors::ObjectPrototype);
1651 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001652 set_prototype_accessors(Proxy::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001653
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001654 // Allocate the code_stubs dictionary. The initial size is set to avoid
1655 // expanding the dictionary during bootstrapping.
1656 obj = NumberDictionary::Allocate(128);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001658 set_code_stubs(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001659
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001660 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
1661 // is set to avoid expanding the dictionary during bootstrapping.
1662 obj = NumberDictionary::Allocate(64);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001663 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001664 set_non_monomorphic_cache(NumberDictionary::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665
1666 CreateFixedStubs();
1667
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001668 if (InitializeNumberStringCache()->IsFailure()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001669
1670 // Allocate cache for single character strings.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001671 obj = AllocateFixedArray(String::kMaxAsciiCharCode+1, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001672 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001673 set_single_character_string_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001674
1675 // Allocate cache for external strings pointing to native source code.
1676 obj = AllocateFixedArray(Natives::GetBuiltinsCount());
1677 if (obj->IsFailure()) return false;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001678 set_natives_source_cache(FixedArray::cast(obj));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001679
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001680 // Handling of script id generation is in Factory::NewScript.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001681 set_last_script_id(undefined_value());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001682
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001683 // Initialize keyed lookup cache.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001684 KeyedLookupCache::Clear();
1685
1686 // Initialize context slot cache.
1687 ContextSlotCache::Clear();
1688
1689 // Initialize descriptor cache.
1690 DescriptorLookupCache::Clear();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001691
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00001692 // Initialize compilation cache.
1693 CompilationCache::Clear();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001694
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001695 return true;
1696}
1697
1698
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001699Object* Heap::InitializeNumberStringCache() {
1700 // Compute the size of the number string cache based on the max heap size.
1701 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
1702 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
1703 int number_string_cache_size = max_semispace_size_ / 512;
1704 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001705 Object* obj = AllocateFixedArray(number_string_cache_size * 2, TENURED);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001706 if (!obj->IsFailure()) set_number_string_cache(FixedArray::cast(obj));
1707 return obj;
1708}
1709
1710
1711void Heap::FlushNumberStringCache() {
1712 // Flush the number to string cache.
1713 int len = number_string_cache()->length();
1714 for (int i = 0; i < len; i++) {
1715 number_string_cache()->set_undefined(i);
1716 }
1717}
1718
1719
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001720static inline int double_get_hash(double d) {
1721 DoubleRepresentation rep(d);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001722 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001723}
1724
1725
1726static inline int smi_get_hash(Smi* smi) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001727 return smi->value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001728}
1729
1730
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001731Object* Heap::GetNumberStringCache(Object* number) {
1732 int hash;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001733 int mask = (number_string_cache()->length() >> 1) - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001734 if (number->IsSmi()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001735 hash = smi_get_hash(Smi::cast(number)) & mask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001736 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001737 hash = double_get_hash(number->Number()) & mask;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001738 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001739 Object* key = number_string_cache()->get(hash * 2);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001740 if (key == number) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001741 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001742 } else if (key->IsHeapNumber() &&
1743 number->IsHeapNumber() &&
1744 key->Number() == number->Number()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001745 return String::cast(number_string_cache()->get(hash * 2 + 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001746 }
1747 return undefined_value();
1748}
1749
1750
1751void Heap::SetNumberStringCache(Object* number, String* string) {
1752 int hash;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001753 int mask = (number_string_cache()->length() >> 1) - 1;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754 if (number->IsSmi()) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001755 hash = smi_get_hash(Smi::cast(number)) & mask;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001756 number_string_cache()->set(hash * 2, Smi::cast(number));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00001758 hash = double_get_hash(number->Number()) & mask;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001759 number_string_cache()->set(hash * 2, number);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001760 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001761 number_string_cache()->set(hash * 2 + 1, string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001762}
1763
1764
1765Object* Heap::SmiOrNumberFromDouble(double value,
1766 bool new_object,
1767 PretenureFlag pretenure) {
1768 // We need to distinguish the minus zero value and this cannot be
1769 // done after conversion to int. Doing this by comparing bit
1770 // patterns is faster than using fpclassify() et al.
1771 static const DoubleRepresentation plus_zero(0.0);
1772 static const DoubleRepresentation minus_zero(-0.0);
1773 static const DoubleRepresentation nan(OS::nan_value());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001774 ASSERT(minus_zero_value() != NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001775 ASSERT(sizeof(plus_zero.value) == sizeof(plus_zero.bits));
1776
1777 DoubleRepresentation rep(value);
1778 if (rep.bits == plus_zero.bits) return Smi::FromInt(0); // not uncommon
1779 if (rep.bits == minus_zero.bits) {
1780 return new_object ? AllocateHeapNumber(-0.0, pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001781 : minus_zero_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782 }
1783 if (rep.bits == nan.bits) {
1784 return new_object
1785 ? AllocateHeapNumber(OS::nan_value(), pretenure)
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001786 : nan_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001787 }
1788
1789 // Try to represent the value as a tagged small integer.
1790 int int_value = FastD2I(value);
1791 if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
1792 return Smi::FromInt(int_value);
1793 }
1794
1795 // Materialize the value in the heap.
1796 return AllocateHeapNumber(value, pretenure);
1797}
1798
1799
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001800Object* Heap::NumberToString(Object* number) {
ager@chromium.org5c838252010-02-19 08:53:10 +00001801 Counters::number_to_string_runtime.Increment();
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00001802 Object* cached = GetNumberStringCache(number);
1803 if (cached != undefined_value()) {
1804 return cached;
1805 }
1806
1807 char arr[100];
1808 Vector<char> buffer(arr, ARRAY_SIZE(arr));
1809 const char* str;
1810 if (number->IsSmi()) {
1811 int num = Smi::cast(number)->value();
1812 str = IntToCString(num, buffer);
1813 } else {
1814 double num = HeapNumber::cast(number)->value();
1815 str = DoubleToCString(num, buffer);
1816 }
1817 Object* result = AllocateStringFromAscii(CStrVector(str));
1818
1819 if (!result->IsFailure()) {
1820 SetNumberStringCache(number, String::cast(result));
1821 }
1822 return result;
1823}
1824
1825
ager@chromium.org3811b432009-10-28 14:53:37 +00001826Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
1827 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
1828}
1829
1830
1831Heap::RootListIndex Heap::RootIndexForExternalArrayType(
1832 ExternalArrayType array_type) {
1833 switch (array_type) {
1834 case kExternalByteArray:
1835 return kExternalByteArrayMapRootIndex;
1836 case kExternalUnsignedByteArray:
1837 return kExternalUnsignedByteArrayMapRootIndex;
1838 case kExternalShortArray:
1839 return kExternalShortArrayMapRootIndex;
1840 case kExternalUnsignedShortArray:
1841 return kExternalUnsignedShortArrayMapRootIndex;
1842 case kExternalIntArray:
1843 return kExternalIntArrayMapRootIndex;
1844 case kExternalUnsignedIntArray:
1845 return kExternalUnsignedIntArrayMapRootIndex;
1846 case kExternalFloatArray:
1847 return kExternalFloatArrayMapRootIndex;
1848 default:
1849 UNREACHABLE();
1850 return kUndefinedValueRootIndex;
1851 }
1852}
1853
1854
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001855Object* Heap::NewNumberFromDouble(double value, PretenureFlag pretenure) {
1856 return SmiOrNumberFromDouble(value,
1857 true /* number object must be new */,
1858 pretenure);
1859}
1860
1861
1862Object* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
1863 return SmiOrNumberFromDouble(value,
1864 false /* use preallocated NaN, -0.0 */,
1865 pretenure);
1866}
1867
1868
1869Object* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
1870 // Statically ensure that it is safe to allocate proxies in paged spaces.
1871 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001872 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001873 Object* result = Allocate(proxy_map(), space);
1874 if (result->IsFailure()) return result;
1875
1876 Proxy::cast(result)->set_proxy(proxy);
1877 return result;
1878}
1879
1880
1881Object* Heap::AllocateSharedFunctionInfo(Object* name) {
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00001882 Object* result = Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001883 if (result->IsFailure()) return result;
1884
1885 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
1886 share->set_name(name);
1887 Code* illegal = Builtins::builtin(Builtins::Illegal);
1888 share->set_code(illegal);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00001889 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
1890 share->set_construct_stub(construct_stub);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001891 share->set_expected_nof_properties(0);
1892 share->set_length(0);
1893 share->set_formal_parameter_count(0);
1894 share->set_instance_class_name(Object_symbol());
1895 share->set_function_data(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001896 share->set_script(undefined_value());
1897 share->set_start_position_and_type(0);
1898 share->set_debug_info(undefined_value());
kasperl@chromium.orgd1e3e722009-04-14 13:38:25 +00001899 share->set_inferred_name(empty_string());
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001900 share->set_compiler_hints(0);
1901 share->set_this_property_assignments_count(0);
1902 share->set_this_property_assignments(undefined_value());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001903 return result;
1904}
1905
1906
ager@chromium.org6141cbe2009-11-20 12:14:52 +00001907// Returns true for a character in a range. Both limits are inclusive.
1908static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
1909 // This makes uses of the the unsigned wraparound.
1910 return character - from <= to - from;
1911}
1912
1913
1914static inline Object* MakeOrFindTwoCharacterString(uint32_t c1, uint32_t c2) {
1915 String* symbol;
1916 // Numeric strings have a different hash algorithm not known by
1917 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
1918 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
1919 Heap::symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
1920 return symbol;
1921 // Now we know the length is 2, we might as well make use of that fact
1922 // when building the new string.
1923 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
1924 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
1925 Object* result = Heap::AllocateRawAsciiString(2);
1926 if (result->IsFailure()) return result;
1927 char* dest = SeqAsciiString::cast(result)->GetChars();
1928 dest[0] = c1;
1929 dest[1] = c2;
1930 return result;
1931 } else {
1932 Object* result = Heap::AllocateRawTwoByteString(2);
1933 if (result->IsFailure()) return result;
1934 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
1935 dest[0] = c1;
1936 dest[1] = c2;
1937 return result;
1938 }
1939}
1940
1941
ager@chromium.org3e875802009-06-29 08:26:34 +00001942Object* Heap::AllocateConsString(String* first, String* second) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001943 int first_length = first->length();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001944 if (first_length == 0) {
1945 return second;
1946 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001947
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001948 int second_length = second->length();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001949 if (second_length == 0) {
1950 return first;
1951 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001952
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001953 int length = first_length + second_length;
ager@chromium.org6141cbe2009-11-20 12:14:52 +00001954
1955 // Optimization for 2-byte strings often used as keys in a decompression
1956 // dictionary. Check whether we already have the string in the symbol
1957 // table to prevent creation of many unneccesary strings.
1958 if (length == 2) {
1959 unsigned c1 = first->Get(0);
1960 unsigned c2 = second->Get(0);
1961 return MakeOrFindTwoCharacterString(c1, c2);
1962 }
1963
ager@chromium.org5ec48922009-05-05 07:25:34 +00001964 bool is_ascii = first->IsAsciiRepresentation()
1965 && second->IsAsciiRepresentation();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001966
ager@chromium.org3e875802009-06-29 08:26:34 +00001967 // Make sure that an out of memory exception is thrown if the length
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001968 // of the new cons string is too large.
1969 if (length > String::kMaxLength || length < 0) {
ager@chromium.org3e875802009-06-29 08:26:34 +00001970 Top::context()->mark_out_of_memory();
1971 return Failure::OutOfMemoryException();
1972 }
1973
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001974 // If the resulting string is small make a flat string.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001975 if (length < String::kMinNonFlatLength) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001976 ASSERT(first->IsFlat());
1977 ASSERT(second->IsFlat());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001978 if (is_ascii) {
1979 Object* result = AllocateRawAsciiString(length);
1980 if (result->IsFailure()) return result;
1981 // Copy the characters into the new object.
1982 char* dest = SeqAsciiString::cast(result)->GetChars();
ager@chromium.org3e875802009-06-29 08:26:34 +00001983 // Copy first part.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001984 const char* src;
1985 if (first->IsExternalString()) {
1986 src = ExternalAsciiString::cast(first)->resource()->data();
1987 } else {
1988 src = SeqAsciiString::cast(first)->GetChars();
1989 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001990 for (int i = 0; i < first_length; i++) *dest++ = src[i];
1991 // Copy second part.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00001992 if (second->IsExternalString()) {
1993 src = ExternalAsciiString::cast(second)->resource()->data();
1994 } else {
1995 src = SeqAsciiString::cast(second)->GetChars();
1996 }
ager@chromium.org3e875802009-06-29 08:26:34 +00001997 for (int i = 0; i < second_length; i++) *dest++ = src[i];
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001998 return result;
1999 } else {
2000 Object* result = AllocateRawTwoByteString(length);
2001 if (result->IsFailure()) return result;
2002 // Copy the characters into the new object.
2003 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002004 String::WriteToFlat(first, dest, 0, first_length);
2005 String::WriteToFlat(second, dest + first_length, 0, second_length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002006 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002007 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002008 }
2009
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002010 Map* map = is_ascii ? cons_ascii_string_map() : cons_string_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002011
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002012 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002013 if (result->IsFailure()) return result;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002014
2015 AssertNoAllocation no_gc;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002016 ConsString* cons_string = ConsString::cast(result);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002017 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002018 cons_string->set_length(length);
2019 cons_string->set_hash_field(String::kEmptyHashField);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002020 cons_string->set_first(first, mode);
2021 cons_string->set_second(second, mode);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002022 return result;
2023}
2024
2025
ager@chromium.org870a0b62008-11-04 11:43:05 +00002026Object* Heap::AllocateSubString(String* buffer,
ager@chromium.org870a0b62008-11-04 11:43:05 +00002027 int start,
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002028 int end,
2029 PretenureFlag pretenure) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002030 int length = end - start;
2031
ager@chromium.org7c537e22008-10-16 08:43:32 +00002032 if (length == 1) {
ager@chromium.org870a0b62008-11-04 11:43:05 +00002033 return Heap::LookupSingleCharacterStringFromCode(
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002034 buffer->Get(start));
ager@chromium.org6141cbe2009-11-20 12:14:52 +00002035 } else if (length == 2) {
2036 // Optimization for 2-byte strings often used as keys in a decompression
2037 // dictionary. Check whether we already have the string in the symbol
2038 // table to prevent creation of many unneccesary strings.
2039 unsigned c1 = buffer->Get(start);
2040 unsigned c2 = buffer->Get(start + 1);
2041 return MakeOrFindTwoCharacterString(c1, c2);
ager@chromium.org7c537e22008-10-16 08:43:32 +00002042 }
2043
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002044 // Make an attempt to flatten the buffer to reduce access time.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002045 buffer->TryFlatten();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002046
ager@chromium.org5ec48922009-05-05 07:25:34 +00002047 Object* result = buffer->IsAsciiRepresentation()
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002048 ? AllocateRawAsciiString(length, pretenure )
2049 : AllocateRawTwoByteString(length, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002050 if (result->IsFailure()) return result;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002051 String* string_result = String::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002052 // Copy the characters into the new object.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002053 if (buffer->IsAsciiRepresentation()) {
2054 ASSERT(string_result->IsAsciiRepresentation());
2055 char* dest = SeqAsciiString::cast(string_result)->GetChars();
2056 String::WriteToFlat(buffer, dest, start, end);
2057 } else {
2058 ASSERT(string_result->IsTwoByteRepresentation());
2059 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
2060 String::WriteToFlat(buffer, dest, start, end);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002061 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002062
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002063 return result;
2064}
2065
2066
2067Object* Heap::AllocateExternalStringFromAscii(
2068 ExternalAsciiString::Resource* resource) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002069 size_t length = resource->length();
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002070 if (length > static_cast<size_t>(String::kMaxLength)) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002071 Top::context()->mark_out_of_memory();
2072 return Failure::OutOfMemoryException();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002073 }
2074
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002075 Map* map = external_ascii_string_map();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002076 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002077 if (result->IsFailure()) return result;
2078
2079 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002080 external_string->set_length(static_cast<int>(length));
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002081 external_string->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002082 external_string->set_resource(resource);
2083
2084 return result;
2085}
2086
2087
2088Object* Heap::AllocateExternalStringFromTwoByte(
2089 ExternalTwoByteString::Resource* resource) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002090 size_t length = resource->length();
2091 if (length > static_cast<size_t>(String::kMaxLength)) {
2092 Top::context()->mark_out_of_memory();
2093 return Failure::OutOfMemoryException();
2094 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002095
2096 Map* map = Heap::external_string_map();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002097 Object* result = Allocate(map, NEW_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002098 if (result->IsFailure()) return result;
2099
2100 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002101 external_string->set_length(static_cast<int>(length));
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002102 external_string->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002103 external_string->set_resource(resource);
2104
2105 return result;
2106}
2107
2108
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002109Object* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002110 if (code <= String::kMaxAsciiCharCode) {
2111 Object* value = Heap::single_character_string_cache()->get(code);
2112 if (value != Heap::undefined_value()) return value;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002113
2114 char buffer[1];
2115 buffer[0] = static_cast<char>(code);
2116 Object* result = LookupSymbol(Vector<const char>(buffer, 1));
2117
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002118 if (result->IsFailure()) return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002119 Heap::single_character_string_cache()->set(code, result);
2120 return result;
2121 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002122
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002123 Object* result = Heap::AllocateRawTwoByteString(1);
2124 if (result->IsFailure()) return result;
ager@chromium.org870a0b62008-11-04 11:43:05 +00002125 String* answer = String::cast(result);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002126 answer->Set(0, code);
ager@chromium.org870a0b62008-11-04 11:43:05 +00002127 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002128}
2129
2130
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002131Object* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002132 if (length < 0 || length > ByteArray::kMaxLength) {
2133 return Failure::OutOfMemoryException();
2134 }
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002135 if (pretenure == NOT_TENURED) {
2136 return AllocateByteArray(length);
2137 }
2138 int size = ByteArray::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002139 Object* result = (size <= MaxObjectSizeInPagedSpace())
2140 ? old_data_space_->AllocateRaw(size)
2141 : lo_space_->AllocateRaw(size);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002142 if (result->IsFailure()) return result;
2143
2144 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2145 reinterpret_cast<Array*>(result)->set_length(length);
2146 return result;
2147}
2148
2149
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002150Object* Heap::AllocateByteArray(int length) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002151 if (length < 0 || length > ByteArray::kMaxLength) {
2152 return Failure::OutOfMemoryException();
2153 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002154 int size = ByteArray::SizeFor(length);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002155 AllocationSpace space =
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002156 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : NEW_SPACE;
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002157 Object* result = AllocateRaw(size, space, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002158 if (result->IsFailure()) return result;
2159
2160 reinterpret_cast<Array*>(result)->set_map(byte_array_map());
2161 reinterpret_cast<Array*>(result)->set_length(length);
2162 return result;
2163}
2164
2165
ager@chromium.org6f10e412009-02-13 10:11:16 +00002166void Heap::CreateFillerObjectAt(Address addr, int size) {
2167 if (size == 0) return;
2168 HeapObject* filler = HeapObject::FromAddress(addr);
2169 if (size == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002170 filler->set_map(Heap::one_pointer_filler_map());
ager@chromium.org6f10e412009-02-13 10:11:16 +00002171 } else {
2172 filler->set_map(Heap::byte_array_map());
2173 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2174 }
2175}
2176
2177
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002178Object* Heap::AllocatePixelArray(int length,
2179 uint8_t* external_pointer,
2180 PretenureFlag pretenure) {
2181 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002182 Object* result = AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002183 if (result->IsFailure()) return result;
2184
2185 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
2186 reinterpret_cast<PixelArray*>(result)->set_length(length);
2187 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
2188
2189 return result;
2190}
2191
2192
ager@chromium.org3811b432009-10-28 14:53:37 +00002193Object* Heap::AllocateExternalArray(int length,
2194 ExternalArrayType array_type,
2195 void* external_pointer,
2196 PretenureFlag pretenure) {
2197 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
ager@chromium.org3811b432009-10-28 14:53:37 +00002198 Object* result = AllocateRaw(ExternalArray::kAlignedSize,
2199 space,
2200 OLD_DATA_SPACE);
ager@chromium.org3811b432009-10-28 14:53:37 +00002201 if (result->IsFailure()) return result;
2202
2203 reinterpret_cast<ExternalArray*>(result)->set_map(
2204 MapForExternalArrayType(array_type));
2205 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2206 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2207 external_pointer);
2208
2209 return result;
2210}
2211
2212
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002213Object* Heap::CreateCode(const CodeDesc& desc,
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002214 ZoneScopeInfo* sinfo,
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002215 Code::Flags flags,
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002216 Handle<Object> self_reference) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002217 // Compute size
2218 int body_size = RoundUp(desc.instr_size + desc.reloc_size, kObjectAlignment);
2219 int sinfo_size = 0;
2220 if (sinfo != NULL) sinfo_size = sinfo->Serialize(NULL);
2221 int obj_size = Code::SizeFor(body_size, sinfo_size);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002222 ASSERT(IsAligned(obj_size, Code::kCodeAlignment));
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002223 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002224 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002225 result = lo_space_->AllocateRawCode(obj_size);
2226 } else {
2227 result = code_space_->AllocateRaw(obj_size);
2228 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002229
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002230 if (result->IsFailure()) return result;
2231
2232 // Initialize the object
2233 HeapObject::cast(result)->set_map(code_map());
2234 Code* code = Code::cast(result);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002235 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002236 code->set_instruction_size(desc.instr_size);
2237 code->set_relocation_size(desc.reloc_size);
2238 code->set_sinfo_size(sinfo_size);
2239 code->set_flags(flags);
kasperl@chromium.org061ef742009-02-27 12:16:20 +00002240 // Allow self references to created code object by patching the handle to
2241 // point to the newly allocated Code object.
2242 if (!self_reference.is_null()) {
2243 *(self_reference.location()) = code;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002244 }
2245 // Migrate generated code.
2246 // The generated code can contain Object** values (typically from handles)
2247 // that are dereferenced during the copy to point directly to the actual heap
2248 // objects. These pointers can include references to the code object itself,
2249 // through the self_reference parameter.
2250 code->CopyFrom(desc);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002251 if (sinfo != NULL) sinfo->Serialize(code); // write scope info
2252
2253#ifdef DEBUG
2254 code->Verify();
2255#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002256 return code;
2257}
2258
2259
2260Object* Heap::CopyCode(Code* code) {
2261 // Allocate an object the same size as the code object.
2262 int obj_size = code->Size();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002263 Object* result;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002264 if (obj_size > MaxObjectSizeInPagedSpace()) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002265 result = lo_space_->AllocateRawCode(obj_size);
2266 } else {
2267 result = code_space_->AllocateRaw(obj_size);
2268 }
2269
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002270 if (result->IsFailure()) return result;
2271
2272 // Copy code object.
2273 Address old_addr = code->address();
2274 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002275 CopyBlock(reinterpret_cast<Object**>(new_addr),
2276 reinterpret_cast<Object**>(old_addr),
2277 obj_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002278 // Relocate the copy.
2279 Code* new_code = Code::cast(result);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002280 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002281 new_code->Relocate(new_addr - old_addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002282 return new_code;
2283}
2284
2285
fschneider@chromium.org086aac62010-03-17 13:18:24 +00002286Object* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
2287 int new_body_size = RoundUp(code->instruction_size() + reloc_info.length(),
2288 kObjectAlignment);
2289
2290 int sinfo_size = code->sinfo_size();
2291
2292 int new_obj_size = Code::SizeFor(new_body_size, sinfo_size);
2293
2294 Address old_addr = code->address();
2295
2296 int relocation_offset = code->relocation_start() - old_addr;
2297
2298 Object* result;
2299 if (new_obj_size > MaxObjectSizeInPagedSpace()) {
2300 result = lo_space_->AllocateRawCode(new_obj_size);
2301 } else {
2302 result = code_space_->AllocateRaw(new_obj_size);
2303 }
2304
2305 if (result->IsFailure()) return result;
2306
2307 // Copy code object.
2308 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
2309
2310 // Copy header and instructions.
2311 memcpy(new_addr, old_addr, relocation_offset);
2312
2313 // Copy patched rinfo.
2314 memcpy(new_addr + relocation_offset,
2315 reloc_info.start(),
2316 reloc_info.length());
2317
2318 Code* new_code = Code::cast(result);
2319 new_code->set_relocation_size(reloc_info.length());
2320
2321 // Copy sinfo.
2322 memcpy(new_code->sinfo_start(), code->sinfo_start(), code->sinfo_size());
2323
2324 // Relocate the copy.
2325 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2326 new_code->Relocate(new_addr - old_addr);
2327
2328#ifdef DEBUG
2329 code->Verify();
2330#endif
2331 return new_code;
2332}
2333
2334
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002335Object* Heap::Allocate(Map* map, AllocationSpace space) {
2336 ASSERT(gc_state_ == NOT_IN_GC);
2337 ASSERT(map->instance_type() != MAP_TYPE);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002338 // If allocation failures are disallowed, we may allocate in a different
2339 // space when new space is full and the object is not a large object.
2340 AllocationSpace retry_space =
2341 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
2342 Object* result =
2343 AllocateRaw(map->instance_size(), space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002344 if (result->IsFailure()) return result;
2345 HeapObject::cast(result)->set_map(map);
ager@chromium.org3811b432009-10-28 14:53:37 +00002346#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002347 ProducerHeapProfile::RecordJSObjectAllocation(result);
ager@chromium.org3811b432009-10-28 14:53:37 +00002348#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002349 return result;
2350}
2351
2352
2353Object* Heap::InitializeFunction(JSFunction* function,
2354 SharedFunctionInfo* shared,
2355 Object* prototype) {
2356 ASSERT(!prototype->IsMap());
2357 function->initialize_properties();
2358 function->initialize_elements();
2359 function->set_shared(shared);
2360 function->set_prototype_or_initial_map(prototype);
2361 function->set_context(undefined_value());
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002362 function->set_literals(empty_fixed_array());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002363 return function;
2364}
2365
2366
2367Object* Heap::AllocateFunctionPrototype(JSFunction* function) {
ager@chromium.orgddb913d2009-01-27 10:01:48 +00002368 // Allocate the prototype. Make sure to use the object function
2369 // from the function's context, since the function can be from a
2370 // different context.
2371 JSFunction* object_function =
2372 function->context()->global_context()->object_function();
2373 Object* prototype = AllocateJSObject(object_function);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002374 if (prototype->IsFailure()) return prototype;
2375 // When creating the prototype for the function we must set its
2376 // constructor to the function.
2377 Object* result =
2378 JSObject::cast(prototype)->SetProperty(constructor_symbol(),
2379 function,
2380 DONT_ENUM);
2381 if (result->IsFailure()) return result;
2382 return prototype;
2383}
2384
2385
2386Object* Heap::AllocateFunction(Map* function_map,
2387 SharedFunctionInfo* shared,
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002388 Object* prototype,
2389 PretenureFlag pretenure) {
2390 AllocationSpace space =
2391 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
2392 Object* result = Allocate(function_map, space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002393 if (result->IsFailure()) return result;
2394 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2395}
2396
2397
2398Object* Heap::AllocateArgumentsObject(Object* callee, int length) {
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002399 // To get fast allocation and map sharing for arguments objects we
2400 // allocate them based on an arguments boilerplate.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002401
2402 // This calls Copy directly rather than using Heap::AllocateRaw so we
2403 // duplicate the check here.
2404 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2405
2406 JSObject* boilerplate =
2407 Top::context()->global_context()->arguments_boilerplate();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002408
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002409 // Check that the size of the boilerplate matches our
2410 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
2411 // on the size being a known constant.
2412 ASSERT(kArgumentsObjectSize == boilerplate->map()->instance_size());
2413
2414 // Do the allocation.
2415 Object* result =
2416 AllocateRaw(kArgumentsObjectSize, NEW_SPACE, OLD_POINTER_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002417 if (result->IsFailure()) return result;
2418
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002419 // Copy the content. The arguments boilerplate doesn't have any
2420 // fields that point to new space so it's safe to skip the write
2421 // barrier here.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002422 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(result)->address()),
2423 reinterpret_cast<Object**>(boilerplate->address()),
sgjesse@chromium.org846fb742009-12-18 08:56:33 +00002424 kArgumentsObjectSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002425
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002426 // Set the two properties.
2427 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002428 callee);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002429 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2430 Smi::FromInt(length),
2431 SKIP_WRITE_BARRIER);
2432
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002433 // Check the state of the object
2434 ASSERT(JSObject::cast(result)->HasFastProperties());
2435 ASSERT(JSObject::cast(result)->HasFastElements());
2436
2437 return result;
2438}
2439
2440
2441Object* Heap::AllocateInitialMap(JSFunction* fun) {
2442 ASSERT(!fun->has_initial_map());
2443
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002444 // First create a new map with the size and number of in-object properties
2445 // suggested by the function.
2446 int instance_size = fun->shared()->CalculateInstanceSize();
2447 int in_object_properties = fun->shared()->CalculateInObjectProperties();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002448 Object* map_obj = Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002449 if (map_obj->IsFailure()) return map_obj;
2450
2451 // Fetch or allocate prototype.
2452 Object* prototype;
2453 if (fun->has_instance_prototype()) {
2454 prototype = fun->instance_prototype();
2455 } else {
2456 prototype = AllocateFunctionPrototype(fun);
2457 if (prototype->IsFailure()) return prototype;
2458 }
2459 Map* map = Map::cast(map_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002460 map->set_inobject_properties(in_object_properties);
2461 map->set_unused_property_fields(in_object_properties);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002462 map->set_prototype(prototype);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002463
ager@chromium.org5c838252010-02-19 08:53:10 +00002464 // If the function has only simple this property assignments add
2465 // field descriptors for these to the initial map as the object
2466 // cannot be constructed without having these properties. Guard by
2467 // the inline_new flag so we only change the map if we generate a
2468 // specialized construct stub.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002469 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
ager@chromium.org5c838252010-02-19 08:53:10 +00002470 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002471 int count = fun->shared()->this_property_assignments_count();
2472 if (count > in_object_properties) {
2473 count = in_object_properties;
2474 }
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00002475 Object* descriptors_obj = DescriptorArray::Allocate(count);
2476 if (descriptors_obj->IsFailure()) return descriptors_obj;
2477 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002478 for (int i = 0; i < count; i++) {
2479 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
2480 ASSERT(name->IsSymbol());
2481 FieldDescriptor field(name, i, NONE);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002482 field.SetEnumerationIndex(i);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002483 descriptors->Set(i, &field);
2484 }
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002485 descriptors->SetNextEnumerationIndex(count);
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002486 descriptors->Sort();
2487 map->set_instance_descriptors(descriptors);
2488 map->set_pre_allocated_property_fields(count);
2489 map->set_unused_property_fields(in_object_properties - count);
2490 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002491 return map;
2492}
2493
2494
2495void Heap::InitializeJSObjectFromMap(JSObject* obj,
2496 FixedArray* properties,
2497 Map* map) {
2498 obj->set_properties(properties);
2499 obj->initialize_elements();
2500 // TODO(1240798): Initialize the object's body using valid initial values
2501 // according to the object's initial map. For example, if the map's
2502 // instance type is JS_ARRAY_TYPE, the length field should be initialized
2503 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
2504 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
2505 // verification code has to cope with (temporarily) invalid objects. See
2506 // for example, JSArray::JSArrayVerify).
2507 obj->InitializeBody(map->instance_size());
2508}
2509
2510
2511Object* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
2512 // JSFunctions should be allocated using AllocateFunction to be
2513 // properly initialized.
2514 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
2515
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002516 // Both types of globla objects should be allocated using
2517 // AllocateGloblaObject to be properly initialized.
2518 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
2519 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
2520
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002521 // Allocate the backing storage for the properties.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002522 int prop_size =
2523 map->pre_allocated_property_fields() +
2524 map->unused_property_fields() -
2525 map->inobject_properties();
2526 ASSERT(prop_size >= 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002527 Object* properties = AllocateFixedArray(prop_size, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002528 if (properties->IsFailure()) return properties;
2529
2530 // Allocate the JSObject.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002531 AllocationSpace space =
2532 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002533 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002534 Object* obj = Allocate(map, space);
2535 if (obj->IsFailure()) return obj;
2536
2537 // Initialize the JSObject.
2538 InitializeJSObjectFromMap(JSObject::cast(obj),
2539 FixedArray::cast(properties),
2540 map);
2541 return obj;
2542}
2543
2544
2545Object* Heap::AllocateJSObject(JSFunction* constructor,
2546 PretenureFlag pretenure) {
2547 // Allocate the initial map if absent.
2548 if (!constructor->has_initial_map()) {
2549 Object* initial_map = AllocateInitialMap(constructor);
2550 if (initial_map->IsFailure()) return initial_map;
2551 constructor->set_initial_map(Map::cast(initial_map));
2552 Map::cast(initial_map)->set_constructor(constructor);
2553 }
2554 // Allocate the object based on the constructors initial map.
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002555 Object* result =
2556 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
2557 // Make sure result is NOT a global object if valid.
2558 ASSERT(result->IsFailure() || !result->IsGlobalObject());
2559 return result;
2560}
2561
2562
2563Object* Heap::AllocateGlobalObject(JSFunction* constructor) {
2564 ASSERT(constructor->has_initial_map());
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002565 Map* map = constructor->initial_map();
2566
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002567 // Make sure no field properties are described in the initial map.
2568 // This guarantees us that normalizing the properties does not
2569 // require us to change property values to JSGlobalPropertyCells.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002570 ASSERT(map->NextFreePropertyIndex() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002571
2572 // Make sure we don't have a ton of pre-allocated slots in the
2573 // global objects. They will be unused once we normalize the object.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002574 ASSERT(map->unused_property_fields() == 0);
2575 ASSERT(map->inobject_properties() == 0);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002576
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002577 // Initial size of the backing store to avoid resize of the storage during
2578 // bootstrapping. The size differs between the JS global object ad the
2579 // builtins object.
2580 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002581
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00002582 // Allocate a dictionary object for backing storage.
2583 Object* obj =
2584 StringDictionary::Allocate(
2585 map->NumberOfDescribedProperties() * 2 + initial_size);
2586 if (obj->IsFailure()) return obj;
2587 StringDictionary* dictionary = StringDictionary::cast(obj);
2588
2589 // The global object might be created from an object template with accessors.
2590 // Fill these accessors into the dictionary.
2591 DescriptorArray* descs = map->instance_descriptors();
2592 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2593 PropertyDetails details = descs->GetDetails(i);
2594 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
2595 PropertyDetails d =
2596 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2597 Object* value = descs->GetCallbacksObject(i);
2598 value = Heap::AllocateJSGlobalPropertyCell(value);
2599 if (value->IsFailure()) return value;
2600
2601 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2602 if (result->IsFailure()) return result;
2603 dictionary = StringDictionary::cast(result);
2604 }
2605
2606 // Allocate the global object and initialize it with the backing store.
2607 obj = Allocate(map, OLD_POINTER_SPACE);
2608 if (obj->IsFailure()) return obj;
2609 JSObject* global = JSObject::cast(obj);
2610 InitializeJSObjectFromMap(global, dictionary, map);
2611
2612 // Create a new map for the global object.
2613 obj = map->CopyDropDescriptors();
2614 if (obj->IsFailure()) return obj;
2615 Map* new_map = Map::cast(obj);
2616
2617 // Setup the global object as a normalized object.
2618 global->set_map(new_map);
2619 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
2620 global->set_properties(dictionary);
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002621
2622 // Make sure result is a global object with properties in dictionary.
2623 ASSERT(global->IsGlobalObject());
2624 ASSERT(!global->HasFastProperties());
2625 return global;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002626}
2627
2628
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002629Object* Heap::CopyJSObject(JSObject* source) {
2630 // Never used to copy functions. If functions need to be copied we
2631 // have to be careful to clear the literals array.
2632 ASSERT(!source->IsJSFunction());
2633
2634 // Make the clone.
2635 Map* map = source->map();
2636 int object_size = map->instance_size();
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002637 Object* clone;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002638
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002639 // If we're forced to always allocate, we use the general allocation
2640 // functions which may leave us with an object in old space.
2641 if (always_allocate()) {
2642 clone = AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
2643 if (clone->IsFailure()) return clone;
2644 Address clone_address = HeapObject::cast(clone)->address();
2645 CopyBlock(reinterpret_cast<Object**>(clone_address),
2646 reinterpret_cast<Object**>(source->address()),
2647 object_size);
2648 // Update write barrier for all fields that lie beyond the header.
vegorov@chromium.orgf8372902010-03-15 10:26:20 +00002649 RecordWrites(clone_address,
2650 JSObject::kHeaderSize,
antonm@chromium.org8e5e3382010-03-24 09:56:30 +00002651 (object_size - JSObject::kHeaderSize) / kPointerSize);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002652 } else {
2653 clone = new_space_.AllocateRaw(object_size);
2654 if (clone->IsFailure()) return clone;
2655 ASSERT(Heap::InNewSpace(clone));
2656 // Since we know the clone is allocated in new space, we can copy
ager@chromium.org32912102009-01-16 10:38:43 +00002657 // the contents without worrying about updating the write barrier.
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002658 CopyBlock(reinterpret_cast<Object**>(HeapObject::cast(clone)->address()),
2659 reinterpret_cast<Object**>(source->address()),
2660 object_size);
2661 }
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002662
2663 FixedArray* elements = FixedArray::cast(source->elements());
2664 FixedArray* properties = FixedArray::cast(source->properties());
2665 // Update elements if necessary.
ager@chromium.orgb26c50a2010-03-26 09:27:16 +00002666 if (elements->length() > 0) {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002667 Object* elem = CopyFixedArray(elements);
2668 if (elem->IsFailure()) return elem;
2669 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
2670 }
2671 // Update properties if necessary.
2672 if (properties->length() > 0) {
2673 Object* prop = CopyFixedArray(properties);
2674 if (prop->IsFailure()) return prop;
2675 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
2676 }
2677 // Return the new clone.
ager@chromium.org3811b432009-10-28 14:53:37 +00002678#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002679 ProducerHeapProfile::RecordJSObjectAllocation(clone);
ager@chromium.org3811b432009-10-28 14:53:37 +00002680#endif
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002681 return clone;
2682}
2683
2684
2685Object* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
2686 JSGlobalProxy* object) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002687 // Allocate initial map if absent.
2688 if (!constructor->has_initial_map()) {
2689 Object* initial_map = AllocateInitialMap(constructor);
2690 if (initial_map->IsFailure()) return initial_map;
2691 constructor->set_initial_map(Map::cast(initial_map));
2692 Map::cast(initial_map)->set_constructor(constructor);
2693 }
2694
2695 Map* map = constructor->initial_map();
2696
2697 // Check that the already allocated object has the same size as
2698 // objects allocated using the constructor.
2699 ASSERT(map->instance_size() == object->map()->instance_size());
2700
2701 // Allocate the backing storage for the properties.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002702 int prop_size = map->unused_property_fields() - map->inobject_properties();
kasperl@chromium.org2abc4502009-07-02 07:00:29 +00002703 Object* properties = AllocateFixedArray(prop_size, TENURED);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002704 if (properties->IsFailure()) return properties;
2705
2706 // Reset the map for the object.
2707 object->set_map(constructor->initial_map());
2708
2709 // Reinitialize the object from the constructor map.
2710 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
2711 return object;
2712}
2713
2714
2715Object* Heap::AllocateStringFromAscii(Vector<const char> string,
2716 PretenureFlag pretenure) {
2717 Object* result = AllocateRawAsciiString(string.length(), pretenure);
2718 if (result->IsFailure()) return result;
2719
2720 // Copy the characters into the new object.
ager@chromium.org7c537e22008-10-16 08:43:32 +00002721 SeqAsciiString* string_result = SeqAsciiString::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002722 for (int i = 0; i < string.length(); i++) {
ager@chromium.org7c537e22008-10-16 08:43:32 +00002723 string_result->SeqAsciiStringSet(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002724 }
2725 return result;
2726}
2727
2728
2729Object* Heap::AllocateStringFromUtf8(Vector<const char> string,
2730 PretenureFlag pretenure) {
2731 // Count the number of characters in the UTF-8 string and check if
2732 // it is an ASCII string.
2733 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
2734 decoder->Reset(string.start(), string.length());
2735 int chars = 0;
2736 bool is_ascii = true;
2737 while (decoder->has_more()) {
2738 uc32 r = decoder->GetNext();
2739 if (r > String::kMaxAsciiCharCode) is_ascii = false;
2740 chars++;
2741 }
2742
2743 // If the string is ascii, we do not need to convert the characters
2744 // since UTF8 is backwards compatible with ascii.
2745 if (is_ascii) return AllocateStringFromAscii(string, pretenure);
2746
2747 Object* result = AllocateRawTwoByteString(chars, pretenure);
2748 if (result->IsFailure()) return result;
2749
2750 // Convert and copy the characters into the new object.
2751 String* string_result = String::cast(result);
2752 decoder->Reset(string.start(), string.length());
2753 for (int i = 0; i < chars; i++) {
2754 uc32 r = decoder->GetNext();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002755 string_result->Set(i, r);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002756 }
2757 return result;
2758}
2759
2760
2761Object* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
2762 PretenureFlag pretenure) {
2763 // Check if the string is an ASCII string.
2764 int i = 0;
2765 while (i < string.length() && string[i] <= String::kMaxAsciiCharCode) i++;
2766
2767 Object* result;
2768 if (i == string.length()) { // It's an ASCII string.
2769 result = AllocateRawAsciiString(string.length(), pretenure);
2770 } else { // It's not an ASCII string.
2771 result = AllocateRawTwoByteString(string.length(), pretenure);
2772 }
2773 if (result->IsFailure()) return result;
2774
2775 // Copy the characters into the new object, which may be either ASCII or
2776 // UTF-16.
2777 String* string_result = String::cast(result);
2778 for (int i = 0; i < string.length(); i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002779 string_result->Set(i, string[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002780 }
2781 return result;
2782}
2783
2784
2785Map* Heap::SymbolMapForString(String* string) {
2786 // If the string is in new space it cannot be used as a symbol.
2787 if (InNewSpace(string)) return NULL;
2788
2789 // Find the corresponding symbol map for strings.
2790 Map* map = string->map();
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002791 if (map == ascii_string_map()) return ascii_symbol_map();
2792 if (map == string_map()) return symbol_map();
2793 if (map == cons_string_map()) return cons_symbol_map();
2794 if (map == cons_ascii_string_map()) return cons_ascii_symbol_map();
2795 if (map == external_string_map()) return external_symbol_map();
2796 if (map == external_ascii_string_map()) return external_ascii_symbol_map();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002797
2798 // No match found.
2799 return NULL;
2800}
2801
2802
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002803Object* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
2804 int chars,
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002805 uint32_t hash_field) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002806 ASSERT(chars >= 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002807 // Ensure the chars matches the number of characters in the buffer.
2808 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
2809 // Determine whether the string is ascii.
2810 bool is_ascii = true;
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002811 while (buffer->has_more()) {
2812 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
2813 is_ascii = false;
2814 break;
2815 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002816 }
2817 buffer->Rewind();
2818
2819 // Compute map and object size.
2820 int size;
2821 Map* map;
2822
2823 if (is_ascii) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002824 if (chars > SeqAsciiString::kMaxLength) {
2825 return Failure::OutOfMemoryException();
2826 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002827 map = ascii_symbol_map();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002828 size = SeqAsciiString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002829 } else {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002830 if (chars > SeqTwoByteString::kMaxLength) {
2831 return Failure::OutOfMemoryException();
2832 }
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002833 map = symbol_map();
ager@chromium.org7c537e22008-10-16 08:43:32 +00002834 size = SeqTwoByteString::SizeFor(chars);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002835 }
2836
2837 // Allocate string.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002838 Object* result = (size > MaxObjectSizeInPagedSpace())
2839 ? lo_space_->AllocateRaw(size)
2840 : old_data_space_->AllocateRaw(size);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002841 if (result->IsFailure()) return result;
2842
2843 reinterpret_cast<HeapObject*>(result)->set_map(map);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002844 // Set length and hash fields of the allocated string.
ager@chromium.org870a0b62008-11-04 11:43:05 +00002845 String* answer = String::cast(result);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002846 answer->set_length(chars);
2847 answer->set_hash_field(hash_field);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002848
ager@chromium.org870a0b62008-11-04 11:43:05 +00002849 ASSERT_EQ(size, answer->Size());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002850
2851 // Fill in the characters.
2852 for (int i = 0; i < chars; i++) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002853 answer->Set(i, buffer->GetNext());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002854 }
ager@chromium.org870a0b62008-11-04 11:43:05 +00002855 return answer;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002856}
2857
2858
2859Object* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002860 if (length < 0 || length > SeqAsciiString::kMaxLength) {
2861 return Failure::OutOfMemoryException();
2862 }
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002863
ager@chromium.org7c537e22008-10-16 08:43:32 +00002864 int size = SeqAsciiString::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002865 ASSERT(size <= SeqAsciiString::kMaxSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002866
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002867 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2868 AllocationSpace retry_space = OLD_DATA_SPACE;
2869
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002870 if (space == NEW_SPACE) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002871 if (size > kMaxObjectSizeInNewSpace) {
2872 // Allocate in large object space, retry space will be ignored.
2873 space = LO_SPACE;
2874 } else if (size > MaxObjectSizeInPagedSpace()) {
2875 // Allocate in new space, retry in large object space.
2876 retry_space = LO_SPACE;
2877 }
2878 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2879 space = LO_SPACE;
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002880 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002881 Object* result = AllocateRaw(size, space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002882 if (result->IsFailure()) return result;
2883
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002884 // Partially initialize the object.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002885 HeapObject::cast(result)->set_map(ascii_string_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002886 String::cast(result)->set_length(length);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002887 String::cast(result)->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002888 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2889 return result;
2890}
2891
2892
2893Object* Heap::AllocateRawTwoByteString(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002894 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
2895 return Failure::OutOfMemoryException();
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002896 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002897 int size = SeqTwoByteString::SizeFor(length);
2898 ASSERT(size <= SeqTwoByteString::kMaxSize);
2899 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
2900 AllocationSpace retry_space = OLD_DATA_SPACE;
2901
2902 if (space == NEW_SPACE) {
2903 if (size > kMaxObjectSizeInNewSpace) {
2904 // Allocate in large object space, retry space will be ignored.
2905 space = LO_SPACE;
2906 } else if (size > MaxObjectSizeInPagedSpace()) {
2907 // Allocate in new space, retry in large object space.
2908 retry_space = LO_SPACE;
2909 }
2910 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
2911 space = LO_SPACE;
2912 }
2913 Object* result = AllocateRaw(size, space, retry_space);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002914 if (result->IsFailure()) return result;
2915
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002916 // Partially initialize the object.
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002917 HeapObject::cast(result)->set_map(string_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002918 String::cast(result)->set_length(length);
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00002919 String::cast(result)->set_hash_field(String::kEmptyHashField);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002920 ASSERT_EQ(size, HeapObject::cast(result)->Size());
2921 return result;
2922}
2923
2924
2925Object* Heap::AllocateEmptyFixedArray() {
2926 int size = FixedArray::SizeFor(0);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002927 Object* result = AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002928 if (result->IsFailure()) return result;
2929 // Initialize the object.
2930 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2931 reinterpret_cast<Array*>(result)->set_length(0);
2932 return result;
2933}
2934
2935
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002936Object* Heap::AllocateRawFixedArray(int length) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002937 if (length < 0 || length > FixedArray::kMaxLength) {
2938 return Failure::OutOfMemoryException();
2939 }
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002940 // Use the general function if we're forced to always allocate.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002941 if (always_allocate()) return AllocateFixedArray(length, TENURED);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002942 // Allocate the raw data for a fixed array.
2943 int size = FixedArray::SizeFor(length);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00002944 return size <= kMaxObjectSizeInNewSpace
2945 ? new_space_.AllocateRaw(size)
2946 : lo_space_->AllocateRawFixedArray(size);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002947}
2948
2949
2950Object* Heap::CopyFixedArray(FixedArray* src) {
2951 int len = src->length();
2952 Object* obj = AllocateRawFixedArray(len);
2953 if (obj->IsFailure()) return obj;
2954 if (Heap::InNewSpace(obj)) {
2955 HeapObject* dst = HeapObject::cast(obj);
2956 CopyBlock(reinterpret_cast<Object**>(dst->address()),
2957 reinterpret_cast<Object**>(src->address()),
2958 FixedArray::SizeFor(len));
2959 return obj;
2960 }
2961 HeapObject::cast(obj)->set_map(src->map());
2962 FixedArray* result = FixedArray::cast(obj);
2963 result->set_length(len);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002964
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002965 // Copy the content
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002966 AssertNoAllocation no_gc;
2967 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002968 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
2969 return result;
2970}
2971
2972
2973Object* Heap::AllocateFixedArray(int length) {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00002974 ASSERT(length >= 0);
ager@chromium.org32912102009-01-16 10:38:43 +00002975 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002976 Object* result = AllocateRawFixedArray(length);
2977 if (!result->IsFailure()) {
2978 // Initialize header.
2979 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
2980 FixedArray* array = FixedArray::cast(result);
2981 array->set_length(length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002982 // Initialize body.
vegorov@chromium.orgf8372902010-03-15 10:26:20 +00002983 ASSERT(!Heap::InNewSpace(undefined_value()));
2984 MemsetPointer(array->data_start(), undefined_value(), length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00002985 }
2986 return result;
2987}
2988
2989
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002990Object* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002991 ASSERT(length >= 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002992 ASSERT(empty_fixed_array()->IsFixedArray());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002993 if (length < 0 || length > FixedArray::kMaxLength) {
2994 return Failure::OutOfMemoryException();
2995 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002996 if (length == 0) return empty_fixed_array();
2997
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002998 AllocationSpace space =
2999 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003000 int size = FixedArray::SizeFor(length);
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003001 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
3002 // Too big for new space.
3003 space = LO_SPACE;
3004 } else if (space == OLD_POINTER_SPACE &&
3005 size > MaxObjectSizeInPagedSpace()) {
3006 // Too big for old pointer space.
3007 space = LO_SPACE;
3008 }
3009
3010 // Specialize allocation for the space.
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003011 Object* result = Failure::OutOfMemoryException();
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003012 if (space == NEW_SPACE) {
3013 // We cannot use Heap::AllocateRaw() because it will not properly
3014 // allocate extra remembered set bits if always_allocate() is true and
3015 // new space allocation fails.
3016 result = new_space_.AllocateRaw(size);
3017 if (result->IsFailure() && always_allocate()) {
3018 if (size <= MaxObjectSizeInPagedSpace()) {
3019 result = old_pointer_space_->AllocateRaw(size);
3020 } else {
3021 result = lo_space_->AllocateRawFixedArray(size);
3022 }
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003023 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003024 } else if (space == OLD_POINTER_SPACE) {
3025 result = old_pointer_space_->AllocateRaw(size);
3026 } else {
3027 ASSERT(space == LO_SPACE);
3028 result = lo_space_->AllocateRawFixedArray(size);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003029 }
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003030 if (result->IsFailure()) return result;
3031
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003032 // Initialize the object.
3033 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
3034 FixedArray* array = FixedArray::cast(result);
3035 array->set_length(length);
vegorov@chromium.orgf8372902010-03-15 10:26:20 +00003036 ASSERT(!Heap::InNewSpace(undefined_value()));
3037 MemsetPointer(array->data_start(), undefined_value(), length);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003038 return array;
3039}
3040
3041
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003042Object* Heap::AllocateUninitializedFixedArray(int length) {
3043 if (length == 0) return empty_fixed_array();
3044
3045 Object* obj = AllocateRawFixedArray(length);
3046 if (obj->IsFailure()) return obj;
3047
3048 reinterpret_cast<FixedArray*>(obj)->set_map(fixed_array_map());
3049 FixedArray::cast(obj)->set_length(length);
3050 return obj;
3051}
3052
3053
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003054Object* Heap::AllocateFixedArrayWithHoles(int length) {
3055 if (length == 0) return empty_fixed_array();
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003056 Object* result = AllocateRawFixedArray(length);
3057 if (!result->IsFailure()) {
3058 // Initialize header.
3059 reinterpret_cast<Array*>(result)->set_map(fixed_array_map());
3060 FixedArray* array = FixedArray::cast(result);
3061 array->set_length(length);
3062 // Initialize body.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003063 ASSERT(!Heap::InNewSpace(the_hole_value()));
vegorov@chromium.orgf8372902010-03-15 10:26:20 +00003064 MemsetPointer(array->data_start(), the_hole_value(), length);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003065 }
3066 return result;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003067}
3068
3069
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003070Object* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
3071 Object* result = Heap::AllocateFixedArray(length, pretenure);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003072 if (result->IsFailure()) return result;
3073 reinterpret_cast<Array*>(result)->set_map(hash_table_map());
kasperl@chromium.org86f77b72009-07-06 08:21:57 +00003074 ASSERT(result->IsHashTable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003075 return result;
3076}
3077
3078
3079Object* Heap::AllocateGlobalContext() {
3080 Object* result = Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
3081 if (result->IsFailure()) return result;
3082 Context* context = reinterpret_cast<Context*>(result);
3083 context->set_map(global_context_map());
3084 ASSERT(context->IsGlobalContext());
3085 ASSERT(result->IsContext());
3086 return result;
3087}
3088
3089
3090Object* Heap::AllocateFunctionContext(int length, JSFunction* function) {
3091 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
3092 Object* result = Heap::AllocateFixedArray(length);
3093 if (result->IsFailure()) return result;
3094 Context* context = reinterpret_cast<Context*>(result);
3095 context->set_map(context_map());
3096 context->set_closure(function);
3097 context->set_fcontext(context);
3098 context->set_previous(NULL);
3099 context->set_extension(NULL);
3100 context->set_global(function->context()->global());
3101 ASSERT(!context->IsGlobalContext());
3102 ASSERT(context->is_function_context());
3103 ASSERT(result->IsContext());
3104 return result;
3105}
3106
3107
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003108Object* Heap::AllocateWithContext(Context* previous,
3109 JSObject* extension,
3110 bool is_catch_context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003111 Object* result = Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
3112 if (result->IsFailure()) return result;
3113 Context* context = reinterpret_cast<Context*>(result);
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00003114 context->set_map(is_catch_context ? catch_context_map() : context_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003115 context->set_closure(previous->closure());
3116 context->set_fcontext(previous->fcontext());
3117 context->set_previous(previous);
3118 context->set_extension(extension);
3119 context->set_global(previous->global());
3120 ASSERT(!context->IsGlobalContext());
3121 ASSERT(!context->is_function_context());
3122 ASSERT(result->IsContext());
3123 return result;
3124}
3125
3126
3127Object* Heap::AllocateStruct(InstanceType type) {
3128 Map* map;
3129 switch (type) {
3130#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
3131STRUCT_LIST(MAKE_CASE)
3132#undef MAKE_CASE
3133 default:
3134 UNREACHABLE();
3135 return Failure::InternalError();
3136 }
3137 int size = map->instance_size();
3138 AllocationSpace space =
ager@chromium.org5aa501c2009-06-23 07:57:28 +00003139 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003140 Object* result = Heap::Allocate(map, space);
3141 if (result->IsFailure()) return result;
3142 Struct::cast(result)->InitializeBody(size);
3143 return result;
3144}
3145
3146
ager@chromium.org96c75b52009-08-26 09:13:16 +00003147bool Heap::IdleNotification() {
ager@chromium.orga1645e22009-09-09 19:27:10 +00003148 static const int kIdlesBeforeScavenge = 4;
3149 static const int kIdlesBeforeMarkSweep = 7;
3150 static const int kIdlesBeforeMarkCompact = 8;
ager@chromium.org96c75b52009-08-26 09:13:16 +00003151 static int number_idle_notifications = 0;
3152 static int last_gc_count = gc_count_;
3153
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003154 bool uncommit = true;
ager@chromium.org96c75b52009-08-26 09:13:16 +00003155 bool finished = false;
3156
3157 if (last_gc_count == gc_count_) {
3158 number_idle_notifications++;
3159 } else {
3160 number_idle_notifications = 0;
3161 last_gc_count = gc_count_;
3162 }
3163
ager@chromium.orga1645e22009-09-09 19:27:10 +00003164 if (number_idle_notifications == kIdlesBeforeScavenge) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003165 if (contexts_disposed_ > 0) {
3166 HistogramTimerScope scope(&Counters::gc_context);
3167 CollectAllGarbage(false);
3168 } else {
3169 CollectGarbage(0, NEW_SPACE);
3170 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00003171 new_space_.Shrink();
ager@chromium.org96c75b52009-08-26 09:13:16 +00003172 last_gc_count = gc_count_;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003173
3174 } else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00003175 // Before doing the mark-sweep collections we clear the
3176 // compilation cache to avoid hanging on to source code and
3177 // generated code for cached functions.
3178 CompilationCache::Clear();
3179
ager@chromium.orga1645e22009-09-09 19:27:10 +00003180 CollectAllGarbage(false);
3181 new_space_.Shrink();
3182 last_gc_count = gc_count_;
3183
3184 } else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
3185 CollectAllGarbage(true);
3186 new_space_.Shrink();
3187 last_gc_count = gc_count_;
3188 number_idle_notifications = 0;
3189 finished = true;
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003190
3191 } else if (contexts_disposed_ > 0) {
3192 if (FLAG_expose_gc) {
3193 contexts_disposed_ = 0;
3194 } else {
3195 HistogramTimerScope scope(&Counters::gc_context);
3196 CollectAllGarbage(false);
3197 last_gc_count = gc_count_;
3198 }
3199 // If this is the first idle notification, we reset the
3200 // notification count to avoid letting idle notifications for
3201 // context disposal garbage collections start a potentially too
3202 // aggressive idle GC cycle.
3203 if (number_idle_notifications <= 1) {
3204 number_idle_notifications = 0;
3205 uncommit = false;
3206 }
ager@chromium.org96c75b52009-08-26 09:13:16 +00003207 }
3208
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00003209 // Make sure that we have no pending context disposals and
3210 // conditionally uncommit from space.
3211 ASSERT(contexts_disposed_ == 0);
3212 if (uncommit) Heap::UncommitFromSpace();
ager@chromium.org96c75b52009-08-26 09:13:16 +00003213 return finished;
3214}
3215
3216
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003217#ifdef DEBUG
3218
3219void Heap::Print() {
3220 if (!HasBeenSetup()) return;
3221 Top::PrintStack();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003222 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003223 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3224 space->Print();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003225}
3226
3227
3228void Heap::ReportCodeStatistics(const char* title) {
3229 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
3230 PagedSpace::ResetCodeStatistics();
3231 // We do not look for code in new space, map space, or old space. If code
3232 // somehow ends up in those spaces, we would miss it here.
3233 code_space_->CollectCodeStatistics();
3234 lo_space_->CollectCodeStatistics();
3235 PagedSpace::ReportCodeStatistics();
3236}
3237
3238
3239// This function expects that NewSpace's allocated objects histogram is
3240// populated (via a call to CollectStatistics or else as a side effect of a
3241// just-completed scavenge collection).
3242void Heap::ReportHeapStatistics(const char* title) {
3243 USE(title);
3244 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
3245 title, gc_count_);
3246 PrintF("mark-compact GC : %d\n", mc_count_);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00003247 PrintF("old_gen_promotion_limit_ %d\n", old_gen_promotion_limit_);
3248 PrintF("old_gen_allocation_limit_ %d\n", old_gen_allocation_limit_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003249
3250 PrintF("\n");
3251 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
3252 GlobalHandles::PrintStats();
3253 PrintF("\n");
3254
3255 PrintF("Heap statistics : ");
3256 MemoryAllocator::ReportStatistics();
3257 PrintF("To space : ");
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003258 new_space_.ReportStatistics();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003259 PrintF("Old pointer space : ");
3260 old_pointer_space_->ReportStatistics();
3261 PrintF("Old data space : ");
3262 old_data_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003263 PrintF("Code space : ");
3264 code_space_->ReportStatistics();
3265 PrintF("Map space : ");
3266 map_space_->ReportStatistics();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003267 PrintF("Cell space : ");
3268 cell_space_->ReportStatistics();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003269 PrintF("Large object space : ");
3270 lo_space_->ReportStatistics();
3271 PrintF(">>>>>> ========================================= >>>>>>\n");
3272}
3273
3274#endif // DEBUG
3275
3276bool Heap::Contains(HeapObject* value) {
3277 return Contains(value->address());
3278}
3279
3280
3281bool Heap::Contains(Address addr) {
3282 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3283 return HasBeenSetup() &&
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003284 (new_space_.ToSpaceContains(addr) ||
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003285 old_pointer_space_->Contains(addr) ||
3286 old_data_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003287 code_space_->Contains(addr) ||
3288 map_space_->Contains(addr) ||
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003289 cell_space_->Contains(addr) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003290 lo_space_->SlowContains(addr));
3291}
3292
3293
3294bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
3295 return InSpace(value->address(), space);
3296}
3297
3298
3299bool Heap::InSpace(Address addr, AllocationSpace space) {
3300 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3301 if (!HasBeenSetup()) return false;
3302
3303 switch (space) {
3304 case NEW_SPACE:
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003305 return new_space_.ToSpaceContains(addr);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003306 case OLD_POINTER_SPACE:
3307 return old_pointer_space_->Contains(addr);
3308 case OLD_DATA_SPACE:
3309 return old_data_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003310 case CODE_SPACE:
3311 return code_space_->Contains(addr);
3312 case MAP_SPACE:
3313 return map_space_->Contains(addr);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003314 case CELL_SPACE:
3315 return cell_space_->Contains(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003316 case LO_SPACE:
3317 return lo_space_->SlowContains(addr);
3318 }
3319
3320 return false;
3321}
3322
3323
3324#ifdef DEBUG
3325void Heap::Verify() {
3326 ASSERT(HasBeenSetup());
3327
3328 VerifyPointersVisitor visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003329 IterateRoots(&visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003330
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003331 new_space_.Verify();
3332
3333 VerifyPointersAndRSetVisitor rset_visitor;
3334 old_pointer_space_->Verify(&rset_visitor);
3335 map_space_->Verify(&rset_visitor);
3336
3337 VerifyPointersVisitor no_rset_visitor;
3338 old_data_space_->Verify(&no_rset_visitor);
3339 code_space_->Verify(&no_rset_visitor);
3340 cell_space_->Verify(&no_rset_visitor);
3341
3342 lo_space_->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003343}
3344#endif // DEBUG
3345
3346
3347Object* Heap::LookupSymbol(Vector<const char> string) {
3348 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003349 Object* new_table = symbol_table()->LookupSymbol(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003350 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003351 // Can't use set_symbol_table because SymbolTable::cast knows that
3352 // SymbolTable is a singleton and checks for identity.
3353 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003354 ASSERT(symbol != NULL);
3355 return symbol;
3356}
3357
3358
3359Object* Heap::LookupSymbol(String* string) {
3360 if (string->IsSymbol()) return string;
3361 Object* symbol = NULL;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003362 Object* new_table = symbol_table()->LookupString(string, &symbol);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003363 if (new_table->IsFailure()) return new_table;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003364 // Can't use set_symbol_table because SymbolTable::cast knows that
3365 // SymbolTable is a singleton and checks for identity.
3366 roots_[kSymbolTableRootIndex] = new_table;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003367 ASSERT(symbol != NULL);
3368 return symbol;
3369}
3370
3371
ager@chromium.org7c537e22008-10-16 08:43:32 +00003372bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
3373 if (string->IsSymbol()) {
3374 *symbol = string;
3375 return true;
3376 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003377 return symbol_table()->LookupSymbolIfExists(string, symbol);
ager@chromium.org7c537e22008-10-16 08:43:32 +00003378}
3379
3380
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003381#ifdef DEBUG
3382void Heap::ZapFromSpace() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003383 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsHeapObject());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003384 for (Address a = new_space_.FromSpaceLow();
3385 a < new_space_.FromSpaceHigh();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003386 a += kPointerSize) {
3387 Memory::Address_at(a) = kFromSpaceZapValue;
3388 }
3389}
3390#endif // DEBUG
3391
3392
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003393int Heap::IterateRSetRange(Address object_start,
3394 Address object_end,
3395 Address rset_start,
3396 ObjectSlotCallback copy_object_func) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003397 Address object_address = object_start;
3398 Address rset_address = rset_start;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003399 int set_bits_count = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003400
3401 // Loop over all the pointers in [object_start, object_end).
3402 while (object_address < object_end) {
3403 uint32_t rset_word = Memory::uint32_at(rset_address);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003404 if (rset_word != 0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003405 uint32_t result_rset = rset_word;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003406 for (uint32_t bitmask = 1; bitmask != 0; bitmask = bitmask << 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003407 // Do not dereference pointers at or past object_end.
3408 if ((rset_word & bitmask) != 0 && object_address < object_end) {
3409 Object** object_p = reinterpret_cast<Object**>(object_address);
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003410 if (Heap::InNewSpace(*object_p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003411 copy_object_func(reinterpret_cast<HeapObject**>(object_p));
3412 }
3413 // If this pointer does not need to be remembered anymore, clear
3414 // the remembered set bit.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003415 if (!Heap::InNewSpace(*object_p)) result_rset &= ~bitmask;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003416 set_bits_count++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003417 }
3418 object_address += kPointerSize;
3419 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003420 // Update the remembered set if it has changed.
3421 if (result_rset != rset_word) {
3422 Memory::uint32_at(rset_address) = result_rset;
3423 }
3424 } else {
3425 // No bits in the word were set. This is the common case.
3426 object_address += kPointerSize * kBitsPerInt;
3427 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003428 rset_address += kIntSize;
3429 }
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003430 return set_bits_count;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003431}
3432
3433
3434void Heap::IterateRSet(PagedSpace* space, ObjectSlotCallback copy_object_func) {
3435 ASSERT(Page::is_rset_in_use());
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003436 ASSERT(space == old_pointer_space_ || space == map_space_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003437
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003438 static void* paged_rset_histogram = StatsTable::CreateHistogram(
3439 "V8.RSetPaged",
3440 0,
3441 Page::kObjectAreaSize / kPointerSize,
3442 30);
3443
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003444 PageIterator it(space, PageIterator::PAGES_IN_USE);
3445 while (it.has_next()) {
3446 Page* page = it.next();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00003447 int count = IterateRSetRange(page->ObjectAreaStart(), page->AllocationTop(),
3448 page->RSetStart(), copy_object_func);
3449 if (paged_rset_histogram != NULL) {
3450 StatsTable::AddHistogramSample(paged_rset_histogram, count);
3451 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003452 }
3453}
3454
3455
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003456void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
3457 IterateStrongRoots(v, mode);
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003458 IterateWeakRoots(v, mode);
3459}
3460
3461
3462void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003463 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
ager@chromium.org3811b432009-10-28 14:53:37 +00003464 v->Synchronize("symbol_table");
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003465 if (mode != VISIT_ALL_IN_SCAVENGE) {
3466 // Scavenge collections have special processing for this.
3467 ExternalStringTable::Iterate(v);
3468 }
3469 v->Synchronize("external_string_table");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003470}
3471
3472
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003473void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00003474 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
ager@chromium.org3811b432009-10-28 14:53:37 +00003475 v->Synchronize("strong_root_list");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003476
vegorov@chromium.orgf8372902010-03-15 10:26:20 +00003477 v->VisitPointer(BitCast<Object**, String**>(&hidden_symbol_));
ager@chromium.org3811b432009-10-28 14:53:37 +00003478 v->Synchronize("symbol");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003479
3480 Bootstrapper::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003481 v->Synchronize("bootstrapper");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003482 Top::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003483 v->Synchronize("top");
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00003484 Relocatable::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003485 v->Synchronize("relocatable");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003486
3487#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003488 Debug::Iterate(v);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00003489#endif
ager@chromium.org3811b432009-10-28 14:53:37 +00003490 v->Synchronize("debug");
kasperl@chromium.orgb9123622008-09-17 14:05:56 +00003491 CompilationCache::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003492 v->Synchronize("compilationcache");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003493
3494 // Iterate over local handles in handle scopes.
3495 HandleScopeImplementer::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003496 v->Synchronize("handlescope");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003497
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003498 // Iterate over the builtin code objects and code stubs in the
3499 // heap. Note that it is not necessary to iterate over code objects
3500 // on scavenge collections.
3501 if (mode != VISIT_ALL_IN_SCAVENGE) {
3502 Builtins::IterateBuiltins(v);
3503 }
ager@chromium.org3811b432009-10-28 14:53:37 +00003504 v->Synchronize("builtins");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003505
3506 // Iterate over global handles.
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003507 if (mode == VISIT_ONLY_STRONG) {
3508 GlobalHandles::IterateStrongRoots(v);
3509 } else {
3510 GlobalHandles::IterateAllRoots(v);
3511 }
ager@chromium.org3811b432009-10-28 14:53:37 +00003512 v->Synchronize("globalhandles");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003513
3514 // Iterate over pointers being held by inactive threads.
3515 ThreadManager::Iterate(v);
ager@chromium.org3811b432009-10-28 14:53:37 +00003516 v->Synchronize("threadmanager");
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003517
3518 // Iterate over the pointers the Serialization/Deserialization code is
3519 // holding.
3520 // During garbage collection this keeps the partial snapshot cache alive.
3521 // During deserialization of the startup snapshot this creates the partial
3522 // snapshot cache and deserializes the objects it refers to. During
3523 // serialization this does nothing, since the partial snapshot cache is
3524 // empty. However the next thing we do is create the partial snapshot,
3525 // filling up the partial snapshot cache with objects it needs as we go.
3526 SerializerDeserializer::Iterate(v);
3527 // We don't do a v->Synchronize call here, because in debug mode that will
3528 // output a flag to the snapshot. However at this point the serializer and
3529 // deserializer are deliberately a little unsynchronized (see above) so the
3530 // checking of the sync flag in the snapshot would fail.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003531}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003532
3533
3534// Flag is set when the heap has been configured. The heap can be repeatedly
3535// configured through the API until it is setup.
3536static bool heap_configured = false;
3537
3538// TODO(1236194): Since the heap size is configurable on the command line
3539// and through the API, we should gracefully handle the case that the heap
3540// size is not big enough to fit all the initial objects.
ager@chromium.org3811b432009-10-28 14:53:37 +00003541bool Heap::ConfigureHeap(int max_semispace_size, int max_old_gen_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003542 if (HasBeenSetup()) return false;
3543
ager@chromium.org3811b432009-10-28 14:53:37 +00003544 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
3545
3546 if (Snapshot::IsEnabled()) {
3547 // If we are using a snapshot we always reserve the default amount
3548 // of memory for each semispace because code in the snapshot has
3549 // write-barrier code that relies on the size and alignment of new
3550 // space. We therefore cannot use a larger max semispace size
3551 // than the default reserved semispace size.
3552 if (max_semispace_size_ > reserved_semispace_size_) {
3553 max_semispace_size_ = reserved_semispace_size_;
3554 }
3555 } else {
3556 // If we are not using snapshots we reserve space for the actual
3557 // max semispace size.
3558 reserved_semispace_size_ = max_semispace_size_;
3559 }
3560
3561 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003562
3563 // The new space size must be a power of two to support single-bit testing
3564 // for containment.
ager@chromium.org3811b432009-10-28 14:53:37 +00003565 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
3566 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
3567 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
3568 external_allocation_limit_ = 10 * max_semispace_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003569
3570 // The old generation is paged.
ager@chromium.org3811b432009-10-28 14:53:37 +00003571 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003572
3573 heap_configured = true;
3574 return true;
3575}
3576
3577
kasper.lund7276f142008-07-30 08:49:36 +00003578bool Heap::ConfigureHeapDefault() {
ager@chromium.org3811b432009-10-28 14:53:37 +00003579 return ConfigureHeap(FLAG_max_new_space_size / 2, FLAG_max_old_space_size);
kasper.lund7276f142008-07-30 08:49:36 +00003580}
3581
3582
ager@chromium.org60121232009-12-03 11:25:37 +00003583void Heap::RecordStats(HeapStats* stats) {
sgjesse@chromium.orgac6aa172009-12-04 12:29:05 +00003584 *stats->start_marker = 0xDECADE00;
3585 *stats->end_marker = 0xDECADE01;
3586 *stats->new_space_size = new_space_.Size();
3587 *stats->new_space_capacity = new_space_.Capacity();
3588 *stats->old_pointer_space_size = old_pointer_space_->Size();
3589 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
3590 *stats->old_data_space_size = old_data_space_->Size();
3591 *stats->old_data_space_capacity = old_data_space_->Capacity();
3592 *stats->code_space_size = code_space_->Size();
3593 *stats->code_space_capacity = code_space_->Capacity();
3594 *stats->map_space_size = map_space_->Size();
3595 *stats->map_space_capacity = map_space_->Capacity();
3596 *stats->cell_space_size = cell_space_->Size();
3597 *stats->cell_space_capacity = cell_space_->Capacity();
3598 *stats->lo_space_size = lo_space_->Size();
ager@chromium.org60121232009-12-03 11:25:37 +00003599 GlobalHandles::RecordStats(stats);
3600}
3601
3602
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003603int Heap::PromotedSpaceSize() {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003604 return old_pointer_space_->Size()
3605 + old_data_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003606 + code_space_->Size()
3607 + map_space_->Size()
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003608 + cell_space_->Size()
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003609 + lo_space_->Size();
3610}
3611
3612
kasper.lund7276f142008-07-30 08:49:36 +00003613int Heap::PromotedExternalMemorySize() {
3614 if (amount_of_external_allocated_memory_
3615 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
3616 return amount_of_external_allocated_memory_
3617 - amount_of_external_allocated_memory_at_last_global_gc_;
3618}
3619
3620
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003621bool Heap::Setup(bool create_heap_objects) {
3622 // Initialize heap spaces and initial maps and objects. Whenever something
3623 // goes wrong, just return false. The caller should check the results and
3624 // call Heap::TearDown() to release allocated memory.
3625 //
3626 // If the heap is not yet configured (eg, through the API), configure it.
3627 // Configuration is based on the flags new-space-size (really the semispace
3628 // size) and old-space-size if set or the initial values of semispace_size_
3629 // and old_generation_size_ otherwise.
3630 if (!heap_configured) {
kasper.lund7276f142008-07-30 08:49:36 +00003631 if (!ConfigureHeapDefault()) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003632 }
3633
ager@chromium.orga1645e22009-09-09 19:27:10 +00003634 // Setup memory allocator and reserve a chunk of memory for new
ager@chromium.org3811b432009-10-28 14:53:37 +00003635 // space. The chunk is double the size of the requested reserved
3636 // new space size to ensure that we can find a pair of semispaces that
3637 // are contiguous and aligned to their size.
3638 if (!MemoryAllocator::Setup(MaxReserved())) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003639 void* chunk =
ager@chromium.org3811b432009-10-28 14:53:37 +00003640 MemoryAllocator::ReserveInitialChunk(4 * reserved_semispace_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003641 if (chunk == NULL) return false;
3642
ager@chromium.orga1645e22009-09-09 19:27:10 +00003643 // Align the pair of semispaces to their size, which must be a power
3644 // of 2.
ager@chromium.orga1645e22009-09-09 19:27:10 +00003645 Address new_space_start =
ager@chromium.org3811b432009-10-28 14:53:37 +00003646 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
3647 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
3648 return false;
3649 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003650
ager@chromium.orga1645e22009-09-09 19:27:10 +00003651 // Initialize old pointer space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003652 old_pointer_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003653 new OldSpace(max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003654 if (old_pointer_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003655 if (!old_pointer_space_->Setup(NULL, 0)) return false;
3656
3657 // Initialize old data space.
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003658 old_data_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003659 new OldSpace(max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003660 if (old_data_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003661 if (!old_data_space_->Setup(NULL, 0)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003662
3663 // Initialize the code space, set its maximum capacity to the old
kasper.lund7276f142008-07-30 08:49:36 +00003664 // generation size. It needs executable memory.
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00003665 // On 64-bit platform(s), we put all code objects in a 2 GB range of
3666 // virtual address space, so that they can call each other with near calls.
3667 if (code_range_size_ > 0) {
3668 if (!CodeRange::Setup(code_range_size_)) {
3669 return false;
3670 }
3671 }
3672
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003673 code_space_ =
ager@chromium.org3811b432009-10-28 14:53:37 +00003674 new OldSpace(max_old_generation_size_, CODE_SPACE, EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003675 if (code_space_ == NULL) return false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00003676 if (!code_space_->Setup(NULL, 0)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003677
3678 // Initialize map space.
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003679 map_space_ = new MapSpace(FLAG_use_big_map_space
3680 ? max_old_generation_size_
kasperl@chromium.orgeac059f2010-01-25 11:02:06 +00003681 : MapSpace::kMaxMapPageIndex * Page::kPageSize,
3682 FLAG_max_map_space_pages,
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00003683 MAP_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003684 if (map_space_ == NULL) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003685 if (!map_space_->Setup(NULL, 0)) return false;
3686
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003687 // Initialize global property cell space.
ager@chromium.org3811b432009-10-28 14:53:37 +00003688 cell_space_ = new CellSpace(max_old_generation_size_, CELL_SPACE);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003689 if (cell_space_ == NULL) return false;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003690 if (!cell_space_->Setup(NULL, 0)) return false;
3691
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003692 // The large object code space may contain code or data. We set the memory
3693 // to be non-executable here for safety, but this means we need to enable it
3694 // explicitly when allocating large code objects.
3695 lo_space_ = new LargeObjectSpace(LO_SPACE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003696 if (lo_space_ == NULL) return false;
3697 if (!lo_space_->Setup()) return false;
3698
3699 if (create_heap_objects) {
3700 // Create initial maps.
3701 if (!CreateInitialMaps()) return false;
3702 if (!CreateApiObjects()) return false;
3703
3704 // Create initial objects
3705 if (!CreateInitialObjects()) return false;
3706 }
3707
3708 LOG(IntEvent("heap-capacity", Capacity()));
3709 LOG(IntEvent("heap-available", Available()));
3710
ager@chromium.org3811b432009-10-28 14:53:37 +00003711#ifdef ENABLE_LOGGING_AND_PROFILING
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00003712 // This should be called only after initial objects have been created.
3713 ProducerHeapProfile::Setup();
ager@chromium.org3811b432009-10-28 14:53:37 +00003714#endif
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00003715
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003716 return true;
3717}
3718
3719
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003720void Heap::SetStackLimits() {
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003721 // On 64 bit machines, pointers are generally out of range of Smis. We write
3722 // something that looks like an out of range Smi to the GC.
3723
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003724 // Set up the special root array entries containing the stack limits.
3725 // These are actually addresses, but the tag makes the GC ignore it.
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003726 roots_[kStackLimitRootIndex] =
ager@chromium.orgc4c92722009-11-18 14:12:51 +00003727 reinterpret_cast<Object*>(
3728 (StackGuard::jslimit() & ~kSmiTagMask) | kSmiTag);
3729 roots_[kRealStackLimitRootIndex] =
3730 reinterpret_cast<Object*>(
3731 (StackGuard::real_jslimit() & ~kSmiTagMask) | kSmiTag);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00003732}
3733
3734
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003735void Heap::TearDown() {
3736 GlobalHandles::TearDown();
3737
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00003738 ExternalStringTable::TearDown();
3739
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00003740 new_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003741
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003742 if (old_pointer_space_ != NULL) {
3743 old_pointer_space_->TearDown();
3744 delete old_pointer_space_;
3745 old_pointer_space_ = NULL;
3746 }
3747
3748 if (old_data_space_ != NULL) {
3749 old_data_space_->TearDown();
3750 delete old_data_space_;
3751 old_data_space_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003752 }
3753
3754 if (code_space_ != NULL) {
3755 code_space_->TearDown();
3756 delete code_space_;
3757 code_space_ = NULL;
3758 }
3759
3760 if (map_space_ != NULL) {
3761 map_space_->TearDown();
3762 delete map_space_;
3763 map_space_ = NULL;
3764 }
3765
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003766 if (cell_space_ != NULL) {
3767 cell_space_->TearDown();
3768 delete cell_space_;
3769 cell_space_ = NULL;
3770 }
3771
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003772 if (lo_space_ != NULL) {
3773 lo_space_->TearDown();
3774 delete lo_space_;
3775 lo_space_ = NULL;
3776 }
3777
3778 MemoryAllocator::TearDown();
3779}
3780
3781
3782void Heap::Shrink() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003783 // Try to shrink all paged spaces.
3784 PagedSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003785 for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next())
3786 space->Shrink();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003787}
3788
3789
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003790#ifdef ENABLE_HEAP_PROTECTION
3791
3792void Heap::Protect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003793 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003794 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003795 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3796 space->Protect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003797 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003798}
3799
3800
3801void Heap::Unprotect() {
ager@chromium.org71daaf62009-04-01 07:22:49 +00003802 if (HasBeenSetup()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003803 AllSpaces spaces;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00003804 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3805 space->Unprotect();
ager@chromium.org71daaf62009-04-01 07:22:49 +00003806 }
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00003807}
3808
3809#endif
3810
3811
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00003812void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
3813 ASSERT(callback != NULL);
3814 GCPrologueCallbackPair pair(callback, gc_type);
3815 ASSERT(!gc_prologue_callbacks_.Contains(pair));
3816 return gc_prologue_callbacks_.Add(pair);
3817}
3818
3819
3820void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
3821 ASSERT(callback != NULL);
3822 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
3823 if (gc_prologue_callbacks_[i].callback == callback) {
3824 gc_prologue_callbacks_.Remove(i);
3825 return;
3826 }
3827 }
3828 UNREACHABLE();
3829}
3830
3831
3832void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
3833 ASSERT(callback != NULL);
3834 GCEpilogueCallbackPair pair(callback, gc_type);
3835 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
3836 return gc_epilogue_callbacks_.Add(pair);
3837}
3838
3839
3840void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
3841 ASSERT(callback != NULL);
3842 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
3843 if (gc_epilogue_callbacks_[i].callback == callback) {
3844 gc_epilogue_callbacks_.Remove(i);
3845 return;
3846 }
3847 }
3848 UNREACHABLE();
3849}
3850
3851
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003852#ifdef DEBUG
3853
3854class PrintHandleVisitor: public ObjectVisitor {
3855 public:
3856 void VisitPointers(Object** start, Object** end) {
3857 for (Object** p = start; p < end; p++)
3858 PrintF(" handle %p to %p\n", p, *p);
3859 }
3860};
3861
3862void Heap::PrintHandles() {
3863 PrintF("Handles:\n");
3864 PrintHandleVisitor v;
3865 HandleScopeImplementer::Iterate(&v);
3866}
3867
3868#endif
3869
3870
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003871Space* AllSpaces::next() {
3872 switch (counter_++) {
3873 case NEW_SPACE:
3874 return Heap::new_space();
3875 case OLD_POINTER_SPACE:
3876 return Heap::old_pointer_space();
3877 case OLD_DATA_SPACE:
3878 return Heap::old_data_space();
3879 case CODE_SPACE:
3880 return Heap::code_space();
3881 case MAP_SPACE:
3882 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003883 case CELL_SPACE:
3884 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003885 case LO_SPACE:
3886 return Heap::lo_space();
3887 default:
3888 return NULL;
3889 }
3890}
3891
3892
3893PagedSpace* PagedSpaces::next() {
3894 switch (counter_++) {
3895 case OLD_POINTER_SPACE:
3896 return Heap::old_pointer_space();
3897 case OLD_DATA_SPACE:
3898 return Heap::old_data_space();
3899 case CODE_SPACE:
3900 return Heap::code_space();
3901 case MAP_SPACE:
3902 return Heap::map_space();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003903 case CELL_SPACE:
3904 return Heap::cell_space();
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003905 default:
3906 return NULL;
3907 }
3908}
3909
3910
3911
3912OldSpace* OldSpaces::next() {
3913 switch (counter_++) {
3914 case OLD_POINTER_SPACE:
3915 return Heap::old_pointer_space();
3916 case OLD_DATA_SPACE:
3917 return Heap::old_data_space();
3918 case CODE_SPACE:
3919 return Heap::code_space();
3920 default:
3921 return NULL;
3922 }
3923}
3924
3925
kasper.lund7276f142008-07-30 08:49:36 +00003926SpaceIterator::SpaceIterator() : current_space_(FIRST_SPACE), iterator_(NULL) {
3927}
3928
3929
3930SpaceIterator::~SpaceIterator() {
3931 // Delete active iterator if any.
3932 delete iterator_;
3933}
3934
3935
3936bool SpaceIterator::has_next() {
3937 // Iterate until no more spaces.
3938 return current_space_ != LAST_SPACE;
3939}
3940
3941
3942ObjectIterator* SpaceIterator::next() {
3943 if (iterator_ != NULL) {
3944 delete iterator_;
3945 iterator_ = NULL;
3946 // Move to the next space
3947 current_space_++;
3948 if (current_space_ > LAST_SPACE) {
3949 return NULL;
3950 }
3951 }
3952
3953 // Return iterator for the new current space.
3954 return CreateIterator();
3955}
3956
3957
3958// Create an iterator for the space to iterate.
3959ObjectIterator* SpaceIterator::CreateIterator() {
3960 ASSERT(iterator_ == NULL);
3961
3962 switch (current_space_) {
3963 case NEW_SPACE:
3964 iterator_ = new SemiSpaceIterator(Heap::new_space());
3965 break;
ager@chromium.org9258b6b2008-09-11 09:11:10 +00003966 case OLD_POINTER_SPACE:
3967 iterator_ = new HeapObjectIterator(Heap::old_pointer_space());
3968 break;
3969 case OLD_DATA_SPACE:
3970 iterator_ = new HeapObjectIterator(Heap::old_data_space());
kasper.lund7276f142008-07-30 08:49:36 +00003971 break;
3972 case CODE_SPACE:
3973 iterator_ = new HeapObjectIterator(Heap::code_space());
3974 break;
3975 case MAP_SPACE:
3976 iterator_ = new HeapObjectIterator(Heap::map_space());
3977 break;
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00003978 case CELL_SPACE:
3979 iterator_ = new HeapObjectIterator(Heap::cell_space());
3980 break;
kasper.lund7276f142008-07-30 08:49:36 +00003981 case LO_SPACE:
3982 iterator_ = new LargeObjectIterator(Heap::lo_space());
3983 break;
3984 }
3985
3986 // Return the newly allocated iterator;
3987 ASSERT(iterator_ != NULL);
3988 return iterator_;
3989}
3990
3991
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00003992HeapIterator::HeapIterator() {
3993 Init();
3994}
3995
3996
3997HeapIterator::~HeapIterator() {
3998 Shutdown();
3999}
4000
4001
4002void HeapIterator::Init() {
4003 // Start the iteration.
4004 space_iterator_ = new SpaceIterator();
4005 object_iterator_ = space_iterator_->next();
4006}
4007
4008
4009void HeapIterator::Shutdown() {
4010 // Make sure the last iterator is deallocated.
4011 delete space_iterator_;
4012 space_iterator_ = NULL;
4013 object_iterator_ = NULL;
4014}
4015
4016
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004017HeapObject* HeapIterator::next() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004018 // No iterator means we are done.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004019 if (object_iterator_ == NULL) return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004020
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004021 if (HeapObject* obj = object_iterator_->next_object()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004022 // If the current iterator has more objects we are fine.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004023 return obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004024 } else {
4025 // Go though the spaces looking for one that has objects.
4026 while (space_iterator_->has_next()) {
4027 object_iterator_ = space_iterator_->next();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004028 if (HeapObject* obj = object_iterator_->next_object()) {
4029 return obj;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004030 }
4031 }
4032 }
4033 // Done with the last space.
4034 object_iterator_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00004035 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004036}
4037
4038
4039void HeapIterator::reset() {
4040 // Restart the iterator.
4041 Shutdown();
4042 Init();
4043}
4044
4045
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004046#ifdef DEBUG
4047
4048static bool search_for_any_global;
4049static Object* search_target;
4050static bool found_target;
4051static List<Object*> object_stack(20);
4052
4053
4054// Tags 0, 1, and 3 are used. Use 2 for marking visited HeapObject.
4055static const int kMarkTag = 2;
4056
4057static void MarkObjectRecursively(Object** p);
4058class MarkObjectVisitor : public ObjectVisitor {
4059 public:
4060 void VisitPointers(Object** start, Object** end) {
4061 // Copy all HeapObject pointers in [start, end)
4062 for (Object** p = start; p < end; p++) {
4063 if ((*p)->IsHeapObject())
4064 MarkObjectRecursively(p);
4065 }
4066 }
4067};
4068
4069static MarkObjectVisitor mark_visitor;
4070
4071static void MarkObjectRecursively(Object** p) {
4072 if (!(*p)->IsHeapObject()) return;
4073
4074 HeapObject* obj = HeapObject::cast(*p);
4075
4076 Object* map = obj->map();
4077
4078 if (!map->IsHeapObject()) return; // visited before
4079
4080 if (found_target) return; // stop if target found
4081 object_stack.Add(obj);
4082 if ((search_for_any_global && obj->IsJSGlobalObject()) ||
4083 (!search_for_any_global && (obj == search_target))) {
4084 found_target = true;
4085 return;
4086 }
4087
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004088 // not visited yet
4089 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
4090
4091 Address map_addr = map_p->address();
4092
4093 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
4094
4095 MarkObjectRecursively(&map);
4096
4097 obj->IterateBody(map_p->instance_type(), obj->SizeFromMap(map_p),
4098 &mark_visitor);
4099
4100 if (!found_target) // don't pop if found the target
4101 object_stack.RemoveLast();
4102}
4103
4104
4105static void UnmarkObjectRecursively(Object** p);
4106class UnmarkObjectVisitor : public ObjectVisitor {
4107 public:
4108 void VisitPointers(Object** start, Object** end) {
4109 // Copy all HeapObject pointers in [start, end)
4110 for (Object** p = start; p < end; p++) {
4111 if ((*p)->IsHeapObject())
4112 UnmarkObjectRecursively(p);
4113 }
4114 }
4115};
4116
4117static UnmarkObjectVisitor unmark_visitor;
4118
4119static void UnmarkObjectRecursively(Object** p) {
4120 if (!(*p)->IsHeapObject()) return;
4121
4122 HeapObject* obj = HeapObject::cast(*p);
4123
4124 Object* map = obj->map();
4125
4126 if (map->IsHeapObject()) return; // unmarked already
4127
4128 Address map_addr = reinterpret_cast<Address>(map);
4129
4130 map_addr -= kMarkTag;
4131
4132 ASSERT_TAG_ALIGNED(map_addr);
4133
4134 HeapObject* map_p = HeapObject::FromAddress(map_addr);
4135
4136 obj->set_map(reinterpret_cast<Map*>(map_p));
4137
4138 UnmarkObjectRecursively(reinterpret_cast<Object**>(&map_p));
4139
4140 obj->IterateBody(Map::cast(map_p)->instance_type(),
4141 obj->SizeFromMap(Map::cast(map_p)),
4142 &unmark_visitor);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004143}
4144
4145
4146static void MarkRootObjectRecursively(Object** root) {
4147 if (search_for_any_global) {
4148 ASSERT(search_target == NULL);
4149 } else {
4150 ASSERT(search_target->IsHeapObject());
4151 }
4152 found_target = false;
4153 object_stack.Clear();
4154
4155 MarkObjectRecursively(root);
4156 UnmarkObjectRecursively(root);
4157
4158 if (found_target) {
4159 PrintF("=====================================\n");
4160 PrintF("==== Path to object ====\n");
4161 PrintF("=====================================\n\n");
4162
4163 ASSERT(!object_stack.is_empty());
4164 for (int i = 0; i < object_stack.length(); i++) {
4165 if (i > 0) PrintF("\n |\n |\n V\n\n");
4166 Object* obj = object_stack[i];
4167 obj->Print();
4168 }
4169 PrintF("=====================================\n");
4170 }
4171}
4172
4173
4174// Helper class for visiting HeapObjects recursively.
4175class MarkRootVisitor: public ObjectVisitor {
4176 public:
4177 void VisitPointers(Object** start, Object** end) {
4178 // Visit all HeapObject pointers in [start, end)
4179 for (Object** p = start; p < end; p++) {
4180 if ((*p)->IsHeapObject())
4181 MarkRootObjectRecursively(p);
4182 }
4183 }
4184};
4185
4186
4187// Triggers a depth-first traversal of reachable objects from roots
4188// and finds a path to a specific heap object and prints it.
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004189void Heap::TracePathToObject(Object* target) {
4190 search_target = target;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004191 search_for_any_global = false;
4192
4193 MarkRootVisitor root_visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00004194 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004195}
4196
4197
4198// Triggers a depth-first traversal of reachable objects from roots
4199// and finds a path to any global object and prints it. Useful for
4200// determining the source for leaks of global objects.
4201void Heap::TracePathToGlobal() {
4202 search_target = NULL;
4203 search_for_any_global = true;
4204
4205 MarkRootVisitor root_visitor;
ager@chromium.orgc4c92722009-11-18 14:12:51 +00004206 IterateRoots(&root_visitor, VISIT_ONLY_STRONG);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004207}
4208#endif
4209
4210
kasper.lund7276f142008-07-30 08:49:36 +00004211GCTracer::GCTracer()
4212 : start_time_(0.0),
4213 start_size_(0.0),
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00004214 external_time_(0.0),
kasper.lund7276f142008-07-30 08:49:36 +00004215 gc_count_(0),
4216 full_gc_count_(0),
4217 is_compacting_(false),
4218 marked_count_(0) {
4219 // These two fields reflect the state of the previous full collection.
4220 // Set them before they are changed by the collector.
4221 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
4222 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
4223 if (!FLAG_trace_gc) return;
4224 start_time_ = OS::TimeCurrentMillis();
4225 start_size_ = SizeOfHeapObjects();
4226}
4227
4228
4229GCTracer::~GCTracer() {
4230 if (!FLAG_trace_gc) return;
4231 // Printf ONE line iff flag is set.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00004232 int time = static_cast<int>(OS::TimeCurrentMillis() - start_time_);
4233 int external_time = static_cast<int>(external_time_);
4234 PrintF("%s %.1f -> %.1f MB, ",
4235 CollectorString(), start_size_, SizeOfHeapObjects());
4236 if (external_time > 0) PrintF("%d / ", external_time);
4237 PrintF("%d ms.\n", time);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00004238
4239#if defined(ENABLE_LOGGING_AND_PROFILING)
4240 Heap::PrintShortHeapStatistics();
4241#endif
kasper.lund7276f142008-07-30 08:49:36 +00004242}
4243
4244
4245const char* GCTracer::CollectorString() {
4246 switch (collector_) {
4247 case SCAVENGER:
4248 return "Scavenge";
4249 case MARK_COMPACTOR:
4250 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
4251 : "Mark-sweep";
4252 }
4253 return "Unknown GC";
4254}
4255
4256
ager@chromium.org5aa501c2009-06-23 07:57:28 +00004257int KeyedLookupCache::Hash(Map* map, String* name) {
4258 // Uses only lower 32 bits if pointers are larger.
4259 uintptr_t addr_hash =
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004260 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
fschneider@chromium.orgb95b98b2010-02-23 10:34:29 +00004261 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
ager@chromium.org5aa501c2009-06-23 07:57:28 +00004262}
4263
4264
4265int KeyedLookupCache::Lookup(Map* map, String* name) {
4266 int index = Hash(map, name);
4267 Key& key = keys_[index];
4268 if ((key.map == map) && key.name->Equals(name)) {
4269 return field_offsets_[index];
4270 }
4271 return -1;
4272}
4273
4274
4275void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
4276 String* symbol;
4277 if (Heap::LookupSymbolIfExists(name, &symbol)) {
4278 int index = Hash(map, symbol);
4279 Key& key = keys_[index];
4280 key.map = map;
4281 key.name = symbol;
4282 field_offsets_[index] = field_offset;
4283 }
4284}
4285
4286
4287void KeyedLookupCache::Clear() {
4288 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
4289}
4290
4291
4292KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
4293
4294
4295int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
4296
4297
4298void DescriptorLookupCache::Clear() {
4299 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
4300}
4301
4302
4303DescriptorLookupCache::Key
4304DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
4305
4306int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
4307
4308
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00004309#ifdef DEBUG
4310bool Heap::GarbageCollectionGreedyCheck() {
4311 ASSERT(FLAG_gc_greedy);
4312 if (Bootstrapper::IsActive()) return true;
4313 if (disallow_allocation_failure()) return true;
4314 return CollectGarbage(0, NEW_SPACE);
4315}
4316#endif
4317
ager@chromium.org18ad94b2009-09-02 08:22:29 +00004318
4319TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
4320 : type_(t) {
4321 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
4322 uint32_t in1 = 0xffffffffu; // generated by the FPU.
4323 for (int i = 0; i < kCacheSize; i++) {
4324 elements_[i].in[0] = in0;
4325 elements_[i].in[1] = in1;
4326 elements_[i].output = NULL;
4327 }
4328}
4329
4330
4331TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
4332
4333
4334void TranscendentalCache::Clear() {
4335 for (int i = 0; i < kNumberOfCaches; i++) {
4336 if (caches_[i] != NULL) {
4337 delete caches_[i];
4338 caches_[i] = NULL;
4339 }
4340 }
4341}
4342
4343
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +00004344void ExternalStringTable::CleanUp() {
4345 int last = 0;
4346 for (int i = 0; i < new_space_strings_.length(); ++i) {
4347 if (new_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4348 if (Heap::InNewSpace(new_space_strings_[i])) {
4349 new_space_strings_[last++] = new_space_strings_[i];
4350 } else {
4351 old_space_strings_.Add(new_space_strings_[i]);
4352 }
4353 }
4354 new_space_strings_.Rewind(last);
4355 last = 0;
4356 for (int i = 0; i < old_space_strings_.length(); ++i) {
4357 if (old_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
4358 ASSERT(!Heap::InNewSpace(old_space_strings_[i]));
4359 old_space_strings_[last++] = old_space_strings_[i];
4360 }
4361 old_space_strings_.Rewind(last);
4362 Verify();
4363}
4364
4365
4366void ExternalStringTable::TearDown() {
4367 new_space_strings_.Free();
4368 old_space_strings_.Free();
4369}
4370
4371
4372List<Object*> ExternalStringTable::new_space_strings_;
4373List<Object*> ExternalStringTable::old_space_strings_;
4374
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00004375} } // namespace v8::internal