blob: 34ab9aafcf64140e9293a316083202e204413a29 [file] [log] [blame]
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +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"
34#include "compilation-cache.h"
35#include "debug.h"
36#include "heap-profiler.h"
37#include "global-handles.h"
Steve Block1e0659c2011-05-24 12:43:12 +010038#include "liveobjectlist-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000039#include "mark-compact.h"
40#include "natives.h"
Iain Merrick75681382010-08-19 15:07:18 +010041#include "objects-visiting.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010042#include "runtime-profiler.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080043#include "scanner-base.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000044#include "scopeinfo.h"
Steve Block3ce2e202009-11-05 08:53:23 +000045#include "snapshot.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000046#include "v8threads.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010047#include "vm-state-inl.h"
Steve Block6ded16b2010-05-10 14:33:55 +010048#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +000049#include "regexp-macro-assembler.h"
Steve Blockd0582a62009-12-15 09:54:21 +000050#include "arm/regexp-macro-assembler-arm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000051#endif
52
Steve Block6ded16b2010-05-10 14:33:55 +010053
Steve Blocka7e24c12009-10-30 11:49:00 +000054namespace v8 {
55namespace internal {
56
57
58String* Heap::hidden_symbol_;
59Object* Heap::roots_[Heap::kRootListLength];
Ben Murdochf87a2032010-10-22 12:50:53 +010060Object* Heap::global_contexts_list_;
Steve Blocka7e24c12009-10-30 11:49:00 +000061
John Reck59135872010-11-02 12:39:01 -070062
Steve Blocka7e24c12009-10-30 11:49:00 +000063NewSpace Heap::new_space_;
64OldSpace* Heap::old_pointer_space_ = NULL;
65OldSpace* Heap::old_data_space_ = NULL;
66OldSpace* Heap::code_space_ = NULL;
67MapSpace* Heap::map_space_ = NULL;
68CellSpace* Heap::cell_space_ = NULL;
69LargeObjectSpace* Heap::lo_space_ = NULL;
70
John Reck59135872010-11-02 12:39:01 -070071static const intptr_t kMinimumPromotionLimit = 2 * MB;
72static const intptr_t kMinimumAllocationLimit = 8 * MB;
73
Ben Murdochf87a2032010-10-22 12:50:53 +010074intptr_t Heap::old_gen_promotion_limit_ = kMinimumPromotionLimit;
75intptr_t Heap::old_gen_allocation_limit_ = kMinimumAllocationLimit;
Steve Blocka7e24c12009-10-30 11:49:00 +000076
77int Heap::old_gen_exhausted_ = false;
78
79int Heap::amount_of_external_allocated_memory_ = 0;
80int Heap::amount_of_external_allocated_memory_at_last_global_gc_ = 0;
81
82// semispace_size_ should be a power of 2 and old_generation_size_ should be
83// a multiple of Page::kPageSize.
84#if defined(ANDROID)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080085static const int default_max_semispace_size_ = 2*MB;
Ben Murdochf87a2032010-10-22 12:50:53 +010086intptr_t Heap::max_old_generation_size_ = 192*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000087int Heap::initial_semispace_size_ = 128*KB;
Ben Murdochf87a2032010-10-22 12:50:53 +010088intptr_t Heap::code_range_size_ = 0;
Russell Brenner90bac252010-11-18 13:33:46 -080089intptr_t Heap::max_executable_size_ = max_old_generation_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +000090#elif defined(V8_TARGET_ARCH_X64)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080091static const int default_max_semispace_size_ = 16*MB;
Ben Murdochf87a2032010-10-22 12:50:53 +010092intptr_t Heap::max_old_generation_size_ = 1*GB;
Steve Blocka7e24c12009-10-30 11:49:00 +000093int Heap::initial_semispace_size_ = 1*MB;
Ben Murdochf87a2032010-10-22 12:50:53 +010094intptr_t Heap::code_range_size_ = 512*MB;
Russell Brenner90bac252010-11-18 13:33:46 -080095intptr_t Heap::max_executable_size_ = 256*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000096#else
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080097static const int default_max_semispace_size_ = 8*MB;
Ben Murdochf87a2032010-10-22 12:50:53 +010098intptr_t Heap::max_old_generation_size_ = 512*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +000099int Heap::initial_semispace_size_ = 512*KB;
Ben Murdochf87a2032010-10-22 12:50:53 +0100100intptr_t Heap::code_range_size_ = 0;
Russell Brenner90bac252010-11-18 13:33:46 -0800101intptr_t Heap::max_executable_size_ = 128*MB;
Steve Blocka7e24c12009-10-30 11:49:00 +0000102#endif
103
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800104// Allow build-time customization of the max semispace size. Building
105// V8 with snapshots and a non-default max semispace size is much
106// easier if you can define it as part of the build environment.
107#if defined(V8_MAX_SEMISPACE_SIZE)
108int Heap::max_semispace_size_ = V8_MAX_SEMISPACE_SIZE;
109#else
110int Heap::max_semispace_size_ = default_max_semispace_size_;
111#endif
112
Steve Block3ce2e202009-11-05 08:53:23 +0000113// The snapshot semispace size will be the default semispace size if
114// snapshotting is used and will be the requested semispace size as
115// set up by ConfigureHeap otherwise.
116int Heap::reserved_semispace_size_ = Heap::max_semispace_size_;
117
Steve Block6ded16b2010-05-10 14:33:55 +0100118List<Heap::GCPrologueCallbackPair> Heap::gc_prologue_callbacks_;
119List<Heap::GCEpilogueCallbackPair> Heap::gc_epilogue_callbacks_;
120
Steve Blocka7e24c12009-10-30 11:49:00 +0000121GCCallback Heap::global_gc_prologue_callback_ = NULL;
122GCCallback Heap::global_gc_epilogue_callback_ = NULL;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100123HeapObjectCallback Heap::gc_safe_size_of_old_object_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000124
125// Variables set based on semispace_size_ and old_generation_size_ in
126// ConfigureHeap.
Steve Block3ce2e202009-11-05 08:53:23 +0000127
128// Will be 4 * reserved_semispace_size_ to ensure that young
129// generation can be aligned to its size.
Steve Blocka7e24c12009-10-30 11:49:00 +0000130int Heap::survived_since_last_expansion_ = 0;
Ben Murdochf87a2032010-10-22 12:50:53 +0100131intptr_t Heap::external_allocation_limit_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000132
133Heap::HeapState Heap::gc_state_ = NOT_IN_GC;
134
135int Heap::mc_count_ = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100136int Heap::ms_count_ = 0;
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100137unsigned int Heap::gc_count_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000138
Leon Clarkef7060e22010-06-03 12:02:55 +0100139GCTracer* Heap::tracer_ = NULL;
140
Steve Block6ded16b2010-05-10 14:33:55 +0100141int Heap::unflattened_strings_length_ = 0;
142
Steve Blocka7e24c12009-10-30 11:49:00 +0000143int Heap::always_allocate_scope_depth_ = 0;
Steve Blockd0582a62009-12-15 09:54:21 +0000144int Heap::linear_allocation_scope_depth_ = 0;
Steve Block6ded16b2010-05-10 14:33:55 +0100145int Heap::contexts_disposed_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000146
Steve Block8defd9f2010-07-08 12:39:36 +0100147int Heap::young_survivors_after_last_gc_ = 0;
148int Heap::high_survival_rate_period_length_ = 0;
149double Heap::survival_rate_ = 0;
150Heap::SurvivalRateTrend Heap::previous_survival_rate_trend_ = Heap::STABLE;
151Heap::SurvivalRateTrend Heap::survival_rate_trend_ = Heap::STABLE;
152
Steve Blocka7e24c12009-10-30 11:49:00 +0000153#ifdef DEBUG
154bool Heap::allocation_allowed_ = true;
155
156int Heap::allocation_timeout_ = 0;
157bool Heap::disallow_allocation_failure_ = false;
158#endif // DEBUG
159
Ben Murdochf87a2032010-10-22 12:50:53 +0100160intptr_t GCTracer::alive_after_last_gc_ = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100161double GCTracer::last_gc_end_timestamp_ = 0.0;
162int GCTracer::max_gc_pause_ = 0;
Ben Murdochf87a2032010-10-22 12:50:53 +0100163intptr_t GCTracer::max_alive_after_gc_ = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +0100164int GCTracer::min_in_mutator_ = kMaxInt;
Steve Blocka7e24c12009-10-30 11:49:00 +0000165
Ben Murdochf87a2032010-10-22 12:50:53 +0100166intptr_t Heap::Capacity() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000167 if (!HasBeenSetup()) return 0;
168
169 return new_space_.Capacity() +
170 old_pointer_space_->Capacity() +
171 old_data_space_->Capacity() +
172 code_space_->Capacity() +
173 map_space_->Capacity() +
174 cell_space_->Capacity();
175}
176
177
Ben Murdochf87a2032010-10-22 12:50:53 +0100178intptr_t Heap::CommittedMemory() {
Steve Block3ce2e202009-11-05 08:53:23 +0000179 if (!HasBeenSetup()) return 0;
180
181 return new_space_.CommittedMemory() +
182 old_pointer_space_->CommittedMemory() +
183 old_data_space_->CommittedMemory() +
184 code_space_->CommittedMemory() +
185 map_space_->CommittedMemory() +
186 cell_space_->CommittedMemory() +
187 lo_space_->Size();
188}
189
Russell Brenner90bac252010-11-18 13:33:46 -0800190intptr_t Heap::CommittedMemoryExecutable() {
191 if (!HasBeenSetup()) return 0;
192
193 return MemoryAllocator::SizeExecutable();
194}
195
Steve Block3ce2e202009-11-05 08:53:23 +0000196
Ben Murdochf87a2032010-10-22 12:50:53 +0100197intptr_t Heap::Available() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000198 if (!HasBeenSetup()) return 0;
199
200 return new_space_.Available() +
201 old_pointer_space_->Available() +
202 old_data_space_->Available() +
203 code_space_->Available() +
204 map_space_->Available() +
205 cell_space_->Available();
206}
207
208
209bool Heap::HasBeenSetup() {
210 return old_pointer_space_ != NULL &&
211 old_data_space_ != NULL &&
212 code_space_ != NULL &&
213 map_space_ != NULL &&
214 cell_space_ != NULL &&
215 lo_space_ != NULL;
216}
217
218
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100219int Heap::GcSafeSizeOfOldObject(HeapObject* object) {
220 ASSERT(!Heap::InNewSpace(object)); // Code only works for old objects.
221 ASSERT(!MarkCompactCollector::are_map_pointers_encoded());
222 MapWord map_word = object->map_word();
223 map_word.ClearMark();
224 map_word.ClearOverflow();
225 return object->SizeFromMap(map_word.ToMap());
226}
227
228
229int Heap::GcSafeSizeOfOldObjectWithEncodedMap(HeapObject* object) {
230 ASSERT(!Heap::InNewSpace(object)); // Code only works for old objects.
231 ASSERT(MarkCompactCollector::are_map_pointers_encoded());
232 uint32_t marker = Memory::uint32_at(object->address());
233 if (marker == MarkCompactCollector::kSingleFreeEncoding) {
234 return kIntSize;
235 } else if (marker == MarkCompactCollector::kMultiFreeEncoding) {
236 return Memory::int_at(object->address() + kIntSize);
237 } else {
238 MapWord map_word = object->map_word();
239 Address map_address = map_word.DecodeMapAddress(Heap::map_space());
240 Map* map = reinterpret_cast<Map*>(HeapObject::FromAddress(map_address));
241 return object->SizeFromMap(map);
242 }
243}
244
245
Steve Blocka7e24c12009-10-30 11:49:00 +0000246GarbageCollector Heap::SelectGarbageCollector(AllocationSpace space) {
247 // Is global GC requested?
248 if (space != NEW_SPACE || FLAG_gc_global) {
249 Counters::gc_compactor_caused_by_request.Increment();
250 return MARK_COMPACTOR;
251 }
252
253 // Is enough data promoted to justify a global GC?
254 if (OldGenerationPromotionLimitReached()) {
255 Counters::gc_compactor_caused_by_promoted_data.Increment();
256 return MARK_COMPACTOR;
257 }
258
259 // Have allocation in OLD and LO failed?
260 if (old_gen_exhausted_) {
261 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
262 return MARK_COMPACTOR;
263 }
264
265 // Is there enough space left in OLD to guarantee that a scavenge can
266 // succeed?
267 //
268 // Note that MemoryAllocator->MaxAvailable() undercounts the memory available
269 // for object promotion. It counts only the bytes that the memory
270 // allocator has not yet allocated from the OS and assigned to any space,
271 // and does not count available bytes already in the old space or code
272 // space. Undercounting is safe---we may get an unrequested full GC when
273 // a scavenge would have succeeded.
274 if (MemoryAllocator::MaxAvailable() <= new_space_.Size()) {
275 Counters::gc_compactor_caused_by_oldspace_exhaustion.Increment();
276 return MARK_COMPACTOR;
277 }
278
279 // Default
280 return SCAVENGER;
281}
282
283
284// TODO(1238405): Combine the infrastructure for --heap-stats and
285// --log-gc to avoid the complicated preprocessor and flag testing.
286#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
287void Heap::ReportStatisticsBeforeGC() {
288 // Heap::ReportHeapStatistics will also log NewSpace statistics when
289 // compiled with ENABLE_LOGGING_AND_PROFILING and --log-gc is set. The
290 // following logic is used to avoid double logging.
291#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
292 if (FLAG_heap_stats || FLAG_log_gc) new_space_.CollectStatistics();
293 if (FLAG_heap_stats) {
294 ReportHeapStatistics("Before GC");
295 } else if (FLAG_log_gc) {
296 new_space_.ReportStatistics();
297 }
298 if (FLAG_heap_stats || FLAG_log_gc) new_space_.ClearHistograms();
299#elif defined(DEBUG)
300 if (FLAG_heap_stats) {
301 new_space_.CollectStatistics();
302 ReportHeapStatistics("Before GC");
303 new_space_.ClearHistograms();
304 }
305#elif defined(ENABLE_LOGGING_AND_PROFILING)
306 if (FLAG_log_gc) {
307 new_space_.CollectStatistics();
308 new_space_.ReportStatistics();
309 new_space_.ClearHistograms();
310 }
311#endif
312}
313
314
315#if defined(ENABLE_LOGGING_AND_PROFILING)
316void Heap::PrintShortHeapStatistics() {
317 if (!FLAG_trace_gc_verbose) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100318 PrintF("Memory allocator, used: %8" V8_PTR_PREFIX "d"
319 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000320 MemoryAllocator::Size(),
321 MemoryAllocator::Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100322 PrintF("New space, used: %8" V8_PTR_PREFIX "d"
323 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000324 Heap::new_space_.Size(),
325 new_space_.Available());
Ben Murdochf87a2032010-10-22 12:50:53 +0100326 PrintF("Old pointers, used: %8" V8_PTR_PREFIX "d"
327 ", available: %8" V8_PTR_PREFIX "d"
328 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000329 old_pointer_space_->Size(),
330 old_pointer_space_->Available(),
331 old_pointer_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100332 PrintF("Old data space, used: %8" V8_PTR_PREFIX "d"
333 ", available: %8" V8_PTR_PREFIX "d"
334 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000335 old_data_space_->Size(),
336 old_data_space_->Available(),
337 old_data_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100338 PrintF("Code space, used: %8" V8_PTR_PREFIX "d"
339 ", available: %8" V8_PTR_PREFIX "d"
340 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000341 code_space_->Size(),
342 code_space_->Available(),
343 code_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100344 PrintF("Map space, used: %8" V8_PTR_PREFIX "d"
345 ", available: %8" V8_PTR_PREFIX "d"
346 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000347 map_space_->Size(),
348 map_space_->Available(),
349 map_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100350 PrintF("Cell space, used: %8" V8_PTR_PREFIX "d"
351 ", available: %8" V8_PTR_PREFIX "d"
352 ", waste: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000353 cell_space_->Size(),
354 cell_space_->Available(),
355 cell_space_->Waste());
Ben Murdochf87a2032010-10-22 12:50:53 +0100356 PrintF("Large object space, used: %8" V8_PTR_PREFIX "d"
357 ", available: %8" V8_PTR_PREFIX "d\n",
Steve Block3ce2e202009-11-05 08:53:23 +0000358 lo_space_->Size(),
359 lo_space_->Available());
Steve Blocka7e24c12009-10-30 11:49:00 +0000360}
361#endif
362
363
364// TODO(1238405): Combine the infrastructure for --heap-stats and
365// --log-gc to avoid the complicated preprocessor and flag testing.
366void Heap::ReportStatisticsAfterGC() {
367 // Similar to the before GC, we use some complicated logic to ensure that
368 // NewSpace statistics are logged exactly once when --log-gc is turned on.
369#if defined(DEBUG) && defined(ENABLE_LOGGING_AND_PROFILING)
370 if (FLAG_heap_stats) {
371 new_space_.CollectStatistics();
372 ReportHeapStatistics("After GC");
373 } else if (FLAG_log_gc) {
374 new_space_.ReportStatistics();
375 }
376#elif defined(DEBUG)
377 if (FLAG_heap_stats) ReportHeapStatistics("After GC");
378#elif defined(ENABLE_LOGGING_AND_PROFILING)
379 if (FLAG_log_gc) new_space_.ReportStatistics();
380#endif
381}
382#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
383
384
385void Heap::GarbageCollectionPrologue() {
386 TranscendentalCache::Clear();
Steve Block6ded16b2010-05-10 14:33:55 +0100387 ClearJSFunctionResultCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000388 gc_count_++;
Steve Block6ded16b2010-05-10 14:33:55 +0100389 unflattened_strings_length_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000390#ifdef DEBUG
391 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
392 allow_allocation(false);
393
394 if (FLAG_verify_heap) {
395 Verify();
396 }
397
398 if (FLAG_gc_verbose) Print();
Steve Blocka7e24c12009-10-30 11:49:00 +0000399#endif
400
401#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
402 ReportStatisticsBeforeGC();
403#endif
Steve Block1e0659c2011-05-24 12:43:12 +0100404
405 LiveObjectList::GCPrologue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000406}
407
Ben Murdochf87a2032010-10-22 12:50:53 +0100408intptr_t Heap::SizeOfObjects() {
409 intptr_t total = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000410 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +0000411 for (Space* space = spaces.next(); space != NULL; space = spaces.next()) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800412 total += space->SizeOfObjects();
Steve Blocka7e24c12009-10-30 11:49:00 +0000413 }
414 return total;
415}
416
417void Heap::GarbageCollectionEpilogue() {
Steve Block1e0659c2011-05-24 12:43:12 +0100418 LiveObjectList::GCEpilogue();
Steve Blocka7e24c12009-10-30 11:49:00 +0000419#ifdef DEBUG
420 allow_allocation(true);
421 ZapFromSpace();
422
423 if (FLAG_verify_heap) {
424 Verify();
425 }
426
427 if (FLAG_print_global_handles) GlobalHandles::Print();
428 if (FLAG_print_handles) PrintHandles();
429 if (FLAG_gc_verbose) Print();
430 if (FLAG_code_stats) ReportCodeStatistics("After GC");
431#endif
432
Ben Murdochf87a2032010-10-22 12:50:53 +0100433 Counters::alive_after_last_gc.Set(static_cast<int>(SizeOfObjects()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000434
435 Counters::symbol_table_capacity.Set(symbol_table()->Capacity());
436 Counters::number_of_symbols.Set(symbol_table()->NumberOfElements());
437#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
438 ReportStatisticsAfterGC();
439#endif
440#ifdef ENABLE_DEBUGGER_SUPPORT
441 Debug::AfterGarbageCollection();
442#endif
443}
444
445
John Reck59135872010-11-02 12:39:01 -0700446void Heap::CollectAllGarbage(bool force_compaction) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000447 // Since we are ignoring the return value, the exact choice of space does
448 // not matter, so long as we do not specify NEW_SPACE, which would not
449 // cause a full GC.
450 MarkCompactCollector::SetForceCompaction(force_compaction);
John Reck59135872010-11-02 12:39:01 -0700451 CollectGarbage(OLD_POINTER_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000452 MarkCompactCollector::SetForceCompaction(false);
453}
454
455
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800456void Heap::CollectAllAvailableGarbage() {
457 // Since we are ignoring the return value, the exact choice of space does
458 // not matter, so long as we do not specify NEW_SPACE, which would not
459 // cause a full GC.
460 MarkCompactCollector::SetForceCompaction(true);
461
462 // Major GC would invoke weak handle callbacks on weakly reachable
463 // handles, but won't collect weakly reachable objects until next
464 // major GC. Therefore if we collect aggressively and weak handle callback
465 // has been invoked, we rerun major GC to release objects which become
466 // garbage.
467 // Note: as weak callbacks can execute arbitrary code, we cannot
468 // hope that eventually there will be no weak callbacks invocations.
469 // Therefore stop recollecting after several attempts.
470 const int kMaxNumberOfAttempts = 7;
471 for (int attempt = 0; attempt < kMaxNumberOfAttempts; attempt++) {
472 if (!CollectGarbage(OLD_POINTER_SPACE, MARK_COMPACTOR)) {
473 break;
474 }
475 }
476 MarkCompactCollector::SetForceCompaction(false);
477}
478
479
480bool Heap::CollectGarbage(AllocationSpace space, GarbageCollector collector) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000481 // The VM is in the GC state until exiting this function.
482 VMState state(GC);
483
484#ifdef DEBUG
485 // Reset the allocation timeout to the GC interval, but make sure to
486 // allow at least a few allocations after a collection. The reason
487 // for this is that we have a lot of allocation sequences and we
488 // assume that a garbage collection will allow the subsequent
489 // allocation attempts to go through.
490 allocation_timeout_ = Max(6, FLAG_gc_interval);
491#endif
492
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800493 bool next_gc_likely_to_collect_more = false;
494
Steve Blocka7e24c12009-10-30 11:49:00 +0000495 { GCTracer tracer;
496 GarbageCollectionPrologue();
497 // The GC count was incremented in the prologue. Tell the tracer about
498 // it.
499 tracer.set_gc_count(gc_count_);
500
Steve Blocka7e24c12009-10-30 11:49:00 +0000501 // Tell the tracer which collector we've selected.
502 tracer.set_collector(collector);
503
504 HistogramTimer* rate = (collector == SCAVENGER)
505 ? &Counters::gc_scavenger
506 : &Counters::gc_compactor;
507 rate->Start();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800508 next_gc_likely_to_collect_more =
509 PerformGarbageCollection(collector, &tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000510 rate->Stop();
511
512 GarbageCollectionEpilogue();
513 }
514
515
516#ifdef ENABLE_LOGGING_AND_PROFILING
517 if (FLAG_log_gc) HeapProfiler::WriteSample();
518#endif
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800519
520 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000521}
522
523
524void Heap::PerformScavenge() {
525 GCTracer tracer;
John Reck59135872010-11-02 12:39:01 -0700526 PerformGarbageCollection(SCAVENGER, &tracer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000527}
528
529
530#ifdef DEBUG
531// Helper class for verifying the symbol table.
532class SymbolTableVerifier : public ObjectVisitor {
533 public:
534 SymbolTableVerifier() { }
535 void VisitPointers(Object** start, Object** end) {
536 // Visit all HeapObject pointers in [start, end).
537 for (Object** p = start; p < end; p++) {
538 if ((*p)->IsHeapObject()) {
539 // Check that the symbol is actually a symbol.
540 ASSERT((*p)->IsNull() || (*p)->IsUndefined() || (*p)->IsSymbol());
541 }
542 }
543 }
544};
545#endif // DEBUG
546
547
548static void VerifySymbolTable() {
549#ifdef DEBUG
550 SymbolTableVerifier verifier;
551 Heap::symbol_table()->IterateElements(&verifier);
552#endif // DEBUG
553}
554
555
Leon Clarkee46be812010-01-19 14:06:41 +0000556void Heap::ReserveSpace(
557 int new_space_size,
558 int pointer_space_size,
559 int data_space_size,
560 int code_space_size,
561 int map_space_size,
562 int cell_space_size,
563 int large_object_size) {
564 NewSpace* new_space = Heap::new_space();
565 PagedSpace* old_pointer_space = Heap::old_pointer_space();
566 PagedSpace* old_data_space = Heap::old_data_space();
567 PagedSpace* code_space = Heap::code_space();
568 PagedSpace* map_space = Heap::map_space();
569 PagedSpace* cell_space = Heap::cell_space();
570 LargeObjectSpace* lo_space = Heap::lo_space();
571 bool gc_performed = true;
572 while (gc_performed) {
573 gc_performed = false;
574 if (!new_space->ReserveSpace(new_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100575 Heap::CollectGarbage(NEW_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000576 gc_performed = true;
577 }
578 if (!old_pointer_space->ReserveSpace(pointer_space_size)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100579 Heap::CollectGarbage(OLD_POINTER_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000580 gc_performed = true;
581 }
582 if (!(old_data_space->ReserveSpace(data_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100583 Heap::CollectGarbage(OLD_DATA_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000584 gc_performed = true;
585 }
586 if (!(code_space->ReserveSpace(code_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100587 Heap::CollectGarbage(CODE_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000588 gc_performed = true;
589 }
590 if (!(map_space->ReserveSpace(map_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100591 Heap::CollectGarbage(MAP_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000592 gc_performed = true;
593 }
594 if (!(cell_space->ReserveSpace(cell_space_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100595 Heap::CollectGarbage(CELL_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000596 gc_performed = true;
597 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100598 // We add a slack-factor of 2 in order to have space for a series of
599 // large-object allocations that are only just larger than the page size.
Leon Clarkee46be812010-01-19 14:06:41 +0000600 large_object_size *= 2;
601 // The ReserveSpace method on the large object space checks how much
602 // we can expand the old generation. This includes expansion caused by
603 // allocation in the other spaces.
604 large_object_size += cell_space_size + map_space_size + code_space_size +
605 data_space_size + pointer_space_size;
606 if (!(lo_space->ReserveSpace(large_object_size))) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100607 Heap::CollectGarbage(LO_SPACE);
Leon Clarkee46be812010-01-19 14:06:41 +0000608 gc_performed = true;
609 }
610 }
611}
612
613
Steve Blocka7e24c12009-10-30 11:49:00 +0000614void Heap::EnsureFromSpaceIsCommitted() {
615 if (new_space_.CommitFromSpaceIfNeeded()) return;
616
617 // Committing memory to from space failed.
618 // Try shrinking and try again.
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100619 PagedSpaces spaces;
620 for (PagedSpace* space = spaces.next();
621 space != NULL;
622 space = spaces.next()) {
623 space->RelinkPageListInChunkOrder(true);
624 }
625
Steve Blocka7e24c12009-10-30 11:49:00 +0000626 Shrink();
627 if (new_space_.CommitFromSpaceIfNeeded()) return;
628
629 // Committing memory to from space failed again.
630 // Memory is exhausted and we will die.
631 V8::FatalProcessOutOfMemory("Committing semi space failed.");
632}
633
634
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800635void Heap::ClearJSFunctionResultCaches() {
636 if (Bootstrapper::IsActive()) return;
Steve Block6ded16b2010-05-10 14:33:55 +0100637
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800638 Object* context = global_contexts_list_;
639 while (!context->IsUndefined()) {
640 // Get the caches for this context:
Steve Block6ded16b2010-05-10 14:33:55 +0100641 FixedArray* caches =
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800642 Context::cast(context)->jsfunction_result_caches();
643 // Clear the caches:
Steve Block6ded16b2010-05-10 14:33:55 +0100644 int length = caches->length();
645 for (int i = 0; i < length; i++) {
646 JSFunctionResultCache::cast(caches->get(i))->Clear();
647 }
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800648 // Get the next context:
649 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
Steve Block6ded16b2010-05-10 14:33:55 +0100650 }
Steve Block6ded16b2010-05-10 14:33:55 +0100651}
652
653
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100654void Heap::ClearNormalizedMapCaches() {
655 if (Bootstrapper::IsActive()) return;
Ben Murdochf87a2032010-10-22 12:50:53 +0100656
657 Object* context = global_contexts_list_;
658 while (!context->IsUndefined()) {
659 Context::cast(context)->normalized_map_cache()->Clear();
660 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
661 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100662}
663
664
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100665#ifdef DEBUG
666
667enum PageWatermarkValidity {
668 ALL_VALID,
669 ALL_INVALID
670};
671
672static void VerifyPageWatermarkValidity(PagedSpace* space,
673 PageWatermarkValidity validity) {
674 PageIterator it(space, PageIterator::PAGES_IN_USE);
675 bool expected_value = (validity == ALL_VALID);
676 while (it.has_next()) {
677 Page* page = it.next();
678 ASSERT(page->IsWatermarkValid() == expected_value);
679 }
680}
681#endif
682
Steve Block8defd9f2010-07-08 12:39:36 +0100683void Heap::UpdateSurvivalRateTrend(int start_new_space_size) {
684 double survival_rate =
685 (static_cast<double>(young_survivors_after_last_gc_) * 100) /
686 start_new_space_size;
687
688 if (survival_rate > kYoungSurvivalRateThreshold) {
689 high_survival_rate_period_length_++;
690 } else {
691 high_survival_rate_period_length_ = 0;
692 }
693
694 double survival_rate_diff = survival_rate_ - survival_rate;
695
696 if (survival_rate_diff > kYoungSurvivalRateAllowedDeviation) {
697 set_survival_rate_trend(DECREASING);
698 } else if (survival_rate_diff < -kYoungSurvivalRateAllowedDeviation) {
699 set_survival_rate_trend(INCREASING);
700 } else {
701 set_survival_rate_trend(STABLE);
702 }
703
704 survival_rate_ = survival_rate;
705}
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100706
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800707bool Heap::PerformGarbageCollection(GarbageCollector collector,
John Reck59135872010-11-02 12:39:01 -0700708 GCTracer* tracer) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800709 bool next_gc_likely_to_collect_more = false;
710
Ben Murdochf87a2032010-10-22 12:50:53 +0100711 if (collector != SCAVENGER) {
712 PROFILE(CodeMovingGCEvent());
713 }
714
Steve Blocka7e24c12009-10-30 11:49:00 +0000715 VerifySymbolTable();
716 if (collector == MARK_COMPACTOR && global_gc_prologue_callback_) {
717 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100718 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000719 global_gc_prologue_callback_();
720 }
Steve Block6ded16b2010-05-10 14:33:55 +0100721
722 GCType gc_type =
723 collector == MARK_COMPACTOR ? kGCTypeMarkSweepCompact : kGCTypeScavenge;
724
725 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
726 if (gc_type & gc_prologue_callbacks_[i].gc_type) {
727 gc_prologue_callbacks_[i].callback(gc_type, kNoGCCallbackFlags);
728 }
729 }
730
Steve Blocka7e24c12009-10-30 11:49:00 +0000731 EnsureFromSpaceIsCommitted();
Steve Block6ded16b2010-05-10 14:33:55 +0100732
Ben Murdochf87a2032010-10-22 12:50:53 +0100733 int start_new_space_size = Heap::new_space()->SizeAsInt();
Steve Block8defd9f2010-07-08 12:39:36 +0100734
Steve Blocka7e24c12009-10-30 11:49:00 +0000735 if (collector == MARK_COMPACTOR) {
Steve Block6ded16b2010-05-10 14:33:55 +0100736 // Perform mark-sweep with optional compaction.
Steve Blocka7e24c12009-10-30 11:49:00 +0000737 MarkCompact(tracer);
738
Steve Block8defd9f2010-07-08 12:39:36 +0100739 bool high_survival_rate_during_scavenges = IsHighSurvivalRate() &&
740 IsStableOrIncreasingSurvivalTrend();
741
742 UpdateSurvivalRateTrend(start_new_space_size);
743
John Reck59135872010-11-02 12:39:01 -0700744 intptr_t old_gen_size = PromotedSpaceSize();
745 old_gen_promotion_limit_ =
746 old_gen_size + Max(kMinimumPromotionLimit, old_gen_size / 3);
747 old_gen_allocation_limit_ =
748 old_gen_size + Max(kMinimumAllocationLimit, old_gen_size / 2);
Steve Block8defd9f2010-07-08 12:39:36 +0100749
John Reck59135872010-11-02 12:39:01 -0700750 if (high_survival_rate_during_scavenges &&
751 IsStableOrIncreasingSurvivalTrend()) {
752 // Stable high survival rates of young objects both during partial and
753 // full collection indicate that mutator is either building or modifying
754 // a structure with a long lifetime.
755 // In this case we aggressively raise old generation memory limits to
756 // postpone subsequent mark-sweep collection and thus trade memory
757 // space for the mutation speed.
758 old_gen_promotion_limit_ *= 2;
759 old_gen_allocation_limit_ *= 2;
Steve Block8defd9f2010-07-08 12:39:36 +0100760 }
761
John Reck59135872010-11-02 12:39:01 -0700762 old_gen_exhausted_ = false;
Steve Block6ded16b2010-05-10 14:33:55 +0100763 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +0100764 tracer_ = tracer;
Steve Block6ded16b2010-05-10 14:33:55 +0100765 Scavenge();
Leon Clarkef7060e22010-06-03 12:02:55 +0100766 tracer_ = NULL;
Steve Block8defd9f2010-07-08 12:39:36 +0100767
768 UpdateSurvivalRateTrend(start_new_space_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000769 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000770
771 Counters::objs_since_last_young.Set(0);
772
John Reck59135872010-11-02 12:39:01 -0700773 if (collector == MARK_COMPACTOR) {
774 DisableAssertNoAllocation allow_allocation;
775 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800776 next_gc_likely_to_collect_more =
777 GlobalHandles::PostGarbageCollectionProcessing();
John Reck59135872010-11-02 12:39:01 -0700778 }
779
Steve Block3ce2e202009-11-05 08:53:23 +0000780 // Update relocatables.
781 Relocatable::PostGarbageCollectionProcessing();
Steve Blocka7e24c12009-10-30 11:49:00 +0000782
783 if (collector == MARK_COMPACTOR) {
784 // Register the amount of external allocated memory.
785 amount_of_external_allocated_memory_at_last_global_gc_ =
786 amount_of_external_allocated_memory_;
787 }
788
Steve Block6ded16b2010-05-10 14:33:55 +0100789 GCCallbackFlags callback_flags = tracer->is_compacting()
790 ? kGCCallbackFlagCompacted
791 : kNoGCCallbackFlags;
792 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
793 if (gc_type & gc_epilogue_callbacks_[i].gc_type) {
794 gc_epilogue_callbacks_[i].callback(gc_type, callback_flags);
795 }
796 }
797
Steve Blocka7e24c12009-10-30 11:49:00 +0000798 if (collector == MARK_COMPACTOR && global_gc_epilogue_callback_) {
799 ASSERT(!allocation_allowed_);
Leon Clarkef7060e22010-06-03 12:02:55 +0100800 GCTracer::Scope scope(tracer, GCTracer::Scope::EXTERNAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000801 global_gc_epilogue_callback_();
802 }
803 VerifySymbolTable();
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800804
805 return next_gc_likely_to_collect_more;
Steve Blocka7e24c12009-10-30 11:49:00 +0000806}
807
808
Steve Blocka7e24c12009-10-30 11:49:00 +0000809void Heap::MarkCompact(GCTracer* tracer) {
810 gc_state_ = MARK_COMPACT;
Steve Blocka7e24c12009-10-30 11:49:00 +0000811 LOG(ResourceEvent("markcompact", "begin"));
812
813 MarkCompactCollector::Prepare(tracer);
814
815 bool is_compacting = MarkCompactCollector::IsCompacting();
816
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100817 if (is_compacting) {
818 mc_count_++;
819 } else {
820 ms_count_++;
821 }
822 tracer->set_full_gc_count(mc_count_ + ms_count_);
823
Steve Blocka7e24c12009-10-30 11:49:00 +0000824 MarkCompactPrologue(is_compacting);
825
826 MarkCompactCollector::CollectGarbage();
827
Steve Blocka7e24c12009-10-30 11:49:00 +0000828 LOG(ResourceEvent("markcompact", "end"));
829
830 gc_state_ = NOT_IN_GC;
831
832 Shrink();
833
834 Counters::objs_since_last_full.Set(0);
Steve Block6ded16b2010-05-10 14:33:55 +0100835
836 contexts_disposed_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000837}
838
839
840void Heap::MarkCompactPrologue(bool is_compacting) {
841 // At any old GC clear the keyed lookup cache to enable collection of unused
842 // maps.
843 KeyedLookupCache::Clear();
844 ContextSlotCache::Clear();
845 DescriptorLookupCache::Clear();
846
847 CompilationCache::MarkCompactPrologue();
848
Kristian Monsen25f61362010-05-21 11:50:48 +0100849 CompletelyClearInstanceofCache();
850
Leon Clarkee46be812010-01-19 14:06:41 +0000851 if (is_compacting) FlushNumberStringCache();
Steve Blocka7e24c12009-10-30 11:49:00 +0000852
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100853 ClearNormalizedMapCaches();
Steve Blocka7e24c12009-10-30 11:49:00 +0000854}
855
856
857Object* Heap::FindCodeObject(Address a) {
John Reck59135872010-11-02 12:39:01 -0700858 Object* obj = NULL; // Initialization to please compiler.
859 { MaybeObject* maybe_obj = code_space_->FindObject(a);
860 if (!maybe_obj->ToObject(&obj)) {
861 obj = lo_space_->FindObject(a)->ToObjectUnchecked();
862 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000863 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000864 return obj;
865}
866
867
868// Helper class for copying HeapObjects
869class ScavengeVisitor: public ObjectVisitor {
870 public:
871
872 void VisitPointer(Object** p) { ScavengePointer(p); }
873
874 void VisitPointers(Object** start, Object** end) {
875 // Copy all HeapObject pointers in [start, end)
876 for (Object** p = start; p < end; p++) ScavengePointer(p);
877 }
878
879 private:
880 void ScavengePointer(Object** p) {
881 Object* object = *p;
882 if (!Heap::InNewSpace(object)) return;
883 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
884 reinterpret_cast<HeapObject*>(object));
885 }
886};
887
888
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100889// A queue of objects promoted during scavenge. Each object is accompanied
890// by it's size to avoid dereferencing a map pointer for scanning.
Steve Blocka7e24c12009-10-30 11:49:00 +0000891class PromotionQueue {
892 public:
893 void Initialize(Address start_address) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100894 front_ = rear_ = reinterpret_cast<intptr_t*>(start_address);
Steve Blocka7e24c12009-10-30 11:49:00 +0000895 }
896
897 bool is_empty() { return front_ <= rear_; }
898
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100899 void insert(HeapObject* target, int size) {
900 *(--rear_) = reinterpret_cast<intptr_t>(target);
901 *(--rear_) = size;
Steve Blocka7e24c12009-10-30 11:49:00 +0000902 // Assert no overflow into live objects.
903 ASSERT(reinterpret_cast<Address>(rear_) >= Heap::new_space()->top());
904 }
905
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100906 void remove(HeapObject** target, int* size) {
907 *target = reinterpret_cast<HeapObject*>(*(--front_));
908 *size = static_cast<int>(*(--front_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000909 // Assert no underflow.
910 ASSERT(front_ >= rear_);
911 }
912
913 private:
914 // The front of the queue is higher in memory than the rear.
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100915 intptr_t* front_;
916 intptr_t* rear_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000917};
918
919
920// Shared state read by the scavenge collector and set by ScavengeObject.
921static PromotionQueue promotion_queue;
922
923
924#ifdef DEBUG
925// Visitor class to verify pointers in code or data space do not point into
926// new space.
927class VerifyNonPointerSpacePointersVisitor: public ObjectVisitor {
928 public:
929 void VisitPointers(Object** start, Object**end) {
930 for (Object** current = start; current < end; current++) {
931 if ((*current)->IsHeapObject()) {
932 ASSERT(!Heap::InNewSpace(HeapObject::cast(*current)));
933 }
934 }
935 }
936};
937
938
939static void VerifyNonPointerSpacePointers() {
940 // Verify that there are no pointers to new space in spaces where we
941 // do not expect them.
942 VerifyNonPointerSpacePointersVisitor v;
943 HeapObjectIterator code_it(Heap::code_space());
Leon Clarked91b9f72010-01-27 17:25:45 +0000944 for (HeapObject* object = code_it.next();
945 object != NULL; object = code_it.next())
Steve Blocka7e24c12009-10-30 11:49:00 +0000946 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000947
948 HeapObjectIterator data_it(Heap::old_data_space());
Leon Clarked91b9f72010-01-27 17:25:45 +0000949 for (HeapObject* object = data_it.next();
950 object != NULL; object = data_it.next())
951 object->Iterate(&v);
Steve Blocka7e24c12009-10-30 11:49:00 +0000952}
953#endif
954
955
Steve Block6ded16b2010-05-10 14:33:55 +0100956void Heap::CheckNewSpaceExpansionCriteria() {
957 if (new_space_.Capacity() < new_space_.MaximumCapacity() &&
958 survived_since_last_expansion_ > new_space_.Capacity()) {
959 // Grow the size of new space if there is room to grow and enough
960 // data has survived scavenge since the last expansion.
961 new_space_.Grow();
962 survived_since_last_expansion_ = 0;
963 }
964}
965
966
Steve Blocka7e24c12009-10-30 11:49:00 +0000967void Heap::Scavenge() {
968#ifdef DEBUG
969 if (FLAG_enable_slow_asserts) VerifyNonPointerSpacePointers();
970#endif
971
972 gc_state_ = SCAVENGE;
973
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100974 Page::FlipMeaningOfInvalidatedWatermarkFlag();
975#ifdef DEBUG
976 VerifyPageWatermarkValidity(old_pointer_space_, ALL_VALID);
977 VerifyPageWatermarkValidity(map_space_, ALL_VALID);
978#endif
979
980 // We do not update an allocation watermark of the top page during linear
981 // allocation to avoid overhead. So to maintain the watermark invariant
982 // we have to manually cache the watermark and mark the top page as having an
983 // invalid watermark. This guarantees that dirty regions iteration will use a
984 // correct watermark even if a linear allocation happens.
985 old_pointer_space_->FlushTopPageWatermark();
986 map_space_->FlushTopPageWatermark();
987
Steve Blocka7e24c12009-10-30 11:49:00 +0000988 // Implements Cheney's copying algorithm
989 LOG(ResourceEvent("scavenge", "begin"));
990
991 // Clear descriptor cache.
992 DescriptorLookupCache::Clear();
993
994 // Used for updating survived_since_last_expansion_ at function end.
Ben Murdochf87a2032010-10-22 12:50:53 +0100995 intptr_t survived_watermark = PromotedSpaceSize();
Steve Blocka7e24c12009-10-30 11:49:00 +0000996
Steve Block6ded16b2010-05-10 14:33:55 +0100997 CheckNewSpaceExpansionCriteria();
Steve Blocka7e24c12009-10-30 11:49:00 +0000998
999 // Flip the semispaces. After flipping, to space is empty, from space has
1000 // live objects.
1001 new_space_.Flip();
1002 new_space_.ResetAllocationInfo();
1003
1004 // We need to sweep newly copied objects which can be either in the
1005 // to space or promoted to the old generation. For to-space
1006 // objects, we treat the bottom of the to space as a queue. Newly
1007 // copied and unswept objects lie between a 'front' mark and the
1008 // allocation pointer.
1009 //
1010 // Promoted objects can go into various old-generation spaces, and
1011 // can be allocated internally in the spaces (from the free list).
1012 // We treat the top of the to space as a queue of addresses of
1013 // promoted objects. The addresses of newly promoted and unswept
1014 // objects lie between a 'front' mark and a 'rear' mark that is
1015 // updated as a side effect of promoting an object.
1016 //
1017 // There is guaranteed to be enough room at the top of the to space
1018 // for the addresses of promoted objects: every object promoted
1019 // frees up its size in bytes from the top of the new space, and
1020 // objects are at least one pointer in size.
1021 Address new_space_front = new_space_.ToSpaceLow();
1022 promotion_queue.Initialize(new_space_.ToSpaceHigh());
1023
1024 ScavengeVisitor scavenge_visitor;
1025 // Copy roots.
Leon Clarkee46be812010-01-19 14:06:41 +00001026 IterateRoots(&scavenge_visitor, VISIT_ALL_IN_SCAVENGE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001027
1028 // Copy objects reachable from the old generation. By definition,
1029 // there are no intergenerational pointers in code or data spaces.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001030 IterateDirtyRegions(old_pointer_space_,
1031 &IteratePointersInDirtyRegion,
1032 &ScavengePointer,
1033 WATERMARK_CAN_BE_INVALID);
1034
1035 IterateDirtyRegions(map_space_,
1036 &IteratePointersInDirtyMapsRegion,
1037 &ScavengePointer,
1038 WATERMARK_CAN_BE_INVALID);
1039
1040 lo_space_->IterateDirtyRegions(&ScavengePointer);
Steve Blocka7e24c12009-10-30 11:49:00 +00001041
1042 // Copy objects reachable from cells by scavenging cell values directly.
1043 HeapObjectIterator cell_iterator(cell_space_);
Leon Clarked91b9f72010-01-27 17:25:45 +00001044 for (HeapObject* cell = cell_iterator.next();
1045 cell != NULL; cell = cell_iterator.next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001046 if (cell->IsJSGlobalPropertyCell()) {
1047 Address value_address =
1048 reinterpret_cast<Address>(cell) +
1049 (JSGlobalPropertyCell::kValueOffset - kHeapObjectTag);
1050 scavenge_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
1051 }
1052 }
1053
Ben Murdochf87a2032010-10-22 12:50:53 +01001054 // Scavenge object reachable from the global contexts list directly.
1055 scavenge_visitor.VisitPointer(BitCast<Object**>(&global_contexts_list_));
1056
Leon Clarkee46be812010-01-19 14:06:41 +00001057 new_space_front = DoScavenge(&scavenge_visitor, new_space_front);
1058
Steve Block6ded16b2010-05-10 14:33:55 +01001059 UpdateNewSpaceReferencesInExternalStringTable(
1060 &UpdateNewSpaceReferenceInExternalStringTableEntry);
1061
Steve Block1e0659c2011-05-24 12:43:12 +01001062 LiveObjectList::UpdateReferencesForScavengeGC();
Ben Murdoche0cee9b2011-05-25 10:26:03 +01001063 RuntimeProfiler::UpdateSamplesAfterScavenge();
Steve Block1e0659c2011-05-24 12:43:12 +01001064
Leon Clarkee46be812010-01-19 14:06:41 +00001065 ASSERT(new_space_front == new_space_.top());
1066
1067 // Set age mark.
1068 new_space_.set_age_mark(new_space_.top());
1069
1070 // Update how much has survived scavenge.
Ben Murdochf87a2032010-10-22 12:50:53 +01001071 IncrementYoungSurvivorsCounter(static_cast<int>(
1072 (PromotedSpaceSize() - survived_watermark) + new_space_.Size()));
Leon Clarkee46be812010-01-19 14:06:41 +00001073
1074 LOG(ResourceEvent("scavenge", "end"));
1075
1076 gc_state_ = NOT_IN_GC;
1077}
1078
1079
Steve Block6ded16b2010-05-10 14:33:55 +01001080String* Heap::UpdateNewSpaceReferenceInExternalStringTableEntry(Object** p) {
1081 MapWord first_word = HeapObject::cast(*p)->map_word();
1082
1083 if (!first_word.IsForwardingAddress()) {
1084 // Unreachable external string can be finalized.
1085 FinalizeExternalString(String::cast(*p));
1086 return NULL;
1087 }
1088
1089 // String is still reachable.
1090 return String::cast(first_word.ToForwardingAddress());
1091}
1092
1093
1094void Heap::UpdateNewSpaceReferencesInExternalStringTable(
1095 ExternalStringTableUpdaterCallback updater_func) {
Leon Clarkee46be812010-01-19 14:06:41 +00001096 ExternalStringTable::Verify();
1097
1098 if (ExternalStringTable::new_space_strings_.is_empty()) return;
1099
1100 Object** start = &ExternalStringTable::new_space_strings_[0];
1101 Object** end = start + ExternalStringTable::new_space_strings_.length();
1102 Object** last = start;
1103
1104 for (Object** p = start; p < end; ++p) {
1105 ASSERT(Heap::InFromSpace(*p));
Steve Block6ded16b2010-05-10 14:33:55 +01001106 String* target = updater_func(p);
Leon Clarkee46be812010-01-19 14:06:41 +00001107
Steve Block6ded16b2010-05-10 14:33:55 +01001108 if (target == NULL) continue;
Leon Clarkee46be812010-01-19 14:06:41 +00001109
Leon Clarkee46be812010-01-19 14:06:41 +00001110 ASSERT(target->IsExternalString());
1111
1112 if (Heap::InNewSpace(target)) {
1113 // String is still in new space. Update the table entry.
1114 *last = target;
1115 ++last;
1116 } else {
1117 // String got promoted. Move it to the old string list.
1118 ExternalStringTable::AddOldString(target);
1119 }
1120 }
1121
1122 ASSERT(last <= end);
1123 ExternalStringTable::ShrinkNewStrings(static_cast<int>(last - start));
1124}
1125
1126
Ben Murdochb0fe1622011-05-05 13:52:32 +01001127static Object* ProcessFunctionWeakReferences(Object* function,
1128 WeakObjectRetainer* retainer) {
1129 Object* head = Heap::undefined_value();
1130 JSFunction* tail = NULL;
1131 Object* candidate = function;
1132 while (!candidate->IsUndefined()) {
1133 // Check whether to keep the candidate in the list.
1134 JSFunction* candidate_function = reinterpret_cast<JSFunction*>(candidate);
1135 Object* retain = retainer->RetainAs(candidate);
1136 if (retain != NULL) {
1137 if (head->IsUndefined()) {
1138 // First element in the list.
1139 head = candidate_function;
1140 } else {
1141 // Subsequent elements in the list.
1142 ASSERT(tail != NULL);
1143 tail->set_next_function_link(candidate_function);
1144 }
1145 // Retained function is new tail.
1146 tail = candidate_function;
1147 }
1148 // Move to next element in the list.
1149 candidate = candidate_function->next_function_link();
1150 }
1151
1152 // Terminate the list if there is one or more elements.
1153 if (tail != NULL) {
1154 tail->set_next_function_link(Heap::undefined_value());
1155 }
1156
1157 return head;
1158}
1159
1160
Ben Murdochf87a2032010-10-22 12:50:53 +01001161void Heap::ProcessWeakReferences(WeakObjectRetainer* retainer) {
1162 Object* head = undefined_value();
1163 Context* tail = NULL;
1164 Object* candidate = global_contexts_list_;
1165 while (!candidate->IsUndefined()) {
1166 // Check whether to keep the candidate in the list.
1167 Context* candidate_context = reinterpret_cast<Context*>(candidate);
1168 Object* retain = retainer->RetainAs(candidate);
1169 if (retain != NULL) {
1170 if (head->IsUndefined()) {
1171 // First element in the list.
1172 head = candidate_context;
1173 } else {
1174 // Subsequent elements in the list.
1175 ASSERT(tail != NULL);
1176 tail->set_unchecked(Context::NEXT_CONTEXT_LINK,
1177 candidate_context,
1178 UPDATE_WRITE_BARRIER);
1179 }
1180 // Retained context is new tail.
1181 tail = candidate_context;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001182
1183 // Process the weak list of optimized functions for the context.
1184 Object* function_list_head =
1185 ProcessFunctionWeakReferences(
1186 candidate_context->get(Context::OPTIMIZED_FUNCTIONS_LIST),
1187 retainer);
1188 candidate_context->set_unchecked(Context::OPTIMIZED_FUNCTIONS_LIST,
1189 function_list_head,
1190 UPDATE_WRITE_BARRIER);
Ben Murdochf87a2032010-10-22 12:50:53 +01001191 }
1192 // Move to next element in the list.
1193 candidate = candidate_context->get(Context::NEXT_CONTEXT_LINK);
1194 }
1195
1196 // Terminate the list if there is one or more elements.
1197 if (tail != NULL) {
1198 tail->set_unchecked(Context::NEXT_CONTEXT_LINK,
1199 Heap::undefined_value(),
1200 UPDATE_WRITE_BARRIER);
1201 }
1202
1203 // Update the head of the list of contexts.
1204 Heap::global_contexts_list_ = head;
1205}
1206
1207
Iain Merrick75681382010-08-19 15:07:18 +01001208class NewSpaceScavenger : public StaticNewSpaceVisitor<NewSpaceScavenger> {
1209 public:
1210 static inline void VisitPointer(Object** p) {
1211 Object* object = *p;
1212 if (!Heap::InNewSpace(object)) return;
1213 Heap::ScavengeObject(reinterpret_cast<HeapObject**>(p),
1214 reinterpret_cast<HeapObject*>(object));
1215 }
1216};
1217
1218
Leon Clarkee46be812010-01-19 14:06:41 +00001219Address Heap::DoScavenge(ObjectVisitor* scavenge_visitor,
1220 Address new_space_front) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 do {
1222 ASSERT(new_space_front <= new_space_.top());
1223
1224 // The addresses new_space_front and new_space_.top() define a
1225 // queue of unprocessed copied objects. Process them until the
1226 // queue is empty.
1227 while (new_space_front < new_space_.top()) {
1228 HeapObject* object = HeapObject::FromAddress(new_space_front);
Iain Merrick75681382010-08-19 15:07:18 +01001229 new_space_front += NewSpaceScavenger::IterateBody(object->map(), object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001230 }
1231
1232 // Promote and process all the to-be-promoted objects.
1233 while (!promotion_queue.is_empty()) {
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001234 HeapObject* target;
1235 int size;
1236 promotion_queue.remove(&target, &size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001237
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001238 // Promoted object might be already partially visited
1239 // during dirty regions iteration. Thus we search specificly
1240 // for pointers to from semispace instead of looking for pointers
1241 // to new space.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001242 ASSERT(!target->IsMap());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001243 IterateAndMarkPointersToFromSpace(target->address(),
1244 target->address() + size,
1245 &ScavengePointer);
Steve Blocka7e24c12009-10-30 11:49:00 +00001246 }
1247
1248 // Take another spin if there are now unswept objects in new space
1249 // (there are currently no more unswept promoted objects).
1250 } while (new_space_front < new_space_.top());
1251
Leon Clarkee46be812010-01-19 14:06:41 +00001252 return new_space_front;
Steve Blocka7e24c12009-10-30 11:49:00 +00001253}
1254
1255
Iain Merrick75681382010-08-19 15:07:18 +01001256class ScavengingVisitor : public StaticVisitorBase {
1257 public:
1258 static void Initialize() {
1259 table_.Register(kVisitSeqAsciiString, &EvacuateSeqAsciiString);
1260 table_.Register(kVisitSeqTwoByteString, &EvacuateSeqTwoByteString);
1261 table_.Register(kVisitShortcutCandidate, &EvacuateShortcutCandidate);
1262 table_.Register(kVisitByteArray, &EvacuateByteArray);
1263 table_.Register(kVisitFixedArray, &EvacuateFixedArray);
Ben Murdochf87a2032010-10-22 12:50:53 +01001264 table_.Register(kVisitGlobalContext,
1265 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1266 VisitSpecialized<Context::kSize>);
Iain Merrick75681382010-08-19 15:07:18 +01001267
1268 typedef ObjectEvacuationStrategy<POINTER_OBJECT> PointerObject;
1269
1270 table_.Register(kVisitConsString,
1271 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1272 VisitSpecialized<ConsString::kSize>);
1273
1274 table_.Register(kVisitSharedFunctionInfo,
1275 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1276 VisitSpecialized<SharedFunctionInfo::kSize>);
1277
1278 table_.Register(kVisitJSFunction,
1279 &ObjectEvacuationStrategy<POINTER_OBJECT>::
1280 VisitSpecialized<JSFunction::kSize>);
1281
1282 table_.RegisterSpecializations<ObjectEvacuationStrategy<DATA_OBJECT>,
1283 kVisitDataObject,
1284 kVisitDataObjectGeneric>();
1285
1286 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1287 kVisitJSObject,
1288 kVisitJSObjectGeneric>();
1289
1290 table_.RegisterSpecializations<ObjectEvacuationStrategy<POINTER_OBJECT>,
1291 kVisitStruct,
1292 kVisitStructGeneric>();
1293 }
1294
1295
1296 static inline void Scavenge(Map* map, HeapObject** slot, HeapObject* obj) {
1297 table_.GetVisitor(map)(map, slot, obj);
1298 }
1299
1300
1301 private:
1302 enum ObjectContents { DATA_OBJECT, POINTER_OBJECT };
1303 enum SizeRestriction { SMALL, UNKNOWN_SIZE };
1304
Steve Blocka7e24c12009-10-30 11:49:00 +00001305#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
Iain Merrick75681382010-08-19 15:07:18 +01001306 static void RecordCopiedObject(HeapObject* obj) {
1307 bool should_record = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001308#ifdef DEBUG
Iain Merrick75681382010-08-19 15:07:18 +01001309 should_record = FLAG_heap_stats;
Steve Blocka7e24c12009-10-30 11:49:00 +00001310#endif
1311#ifdef ENABLE_LOGGING_AND_PROFILING
Iain Merrick75681382010-08-19 15:07:18 +01001312 should_record = should_record || FLAG_log_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00001313#endif
Iain Merrick75681382010-08-19 15:07:18 +01001314 if (should_record) {
1315 if (Heap::new_space()->Contains(obj)) {
1316 Heap::new_space()->RecordAllocation(obj);
1317 } else {
1318 Heap::new_space()->RecordPromotion(obj);
1319 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001320 }
1321 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001322#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1323
Iain Merrick75681382010-08-19 15:07:18 +01001324 // Helper function used by CopyObject to copy a source object to an
1325 // allocated target object and update the forwarding pointer in the source
1326 // object. Returns the target object.
1327 INLINE(static HeapObject* MigrateObject(HeapObject* source,
1328 HeapObject* target,
1329 int size)) {
1330 // Copy the content of source to target.
1331 Heap::CopyBlock(target->address(), source->address(), size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001332
Iain Merrick75681382010-08-19 15:07:18 +01001333 // Set the forwarding address.
1334 source->set_map_word(MapWord::FromForwardingAddress(target));
Steve Blocka7e24c12009-10-30 11:49:00 +00001335
1336#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
Iain Merrick75681382010-08-19 15:07:18 +01001337 // Update NewSpace stats if necessary.
1338 RecordCopiedObject(target);
Steve Blocka7e24c12009-10-30 11:49:00 +00001339#endif
Iain Merrick75681382010-08-19 15:07:18 +01001340 HEAP_PROFILE(ObjectMoveEvent(source->address(), target->address()));
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001341#if defined(ENABLE_LOGGING_AND_PROFILING)
1342 if (Logger::is_logging() || CpuProfiler::is_profiling()) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01001343 if (target->IsSharedFunctionInfo()) {
1344 PROFILE(SFIMoveEvent(source->address(), target->address()));
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001345 }
1346 }
1347#endif
Iain Merrick75681382010-08-19 15:07:18 +01001348 return target;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001349 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001350
1351
Iain Merrick75681382010-08-19 15:07:18 +01001352 template<ObjectContents object_contents, SizeRestriction size_restriction>
1353 static inline void EvacuateObject(Map* map,
1354 HeapObject** slot,
1355 HeapObject* object,
1356 int object_size) {
1357 ASSERT((size_restriction != SMALL) ||
1358 (object_size <= Page::kMaxHeapObjectSize));
1359 ASSERT(object->Size() == object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001360
Iain Merrick75681382010-08-19 15:07:18 +01001361 if (Heap::ShouldBePromoted(object->address(), object_size)) {
John Reck59135872010-11-02 12:39:01 -07001362 MaybeObject* maybe_result;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001363
Iain Merrick75681382010-08-19 15:07:18 +01001364 if ((size_restriction != SMALL) &&
1365 (object_size > Page::kMaxHeapObjectSize)) {
John Reck59135872010-11-02 12:39:01 -07001366 maybe_result = Heap::lo_space()->AllocateRawFixedArray(object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001367 } else {
Iain Merrick75681382010-08-19 15:07:18 +01001368 if (object_contents == DATA_OBJECT) {
John Reck59135872010-11-02 12:39:01 -07001369 maybe_result = Heap::old_data_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001370 } else {
John Reck59135872010-11-02 12:39:01 -07001371 maybe_result = Heap::old_pointer_space()->AllocateRaw(object_size);
Iain Merrick75681382010-08-19 15:07:18 +01001372 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001373 }
1374
John Reck59135872010-11-02 12:39:01 -07001375 Object* result = NULL; // Initialization to please compiler.
1376 if (maybe_result->ToObject(&result)) {
Iain Merrick75681382010-08-19 15:07:18 +01001377 HeapObject* target = HeapObject::cast(result);
1378 *slot = MigrateObject(object, target, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001379
Iain Merrick75681382010-08-19 15:07:18 +01001380 if (object_contents == POINTER_OBJECT) {
1381 promotion_queue.insert(target, object_size);
1382 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001383
Iain Merrick75681382010-08-19 15:07:18 +01001384 Heap::tracer()->increment_promoted_objects_size(object_size);
1385 return;
1386 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001387 }
John Reck59135872010-11-02 12:39:01 -07001388 Object* result =
1389 Heap::new_space()->AllocateRaw(object_size)->ToObjectUnchecked();
Iain Merrick75681382010-08-19 15:07:18 +01001390 *slot = MigrateObject(object, HeapObject::cast(result), object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001391 return;
1392 }
1393
Iain Merrick75681382010-08-19 15:07:18 +01001394
1395 static inline void EvacuateFixedArray(Map* map,
1396 HeapObject** slot,
1397 HeapObject* object) {
1398 int object_size = FixedArray::BodyDescriptor::SizeOf(map, object);
1399 EvacuateObject<POINTER_OBJECT, UNKNOWN_SIZE>(map,
1400 slot,
1401 object,
1402 object_size);
1403 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001404
1405
Iain Merrick75681382010-08-19 15:07:18 +01001406 static inline void EvacuateByteArray(Map* map,
1407 HeapObject** slot,
1408 HeapObject* object) {
1409 int object_size = reinterpret_cast<ByteArray*>(object)->ByteArraySize();
1410 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1411 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001412
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001413
Iain Merrick75681382010-08-19 15:07:18 +01001414 static inline void EvacuateSeqAsciiString(Map* map,
1415 HeapObject** slot,
1416 HeapObject* object) {
1417 int object_size = SeqAsciiString::cast(object)->
1418 SeqAsciiStringSize(map->instance_type());
1419 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1420 }
1421
1422
1423 static inline void EvacuateSeqTwoByteString(Map* map,
1424 HeapObject** slot,
1425 HeapObject* object) {
1426 int object_size = SeqTwoByteString::cast(object)->
1427 SeqTwoByteStringSize(map->instance_type());
1428 EvacuateObject<DATA_OBJECT, UNKNOWN_SIZE>(map, slot, object, object_size);
1429 }
1430
1431
1432 static inline bool IsShortcutCandidate(int type) {
1433 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
1434 }
1435
1436 static inline void EvacuateShortcutCandidate(Map* map,
1437 HeapObject** slot,
1438 HeapObject* object) {
1439 ASSERT(IsShortcutCandidate(map->instance_type()));
1440
1441 if (ConsString::cast(object)->unchecked_second() == Heap::empty_string()) {
1442 HeapObject* first =
1443 HeapObject::cast(ConsString::cast(object)->unchecked_first());
1444
1445 *slot = first;
1446
1447 if (!Heap::InNewSpace(first)) {
1448 object->set_map_word(MapWord::FromForwardingAddress(first));
1449 return;
1450 }
1451
1452 MapWord first_word = first->map_word();
1453 if (first_word.IsForwardingAddress()) {
1454 HeapObject* target = first_word.ToForwardingAddress();
1455
1456 *slot = target;
1457 object->set_map_word(MapWord::FromForwardingAddress(target));
1458 return;
1459 }
1460
1461 Scavenge(first->map(), slot, first);
1462 object->set_map_word(MapWord::FromForwardingAddress(*slot));
1463 return;
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001464 }
Iain Merrick75681382010-08-19 15:07:18 +01001465
1466 int object_size = ConsString::kSize;
1467 EvacuateObject<POINTER_OBJECT, SMALL>(map, slot, object, object_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001468 }
1469
Iain Merrick75681382010-08-19 15:07:18 +01001470 template<ObjectContents object_contents>
1471 class ObjectEvacuationStrategy {
1472 public:
1473 template<int object_size>
1474 static inline void VisitSpecialized(Map* map,
1475 HeapObject** slot,
1476 HeapObject* object) {
1477 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1478 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001479
Iain Merrick75681382010-08-19 15:07:18 +01001480 static inline void Visit(Map* map,
1481 HeapObject** slot,
1482 HeapObject* object) {
1483 int object_size = map->instance_size();
1484 EvacuateObject<object_contents, SMALL>(map, slot, object, object_size);
1485 }
1486 };
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001487
Iain Merrick75681382010-08-19 15:07:18 +01001488 typedef void (*Callback)(Map* map, HeapObject** slot, HeapObject* object);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001489
Iain Merrick75681382010-08-19 15:07:18 +01001490 static VisitorDispatchTable<Callback> table_;
1491};
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001492
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001493
Iain Merrick75681382010-08-19 15:07:18 +01001494VisitorDispatchTable<ScavengingVisitor::Callback> ScavengingVisitor::table_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001495
1496
1497void Heap::ScavengeObjectSlow(HeapObject** p, HeapObject* object) {
1498 ASSERT(InFromSpace(object));
1499 MapWord first_word = object->map_word();
1500 ASSERT(!first_word.IsForwardingAddress());
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001501 Map* map = first_word.ToMap();
Iain Merrick75681382010-08-19 15:07:18 +01001502 ScavengingVisitor::Scavenge(map, p, object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001503}
1504
1505
1506void Heap::ScavengePointer(HeapObject** p) {
1507 ScavengeObject(p, *p);
1508}
1509
1510
John Reck59135872010-11-02 12:39:01 -07001511MaybeObject* Heap::AllocatePartialMap(InstanceType instance_type,
1512 int instance_size) {
1513 Object* result;
1514 { MaybeObject* maybe_result = AllocateRawMap();
1515 if (!maybe_result->ToObject(&result)) return maybe_result;
1516 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001517
1518 // Map::cast cannot be used due to uninitialized map field.
1519 reinterpret_cast<Map*>(result)->set_map(raw_unchecked_meta_map());
1520 reinterpret_cast<Map*>(result)->set_instance_type(instance_type);
1521 reinterpret_cast<Map*>(result)->set_instance_size(instance_size);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01001522 reinterpret_cast<Map*>(result)->
Iain Merrick75681382010-08-19 15:07:18 +01001523 set_visitor_id(
1524 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Steve Blocka7e24c12009-10-30 11:49:00 +00001525 reinterpret_cast<Map*>(result)->set_inobject_properties(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001526 reinterpret_cast<Map*>(result)->set_pre_allocated_property_fields(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001527 reinterpret_cast<Map*>(result)->set_unused_property_fields(0);
Leon Clarke4515c472010-02-03 11:58:03 +00001528 reinterpret_cast<Map*>(result)->set_bit_field(0);
1529 reinterpret_cast<Map*>(result)->set_bit_field2(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001530 return result;
1531}
1532
1533
John Reck59135872010-11-02 12:39:01 -07001534MaybeObject* Heap::AllocateMap(InstanceType instance_type, int instance_size) {
1535 Object* result;
1536 { MaybeObject* maybe_result = AllocateRawMap();
1537 if (!maybe_result->ToObject(&result)) return maybe_result;
1538 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001539
1540 Map* map = reinterpret_cast<Map*>(result);
1541 map->set_map(meta_map());
1542 map->set_instance_type(instance_type);
Iain Merrick75681382010-08-19 15:07:18 +01001543 map->set_visitor_id(
1544 StaticVisitorBase::GetVisitorId(instance_type, instance_size));
Steve Blocka7e24c12009-10-30 11:49:00 +00001545 map->set_prototype(null_value());
1546 map->set_constructor(null_value());
1547 map->set_instance_size(instance_size);
1548 map->set_inobject_properties(0);
1549 map->set_pre_allocated_property_fields(0);
1550 map->set_instance_descriptors(empty_descriptor_array());
1551 map->set_code_cache(empty_fixed_array());
1552 map->set_unused_property_fields(0);
1553 map->set_bit_field(0);
Steve Block8defd9f2010-07-08 12:39:36 +01001554 map->set_bit_field2((1 << Map::kIsExtensible) | (1 << Map::kHasFastElements));
Leon Clarkee46be812010-01-19 14:06:41 +00001555
1556 // If the map object is aligned fill the padding area with Smi 0 objects.
1557 if (Map::kPadStart < Map::kSize) {
1558 memset(reinterpret_cast<byte*>(map) + Map::kPadStart - kHeapObjectTag,
1559 0,
1560 Map::kSize - Map::kPadStart);
1561 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001562 return map;
1563}
1564
1565
John Reck59135872010-11-02 12:39:01 -07001566MaybeObject* Heap::AllocateCodeCache() {
1567 Object* result;
1568 { MaybeObject* maybe_result = AllocateStruct(CODE_CACHE_TYPE);
1569 if (!maybe_result->ToObject(&result)) return maybe_result;
1570 }
Steve Block6ded16b2010-05-10 14:33:55 +01001571 CodeCache* code_cache = CodeCache::cast(result);
1572 code_cache->set_default_cache(empty_fixed_array());
1573 code_cache->set_normal_type_cache(undefined_value());
1574 return code_cache;
1575}
1576
1577
Steve Blocka7e24c12009-10-30 11:49:00 +00001578const Heap::StringTypeTable Heap::string_type_table[] = {
1579#define STRING_TYPE_ELEMENT(type, size, name, camel_name) \
1580 {type, size, k##camel_name##MapRootIndex},
1581 STRING_TYPE_LIST(STRING_TYPE_ELEMENT)
1582#undef STRING_TYPE_ELEMENT
1583};
1584
1585
1586const Heap::ConstantSymbolTable Heap::constant_symbol_table[] = {
1587#define CONSTANT_SYMBOL_ELEMENT(name, contents) \
1588 {contents, k##name##RootIndex},
1589 SYMBOL_LIST(CONSTANT_SYMBOL_ELEMENT)
1590#undef CONSTANT_SYMBOL_ELEMENT
1591};
1592
1593
1594const Heap::StructTable Heap::struct_table[] = {
1595#define STRUCT_TABLE_ELEMENT(NAME, Name, name) \
1596 { NAME##_TYPE, Name::kSize, k##Name##MapRootIndex },
1597 STRUCT_LIST(STRUCT_TABLE_ELEMENT)
1598#undef STRUCT_TABLE_ELEMENT
1599};
1600
1601
1602bool Heap::CreateInitialMaps() {
John Reck59135872010-11-02 12:39:01 -07001603 Object* obj;
1604 { MaybeObject* maybe_obj = AllocatePartialMap(MAP_TYPE, Map::kSize);
1605 if (!maybe_obj->ToObject(&obj)) return false;
1606 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001607 // Map::cast cannot be used due to uninitialized map field.
1608 Map* new_meta_map = reinterpret_cast<Map*>(obj);
1609 set_meta_map(new_meta_map);
1610 new_meta_map->set_map(new_meta_map);
1611
John Reck59135872010-11-02 12:39:01 -07001612 { MaybeObject* maybe_obj =
1613 AllocatePartialMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1614 if (!maybe_obj->ToObject(&obj)) return false;
1615 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001616 set_fixed_array_map(Map::cast(obj));
1617
John Reck59135872010-11-02 12:39:01 -07001618 { MaybeObject* maybe_obj = AllocatePartialMap(ODDBALL_TYPE, Oddball::kSize);
1619 if (!maybe_obj->ToObject(&obj)) return false;
1620 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001621 set_oddball_map(Map::cast(obj));
1622
Steve Block6ded16b2010-05-10 14:33:55 +01001623 // Allocate the empty array.
John Reck59135872010-11-02 12:39:01 -07001624 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1625 if (!maybe_obj->ToObject(&obj)) return false;
1626 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001627 set_empty_fixed_array(FixedArray::cast(obj));
1628
John Reck59135872010-11-02 12:39:01 -07001629 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1630 if (!maybe_obj->ToObject(&obj)) return false;
1631 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001632 set_null_value(obj);
1633
1634 // Allocate the empty descriptor array.
John Reck59135872010-11-02 12:39:01 -07001635 { MaybeObject* maybe_obj = AllocateEmptyFixedArray();
1636 if (!maybe_obj->ToObject(&obj)) return false;
1637 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001638 set_empty_descriptor_array(DescriptorArray::cast(obj));
1639
1640 // Fix the instance_descriptors for the existing maps.
1641 meta_map()->set_instance_descriptors(empty_descriptor_array());
1642 meta_map()->set_code_cache(empty_fixed_array());
1643
1644 fixed_array_map()->set_instance_descriptors(empty_descriptor_array());
1645 fixed_array_map()->set_code_cache(empty_fixed_array());
1646
1647 oddball_map()->set_instance_descriptors(empty_descriptor_array());
1648 oddball_map()->set_code_cache(empty_fixed_array());
1649
1650 // Fix prototype object for existing maps.
1651 meta_map()->set_prototype(null_value());
1652 meta_map()->set_constructor(null_value());
1653
1654 fixed_array_map()->set_prototype(null_value());
1655 fixed_array_map()->set_constructor(null_value());
1656
1657 oddball_map()->set_prototype(null_value());
1658 oddball_map()->set_constructor(null_value());
1659
John Reck59135872010-11-02 12:39:01 -07001660 { MaybeObject* maybe_obj =
1661 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1662 if (!maybe_obj->ToObject(&obj)) return false;
1663 }
Iain Merrick75681382010-08-19 15:07:18 +01001664 set_fixed_cow_array_map(Map::cast(obj));
1665 ASSERT(fixed_array_map() != fixed_cow_array_map());
1666
John Reck59135872010-11-02 12:39:01 -07001667 { MaybeObject* maybe_obj = AllocateMap(HEAP_NUMBER_TYPE, HeapNumber::kSize);
1668 if (!maybe_obj->ToObject(&obj)) return false;
1669 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001670 set_heap_number_map(Map::cast(obj));
1671
John Reck59135872010-11-02 12:39:01 -07001672 { MaybeObject* maybe_obj = AllocateMap(PROXY_TYPE, Proxy::kSize);
1673 if (!maybe_obj->ToObject(&obj)) return false;
1674 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001675 set_proxy_map(Map::cast(obj));
1676
1677 for (unsigned i = 0; i < ARRAY_SIZE(string_type_table); i++) {
1678 const StringTypeTable& entry = string_type_table[i];
John Reck59135872010-11-02 12:39:01 -07001679 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
1680 if (!maybe_obj->ToObject(&obj)) return false;
1681 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001682 roots_[entry.index] = Map::cast(obj);
1683 }
1684
John Reck59135872010-11-02 12:39:01 -07001685 { MaybeObject* maybe_obj = AllocateMap(STRING_TYPE, kVariableSizeSentinel);
1686 if (!maybe_obj->ToObject(&obj)) return false;
1687 }
Steve Blockd0582a62009-12-15 09:54:21 +00001688 set_undetectable_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001689 Map::cast(obj)->set_is_undetectable();
1690
John Reck59135872010-11-02 12:39:01 -07001691 { MaybeObject* maybe_obj =
1692 AllocateMap(ASCII_STRING_TYPE, kVariableSizeSentinel);
1693 if (!maybe_obj->ToObject(&obj)) return false;
1694 }
Steve Blockd0582a62009-12-15 09:54:21 +00001695 set_undetectable_ascii_string_map(Map::cast(obj));
Steve Blocka7e24c12009-10-30 11:49:00 +00001696 Map::cast(obj)->set_is_undetectable();
1697
John Reck59135872010-11-02 12:39:01 -07001698 { MaybeObject* maybe_obj =
1699 AllocateMap(BYTE_ARRAY_TYPE, kVariableSizeSentinel);
1700 if (!maybe_obj->ToObject(&obj)) return false;
1701 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001702 set_byte_array_map(Map::cast(obj));
1703
Ben Murdochb0fe1622011-05-05 13:52:32 +01001704 { MaybeObject* maybe_obj = AllocateByteArray(0, TENURED);
1705 if (!maybe_obj->ToObject(&obj)) return false;
1706 }
1707 set_empty_byte_array(ByteArray::cast(obj));
1708
John Reck59135872010-11-02 12:39:01 -07001709 { MaybeObject* maybe_obj =
1710 AllocateMap(PIXEL_ARRAY_TYPE, PixelArray::kAlignedSize);
1711 if (!maybe_obj->ToObject(&obj)) return false;
1712 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001713 set_pixel_array_map(Map::cast(obj));
1714
John Reck59135872010-11-02 12:39:01 -07001715 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_BYTE_ARRAY_TYPE,
1716 ExternalArray::kAlignedSize);
1717 if (!maybe_obj->ToObject(&obj)) return false;
1718 }
Steve Block3ce2e202009-11-05 08:53:23 +00001719 set_external_byte_array_map(Map::cast(obj));
1720
John Reck59135872010-11-02 12:39:01 -07001721 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
1722 ExternalArray::kAlignedSize);
1723 if (!maybe_obj->ToObject(&obj)) return false;
1724 }
Steve Block3ce2e202009-11-05 08:53:23 +00001725 set_external_unsigned_byte_array_map(Map::cast(obj));
1726
John Reck59135872010-11-02 12:39:01 -07001727 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_SHORT_ARRAY_TYPE,
1728 ExternalArray::kAlignedSize);
1729 if (!maybe_obj->ToObject(&obj)) return false;
1730 }
Steve Block3ce2e202009-11-05 08:53:23 +00001731 set_external_short_array_map(Map::cast(obj));
1732
John Reck59135872010-11-02 12:39:01 -07001733 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
1734 ExternalArray::kAlignedSize);
1735 if (!maybe_obj->ToObject(&obj)) return false;
1736 }
Steve Block3ce2e202009-11-05 08:53:23 +00001737 set_external_unsigned_short_array_map(Map::cast(obj));
1738
John Reck59135872010-11-02 12:39:01 -07001739 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_INT_ARRAY_TYPE,
1740 ExternalArray::kAlignedSize);
1741 if (!maybe_obj->ToObject(&obj)) return false;
1742 }
Steve Block3ce2e202009-11-05 08:53:23 +00001743 set_external_int_array_map(Map::cast(obj));
1744
John Reck59135872010-11-02 12:39:01 -07001745 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
1746 ExternalArray::kAlignedSize);
1747 if (!maybe_obj->ToObject(&obj)) return false;
1748 }
Steve Block3ce2e202009-11-05 08:53:23 +00001749 set_external_unsigned_int_array_map(Map::cast(obj));
1750
John Reck59135872010-11-02 12:39:01 -07001751 { MaybeObject* maybe_obj = AllocateMap(EXTERNAL_FLOAT_ARRAY_TYPE,
1752 ExternalArray::kAlignedSize);
1753 if (!maybe_obj->ToObject(&obj)) return false;
1754 }
Steve Block3ce2e202009-11-05 08:53:23 +00001755 set_external_float_array_map(Map::cast(obj));
1756
John Reck59135872010-11-02 12:39:01 -07001757 { MaybeObject* maybe_obj = AllocateMap(CODE_TYPE, kVariableSizeSentinel);
1758 if (!maybe_obj->ToObject(&obj)) return false;
1759 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001760 set_code_map(Map::cast(obj));
1761
John Reck59135872010-11-02 12:39:01 -07001762 { MaybeObject* maybe_obj = AllocateMap(JS_GLOBAL_PROPERTY_CELL_TYPE,
1763 JSGlobalPropertyCell::kSize);
1764 if (!maybe_obj->ToObject(&obj)) return false;
1765 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001766 set_global_property_cell_map(Map::cast(obj));
1767
John Reck59135872010-11-02 12:39:01 -07001768 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, kPointerSize);
1769 if (!maybe_obj->ToObject(&obj)) return false;
1770 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001771 set_one_pointer_filler_map(Map::cast(obj));
1772
John Reck59135872010-11-02 12:39:01 -07001773 { MaybeObject* maybe_obj = AllocateMap(FILLER_TYPE, 2 * kPointerSize);
1774 if (!maybe_obj->ToObject(&obj)) return false;
1775 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001776 set_two_pointer_filler_map(Map::cast(obj));
1777
1778 for (unsigned i = 0; i < ARRAY_SIZE(struct_table); i++) {
1779 const StructTable& entry = struct_table[i];
John Reck59135872010-11-02 12:39:01 -07001780 { MaybeObject* maybe_obj = AllocateMap(entry.type, entry.size);
1781 if (!maybe_obj->ToObject(&obj)) return false;
1782 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001783 roots_[entry.index] = Map::cast(obj);
1784 }
1785
John Reck59135872010-11-02 12:39:01 -07001786 { MaybeObject* maybe_obj =
1787 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1788 if (!maybe_obj->ToObject(&obj)) return false;
1789 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001790 set_hash_table_map(Map::cast(obj));
1791
John Reck59135872010-11-02 12:39:01 -07001792 { MaybeObject* maybe_obj =
1793 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1794 if (!maybe_obj->ToObject(&obj)) return false;
1795 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001796 set_context_map(Map::cast(obj));
1797
John Reck59135872010-11-02 12:39:01 -07001798 { MaybeObject* maybe_obj =
1799 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1800 if (!maybe_obj->ToObject(&obj)) return false;
1801 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001802 set_catch_context_map(Map::cast(obj));
1803
John Reck59135872010-11-02 12:39:01 -07001804 { MaybeObject* maybe_obj =
1805 AllocateMap(FIXED_ARRAY_TYPE, kVariableSizeSentinel);
1806 if (!maybe_obj->ToObject(&obj)) return false;
1807 }
Ben Murdochf87a2032010-10-22 12:50:53 +01001808 Map* global_context_map = Map::cast(obj);
1809 global_context_map->set_visitor_id(StaticVisitorBase::kVisitGlobalContext);
1810 set_global_context_map(global_context_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00001811
John Reck59135872010-11-02 12:39:01 -07001812 { MaybeObject* maybe_obj = AllocateMap(SHARED_FUNCTION_INFO_TYPE,
1813 SharedFunctionInfo::kAlignedSize);
1814 if (!maybe_obj->ToObject(&obj)) return false;
1815 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001816 set_shared_function_info_map(Map::cast(obj));
1817
Steve Block1e0659c2011-05-24 12:43:12 +01001818 { MaybeObject* maybe_obj = AllocateMap(JS_MESSAGE_OBJECT_TYPE,
1819 JSMessageObject::kSize);
1820 if (!maybe_obj->ToObject(&obj)) return false;
1821 }
1822 set_message_object_map(Map::cast(obj));
1823
Steve Blocka7e24c12009-10-30 11:49:00 +00001824 ASSERT(!Heap::InNewSpace(Heap::empty_fixed_array()));
1825 return true;
1826}
1827
1828
John Reck59135872010-11-02 12:39:01 -07001829MaybeObject* Heap::AllocateHeapNumber(double value, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001830 // Statically ensure that it is safe to allocate heap numbers in paged
1831 // spaces.
1832 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1833 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
1834
John Reck59135872010-11-02 12:39:01 -07001835 Object* result;
1836 { MaybeObject* maybe_result =
1837 AllocateRaw(HeapNumber::kSize, space, OLD_DATA_SPACE);
1838 if (!maybe_result->ToObject(&result)) return maybe_result;
1839 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001840
1841 HeapObject::cast(result)->set_map(heap_number_map());
1842 HeapNumber::cast(result)->set_value(value);
1843 return result;
1844}
1845
1846
John Reck59135872010-11-02 12:39:01 -07001847MaybeObject* Heap::AllocateHeapNumber(double value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001848 // Use general version, if we're forced to always allocate.
1849 if (always_allocate()) return AllocateHeapNumber(value, TENURED);
1850
1851 // This version of AllocateHeapNumber is optimized for
1852 // allocation in new space.
1853 STATIC_ASSERT(HeapNumber::kSize <= Page::kMaxHeapObjectSize);
1854 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
John Reck59135872010-11-02 12:39:01 -07001855 Object* result;
1856 { MaybeObject* maybe_result = new_space_.AllocateRaw(HeapNumber::kSize);
1857 if (!maybe_result->ToObject(&result)) return maybe_result;
1858 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001859 HeapObject::cast(result)->set_map(heap_number_map());
1860 HeapNumber::cast(result)->set_value(value);
1861 return result;
1862}
1863
1864
John Reck59135872010-11-02 12:39:01 -07001865MaybeObject* Heap::AllocateJSGlobalPropertyCell(Object* value) {
1866 Object* result;
1867 { MaybeObject* maybe_result = AllocateRawCell();
1868 if (!maybe_result->ToObject(&result)) return maybe_result;
1869 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001870 HeapObject::cast(result)->set_map(global_property_cell_map());
1871 JSGlobalPropertyCell::cast(result)->set_value(value);
1872 return result;
1873}
1874
1875
John Reck59135872010-11-02 12:39:01 -07001876MaybeObject* Heap::CreateOddball(const char* to_string,
1877 Object* to_number) {
1878 Object* result;
1879 { MaybeObject* maybe_result = Allocate(oddball_map(), OLD_DATA_SPACE);
1880 if (!maybe_result->ToObject(&result)) return maybe_result;
1881 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001882 return Oddball::cast(result)->Initialize(to_string, to_number);
1883}
1884
1885
1886bool Heap::CreateApiObjects() {
1887 Object* obj;
1888
John Reck59135872010-11-02 12:39:01 -07001889 { MaybeObject* maybe_obj = AllocateMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
1890 if (!maybe_obj->ToObject(&obj)) return false;
1891 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001892 set_neander_map(Map::cast(obj));
1893
John Reck59135872010-11-02 12:39:01 -07001894 { MaybeObject* maybe_obj = Heap::AllocateJSObjectFromMap(neander_map());
1895 if (!maybe_obj->ToObject(&obj)) return false;
1896 }
1897 Object* elements;
1898 { MaybeObject* maybe_elements = AllocateFixedArray(2);
1899 if (!maybe_elements->ToObject(&elements)) return false;
1900 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001901 FixedArray::cast(elements)->set(0, Smi::FromInt(0));
1902 JSObject::cast(obj)->set_elements(FixedArray::cast(elements));
1903 set_message_listeners(JSObject::cast(obj));
1904
1905 return true;
1906}
1907
1908
1909void Heap::CreateCEntryStub() {
1910 CEntryStub stub(1);
1911 set_c_entry_code(*stub.GetCode());
1912}
1913
1914
Steve Block6ded16b2010-05-10 14:33:55 +01001915#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001916void Heap::CreateRegExpCEntryStub() {
1917 RegExpCEntryStub stub;
1918 set_re_c_entry_code(*stub.GetCode());
1919}
1920#endif
1921
1922
Steve Blocka7e24c12009-10-30 11:49:00 +00001923void Heap::CreateJSEntryStub() {
1924 JSEntryStub stub;
1925 set_js_entry_code(*stub.GetCode());
1926}
1927
1928
1929void Heap::CreateJSConstructEntryStub() {
1930 JSConstructEntryStub stub;
1931 set_js_construct_entry_code(*stub.GetCode());
1932}
1933
1934
Steve Block1e0659c2011-05-24 12:43:12 +01001935#if V8_TARGET_ARCH_ARM
1936void Heap::CreateDirectCEntryStub() {
1937 DirectCEntryStub stub;
1938 set_direct_c_entry_code(*stub.GetCode());
1939}
1940#endif
1941
1942
Steve Blocka7e24c12009-10-30 11:49:00 +00001943void Heap::CreateFixedStubs() {
1944 // Here we create roots for fixed stubs. They are needed at GC
1945 // for cooking and uncooking (check out frames.cc).
1946 // The eliminates the need for doing dictionary lookup in the
1947 // stub cache for these stubs.
1948 HandleScope scope;
1949 // gcc-4.4 has problem generating correct code of following snippet:
1950 // { CEntryStub stub;
1951 // c_entry_code_ = *stub.GetCode();
1952 // }
Leon Clarke4515c472010-02-03 11:58:03 +00001953 // { DebuggerStatementStub stub;
1954 // debugger_statement_code_ = *stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00001955 // }
1956 // To workaround the problem, make separate functions without inlining.
1957 Heap::CreateCEntryStub();
Steve Blocka7e24c12009-10-30 11:49:00 +00001958 Heap::CreateJSEntryStub();
1959 Heap::CreateJSConstructEntryStub();
Steve Block6ded16b2010-05-10 14:33:55 +01001960#if V8_TARGET_ARCH_ARM && !V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00001961 Heap::CreateRegExpCEntryStub();
1962#endif
Steve Block1e0659c2011-05-24 12:43:12 +01001963#if V8_TARGET_ARCH_ARM
1964 Heap::CreateDirectCEntryStub();
1965#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001966}
1967
1968
1969bool Heap::CreateInitialObjects() {
1970 Object* obj;
1971
1972 // The -0 value must be set before NumberFromDouble works.
John Reck59135872010-11-02 12:39:01 -07001973 { MaybeObject* maybe_obj = AllocateHeapNumber(-0.0, TENURED);
1974 if (!maybe_obj->ToObject(&obj)) return false;
1975 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001976 set_minus_zero_value(obj);
1977 ASSERT(signbit(minus_zero_value()->Number()) != 0);
1978
John Reck59135872010-11-02 12:39:01 -07001979 { MaybeObject* maybe_obj = AllocateHeapNumber(OS::nan_value(), TENURED);
1980 if (!maybe_obj->ToObject(&obj)) return false;
1981 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001982 set_nan_value(obj);
1983
John Reck59135872010-11-02 12:39:01 -07001984 { MaybeObject* maybe_obj = Allocate(oddball_map(), OLD_DATA_SPACE);
1985 if (!maybe_obj->ToObject(&obj)) return false;
1986 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001987 set_undefined_value(obj);
1988 ASSERT(!InNewSpace(undefined_value()));
1989
1990 // Allocate initial symbol table.
John Reck59135872010-11-02 12:39:01 -07001991 { MaybeObject* maybe_obj = SymbolTable::Allocate(kInitialSymbolTableSize);
1992 if (!maybe_obj->ToObject(&obj)) return false;
1993 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001994 // Don't use set_symbol_table() due to asserts.
1995 roots_[kSymbolTableRootIndex] = obj;
1996
1997 // Assign the print strings for oddballs after creating symboltable.
John Reck59135872010-11-02 12:39:01 -07001998 Object* symbol;
1999 { MaybeObject* maybe_symbol = LookupAsciiSymbol("undefined");
2000 if (!maybe_symbol->ToObject(&symbol)) return false;
2001 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002002 Oddball::cast(undefined_value())->set_to_string(String::cast(symbol));
2003 Oddball::cast(undefined_value())->set_to_number(nan_value());
2004
Steve Blocka7e24c12009-10-30 11:49:00 +00002005 // Allocate the null_value
John Reck59135872010-11-02 12:39:01 -07002006 { MaybeObject* maybe_obj =
2007 Oddball::cast(null_value())->Initialize("null", Smi::FromInt(0));
2008 if (!maybe_obj->ToObject(&obj)) return false;
2009 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002010
John Reck59135872010-11-02 12:39:01 -07002011 { MaybeObject* maybe_obj = CreateOddball("true", Smi::FromInt(1));
2012 if (!maybe_obj->ToObject(&obj)) return false;
2013 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002014 set_true_value(obj);
2015
John Reck59135872010-11-02 12:39:01 -07002016 { MaybeObject* maybe_obj = CreateOddball("false", Smi::FromInt(0));
2017 if (!maybe_obj->ToObject(&obj)) return false;
2018 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002019 set_false_value(obj);
2020
John Reck59135872010-11-02 12:39:01 -07002021 { MaybeObject* maybe_obj = CreateOddball("hole", Smi::FromInt(-1));
2022 if (!maybe_obj->ToObject(&obj)) return false;
2023 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002024 set_the_hole_value(obj);
2025
Ben Murdoch086aeea2011-05-13 15:57:08 +01002026 { MaybeObject* maybe_obj = CreateOddball("arguments_marker",
2027 Smi::FromInt(-4));
2028 if (!maybe_obj->ToObject(&obj)) return false;
2029 }
2030 set_arguments_marker(obj);
2031
John Reck59135872010-11-02 12:39:01 -07002032 { MaybeObject* maybe_obj =
2033 CreateOddball("no_interceptor_result_sentinel", Smi::FromInt(-2));
2034 if (!maybe_obj->ToObject(&obj)) return false;
2035 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002036 set_no_interceptor_result_sentinel(obj);
2037
John Reck59135872010-11-02 12:39:01 -07002038 { MaybeObject* maybe_obj =
2039 CreateOddball("termination_exception", Smi::FromInt(-3));
2040 if (!maybe_obj->ToObject(&obj)) return false;
2041 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002042 set_termination_exception(obj);
2043
2044 // Allocate the empty string.
John Reck59135872010-11-02 12:39:01 -07002045 { MaybeObject* maybe_obj = AllocateRawAsciiString(0, TENURED);
2046 if (!maybe_obj->ToObject(&obj)) return false;
2047 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002048 set_empty_string(String::cast(obj));
2049
2050 for (unsigned i = 0; i < ARRAY_SIZE(constant_symbol_table); i++) {
John Reck59135872010-11-02 12:39:01 -07002051 { MaybeObject* maybe_obj =
2052 LookupAsciiSymbol(constant_symbol_table[i].contents);
2053 if (!maybe_obj->ToObject(&obj)) return false;
2054 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002055 roots_[constant_symbol_table[i].index] = String::cast(obj);
2056 }
2057
2058 // Allocate the hidden symbol which is used to identify the hidden properties
2059 // in JSObjects. The hash code has a special value so that it will not match
2060 // the empty string when searching for the property. It cannot be part of the
2061 // loop above because it needs to be allocated manually with the special
2062 // hash code in place. The hash code for the hidden_symbol is zero to ensure
2063 // that it will always be at the first entry in property descriptors.
John Reck59135872010-11-02 12:39:01 -07002064 { MaybeObject* maybe_obj =
2065 AllocateSymbol(CStrVector(""), 0, String::kZeroHash);
2066 if (!maybe_obj->ToObject(&obj)) return false;
2067 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002068 hidden_symbol_ = String::cast(obj);
2069
2070 // Allocate the proxy for __proto__.
John Reck59135872010-11-02 12:39:01 -07002071 { MaybeObject* maybe_obj =
2072 AllocateProxy((Address) &Accessors::ObjectPrototype);
2073 if (!maybe_obj->ToObject(&obj)) return false;
2074 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002075 set_prototype_accessors(Proxy::cast(obj));
2076
2077 // Allocate the code_stubs dictionary. The initial size is set to avoid
2078 // expanding the dictionary during bootstrapping.
John Reck59135872010-11-02 12:39:01 -07002079 { MaybeObject* maybe_obj = NumberDictionary::Allocate(128);
2080 if (!maybe_obj->ToObject(&obj)) return false;
2081 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002082 set_code_stubs(NumberDictionary::cast(obj));
2083
2084 // Allocate the non_monomorphic_cache used in stub-cache.cc. The initial size
2085 // is set to avoid expanding the dictionary during bootstrapping.
John Reck59135872010-11-02 12:39:01 -07002086 { MaybeObject* maybe_obj = NumberDictionary::Allocate(64);
2087 if (!maybe_obj->ToObject(&obj)) return false;
2088 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002089 set_non_monomorphic_cache(NumberDictionary::cast(obj));
2090
Kristian Monsen25f61362010-05-21 11:50:48 +01002091 set_instanceof_cache_function(Smi::FromInt(0));
2092 set_instanceof_cache_map(Smi::FromInt(0));
2093 set_instanceof_cache_answer(Smi::FromInt(0));
2094
Steve Blocka7e24c12009-10-30 11:49:00 +00002095 CreateFixedStubs();
2096
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002097 // Allocate the dictionary of intrinsic function names.
John Reck59135872010-11-02 12:39:01 -07002098 { MaybeObject* maybe_obj = StringDictionary::Allocate(Runtime::kNumFunctions);
2099 if (!maybe_obj->ToObject(&obj)) return false;
2100 }
2101 { MaybeObject* maybe_obj = Runtime::InitializeIntrinsicFunctionNames(obj);
2102 if (!maybe_obj->ToObject(&obj)) return false;
2103 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002104 set_intrinsic_function_names(StringDictionary::cast(obj));
2105
Leon Clarkee46be812010-01-19 14:06:41 +00002106 if (InitializeNumberStringCache()->IsFailure()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002107
Steve Block6ded16b2010-05-10 14:33:55 +01002108 // Allocate cache for single character ASCII strings.
John Reck59135872010-11-02 12:39:01 -07002109 { MaybeObject* maybe_obj =
2110 AllocateFixedArray(String::kMaxAsciiCharCode + 1, TENURED);
2111 if (!maybe_obj->ToObject(&obj)) return false;
2112 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002113 set_single_character_string_cache(FixedArray::cast(obj));
2114
2115 // Allocate cache for external strings pointing to native source code.
John Reck59135872010-11-02 12:39:01 -07002116 { MaybeObject* maybe_obj = AllocateFixedArray(Natives::GetBuiltinsCount());
2117 if (!maybe_obj->ToObject(&obj)) return false;
2118 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002119 set_natives_source_cache(FixedArray::cast(obj));
2120
2121 // Handling of script id generation is in Factory::NewScript.
2122 set_last_script_id(undefined_value());
2123
2124 // Initialize keyed lookup cache.
2125 KeyedLookupCache::Clear();
2126
2127 // Initialize context slot cache.
2128 ContextSlotCache::Clear();
2129
2130 // Initialize descriptor cache.
2131 DescriptorLookupCache::Clear();
2132
2133 // Initialize compilation cache.
2134 CompilationCache::Clear();
2135
2136 return true;
2137}
2138
2139
John Reck59135872010-11-02 12:39:01 -07002140MaybeObject* Heap::InitializeNumberStringCache() {
Leon Clarkee46be812010-01-19 14:06:41 +00002141 // Compute the size of the number string cache based on the max heap size.
2142 // max_semispace_size_ == 512 KB => number_string_cache_size = 32.
2143 // max_semispace_size_ == 8 MB => number_string_cache_size = 16KB.
2144 int number_string_cache_size = max_semispace_size_ / 512;
2145 number_string_cache_size = Max(32, Min(16*KB, number_string_cache_size));
John Reck59135872010-11-02 12:39:01 -07002146 Object* obj;
2147 MaybeObject* maybe_obj =
2148 AllocateFixedArray(number_string_cache_size * 2, TENURED);
2149 if (maybe_obj->ToObject(&obj)) set_number_string_cache(FixedArray::cast(obj));
2150 return maybe_obj;
Leon Clarkee46be812010-01-19 14:06:41 +00002151}
2152
2153
2154void Heap::FlushNumberStringCache() {
2155 // Flush the number to string cache.
2156 int len = number_string_cache()->length();
2157 for (int i = 0; i < len; i++) {
2158 number_string_cache()->set_undefined(i);
2159 }
2160}
2161
2162
Steve Blocka7e24c12009-10-30 11:49:00 +00002163static inline int double_get_hash(double d) {
2164 DoubleRepresentation rep(d);
Leon Clarkee46be812010-01-19 14:06:41 +00002165 return static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32);
Steve Blocka7e24c12009-10-30 11:49:00 +00002166}
2167
2168
2169static inline int smi_get_hash(Smi* smi) {
Leon Clarkee46be812010-01-19 14:06:41 +00002170 return smi->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002171}
2172
2173
Steve Blocka7e24c12009-10-30 11:49:00 +00002174Object* Heap::GetNumberStringCache(Object* number) {
2175 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002176 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002177 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002178 hash = smi_get_hash(Smi::cast(number)) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002179 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002180 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002181 }
2182 Object* key = number_string_cache()->get(hash * 2);
2183 if (key == number) {
2184 return String::cast(number_string_cache()->get(hash * 2 + 1));
2185 } else if (key->IsHeapNumber() &&
2186 number->IsHeapNumber() &&
2187 key->Number() == number->Number()) {
2188 return String::cast(number_string_cache()->get(hash * 2 + 1));
2189 }
2190 return undefined_value();
2191}
2192
2193
2194void Heap::SetNumberStringCache(Object* number, String* string) {
2195 int hash;
Leon Clarkee46be812010-01-19 14:06:41 +00002196 int mask = (number_string_cache()->length() >> 1) - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00002197 if (number->IsSmi()) {
Leon Clarkee46be812010-01-19 14:06:41 +00002198 hash = smi_get_hash(Smi::cast(number)) & mask;
Leon Clarke4515c472010-02-03 11:58:03 +00002199 number_string_cache()->set(hash * 2, Smi::cast(number));
Steve Blocka7e24c12009-10-30 11:49:00 +00002200 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00002201 hash = double_get_hash(number->Number()) & mask;
Steve Blocka7e24c12009-10-30 11:49:00 +00002202 number_string_cache()->set(hash * 2, number);
2203 }
2204 number_string_cache()->set(hash * 2 + 1, string);
2205}
2206
2207
John Reck59135872010-11-02 12:39:01 -07002208MaybeObject* Heap::NumberToString(Object* number,
2209 bool check_number_string_cache) {
Andrei Popescu402d9372010-02-26 13:31:12 +00002210 Counters::number_to_string_runtime.Increment();
Steve Block6ded16b2010-05-10 14:33:55 +01002211 if (check_number_string_cache) {
2212 Object* cached = GetNumberStringCache(number);
2213 if (cached != undefined_value()) {
2214 return cached;
2215 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002216 }
2217
2218 char arr[100];
2219 Vector<char> buffer(arr, ARRAY_SIZE(arr));
2220 const char* str;
2221 if (number->IsSmi()) {
2222 int num = Smi::cast(number)->value();
2223 str = IntToCString(num, buffer);
2224 } else {
2225 double num = HeapNumber::cast(number)->value();
2226 str = DoubleToCString(num, buffer);
2227 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002228
John Reck59135872010-11-02 12:39:01 -07002229 Object* js_string;
2230 MaybeObject* maybe_js_string = AllocateStringFromAscii(CStrVector(str));
2231 if (maybe_js_string->ToObject(&js_string)) {
2232 SetNumberStringCache(number, String::cast(js_string));
Steve Blocka7e24c12009-10-30 11:49:00 +00002233 }
John Reck59135872010-11-02 12:39:01 -07002234 return maybe_js_string;
Steve Blocka7e24c12009-10-30 11:49:00 +00002235}
2236
2237
Steve Block3ce2e202009-11-05 08:53:23 +00002238Map* Heap::MapForExternalArrayType(ExternalArrayType array_type) {
2239 return Map::cast(roots_[RootIndexForExternalArrayType(array_type)]);
2240}
2241
2242
2243Heap::RootListIndex Heap::RootIndexForExternalArrayType(
2244 ExternalArrayType array_type) {
2245 switch (array_type) {
2246 case kExternalByteArray:
2247 return kExternalByteArrayMapRootIndex;
2248 case kExternalUnsignedByteArray:
2249 return kExternalUnsignedByteArrayMapRootIndex;
2250 case kExternalShortArray:
2251 return kExternalShortArrayMapRootIndex;
2252 case kExternalUnsignedShortArray:
2253 return kExternalUnsignedShortArrayMapRootIndex;
2254 case kExternalIntArray:
2255 return kExternalIntArrayMapRootIndex;
2256 case kExternalUnsignedIntArray:
2257 return kExternalUnsignedIntArrayMapRootIndex;
2258 case kExternalFloatArray:
2259 return kExternalFloatArrayMapRootIndex;
2260 default:
2261 UNREACHABLE();
2262 return kUndefinedValueRootIndex;
2263 }
2264}
2265
2266
John Reck59135872010-11-02 12:39:01 -07002267MaybeObject* Heap::NumberFromDouble(double value, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01002268 // We need to distinguish the minus zero value and this cannot be
2269 // done after conversion to int. Doing this by comparing bit
2270 // patterns is faster than using fpclassify() et al.
2271 static const DoubleRepresentation minus_zero(-0.0);
2272
2273 DoubleRepresentation rep(value);
2274 if (rep.bits == minus_zero.bits) {
2275 return AllocateHeapNumber(-0.0, pretenure);
2276 }
2277
2278 int int_value = FastD2I(value);
2279 if (value == int_value && Smi::IsValid(int_value)) {
2280 return Smi::FromInt(int_value);
2281 }
2282
2283 // Materialize the value in the heap.
2284 return AllocateHeapNumber(value, pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00002285}
2286
2287
John Reck59135872010-11-02 12:39:01 -07002288MaybeObject* Heap::AllocateProxy(Address proxy, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002289 // Statically ensure that it is safe to allocate proxies in paged spaces.
2290 STATIC_ASSERT(Proxy::kSize <= Page::kMaxHeapObjectSize);
2291 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07002292 Object* result;
2293 { MaybeObject* maybe_result = Allocate(proxy_map(), space);
2294 if (!maybe_result->ToObject(&result)) return maybe_result;
2295 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002296
2297 Proxy::cast(result)->set_proxy(proxy);
2298 return result;
2299}
2300
2301
John Reck59135872010-11-02 12:39:01 -07002302MaybeObject* Heap::AllocateSharedFunctionInfo(Object* name) {
2303 Object* result;
2304 { MaybeObject* maybe_result =
2305 Allocate(shared_function_info_map(), OLD_POINTER_SPACE);
2306 if (!maybe_result->ToObject(&result)) return maybe_result;
2307 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002308
2309 SharedFunctionInfo* share = SharedFunctionInfo::cast(result);
2310 share->set_name(name);
2311 Code* illegal = Builtins::builtin(Builtins::Illegal);
2312 share->set_code(illegal);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002313 share->set_scope_info(SerializedScopeInfo::Empty());
Steve Blocka7e24c12009-10-30 11:49:00 +00002314 Code* construct_stub = Builtins::builtin(Builtins::JSConstructStubGeneric);
2315 share->set_construct_stub(construct_stub);
2316 share->set_expected_nof_properties(0);
2317 share->set_length(0);
2318 share->set_formal_parameter_count(0);
2319 share->set_instance_class_name(Object_symbol());
2320 share->set_function_data(undefined_value());
2321 share->set_script(undefined_value());
2322 share->set_start_position_and_type(0);
2323 share->set_debug_info(undefined_value());
2324 share->set_inferred_name(empty_string());
2325 share->set_compiler_hints(0);
Ben Murdochb0fe1622011-05-05 13:52:32 +01002326 share->set_deopt_counter(Smi::FromInt(FLAG_deopt_every_n_times));
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002327 share->set_initial_map(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002328 share->set_this_property_assignments_count(0);
2329 share->set_this_property_assignments(undefined_value());
Ben Murdochb0fe1622011-05-05 13:52:32 +01002330 share->set_opt_count(0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002331 share->set_num_literals(0);
2332 share->set_end_position(0);
2333 share->set_function_token_position(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00002334 return result;
2335}
2336
2337
Steve Block1e0659c2011-05-24 12:43:12 +01002338MaybeObject* Heap::AllocateJSMessageObject(String* type,
2339 JSArray* arguments,
2340 int start_position,
2341 int end_position,
2342 Object* script,
2343 Object* stack_trace,
2344 Object* stack_frames) {
2345 Object* result;
2346 { MaybeObject* maybe_result = Allocate(message_object_map(), NEW_SPACE);
2347 if (!maybe_result->ToObject(&result)) return maybe_result;
2348 }
2349 JSMessageObject* message = JSMessageObject::cast(result);
2350 message->set_properties(Heap::empty_fixed_array());
2351 message->set_elements(Heap::empty_fixed_array());
2352 message->set_type(type);
2353 message->set_arguments(arguments);
2354 message->set_start_position(start_position);
2355 message->set_end_position(end_position);
2356 message->set_script(script);
2357 message->set_stack_trace(stack_trace);
2358 message->set_stack_frames(stack_frames);
2359 return result;
2360}
2361
2362
2363
Steve Blockd0582a62009-12-15 09:54:21 +00002364// Returns true for a character in a range. Both limits are inclusive.
2365static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
2366 // This makes uses of the the unsigned wraparound.
2367 return character - from <= to - from;
2368}
2369
2370
John Reck59135872010-11-02 12:39:01 -07002371MUST_USE_RESULT static inline MaybeObject* MakeOrFindTwoCharacterString(
2372 uint32_t c1,
2373 uint32_t c2) {
Steve Blockd0582a62009-12-15 09:54:21 +00002374 String* symbol;
2375 // Numeric strings have a different hash algorithm not known by
2376 // LookupTwoCharsSymbolIfExists, so we skip this step for such strings.
2377 if ((!Between(c1, '0', '9') || !Between(c2, '0', '9')) &&
2378 Heap::symbol_table()->LookupTwoCharsSymbolIfExists(c1, c2, &symbol)) {
2379 return symbol;
2380 // Now we know the length is 2, we might as well make use of that fact
2381 // when building the new string.
2382 } else if ((c1 | c2) <= String::kMaxAsciiCharCodeU) { // We can do this
2383 ASSERT(IsPowerOf2(String::kMaxAsciiCharCodeU + 1)); // because of this.
John Reck59135872010-11-02 12:39:01 -07002384 Object* result;
2385 { MaybeObject* maybe_result = Heap::AllocateRawAsciiString(2);
2386 if (!maybe_result->ToObject(&result)) return maybe_result;
2387 }
Steve Blockd0582a62009-12-15 09:54:21 +00002388 char* dest = SeqAsciiString::cast(result)->GetChars();
2389 dest[0] = c1;
2390 dest[1] = c2;
2391 return result;
2392 } else {
John Reck59135872010-11-02 12:39:01 -07002393 Object* result;
2394 { MaybeObject* maybe_result = Heap::AllocateRawTwoByteString(2);
2395 if (!maybe_result->ToObject(&result)) return maybe_result;
2396 }
Steve Blockd0582a62009-12-15 09:54:21 +00002397 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2398 dest[0] = c1;
2399 dest[1] = c2;
2400 return result;
2401 }
2402}
2403
2404
John Reck59135872010-11-02 12:39:01 -07002405MaybeObject* Heap::AllocateConsString(String* first, String* second) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002406 int first_length = first->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002407 if (first_length == 0) {
2408 return second;
2409 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002410
2411 int second_length = second->length();
Steve Blockd0582a62009-12-15 09:54:21 +00002412 if (second_length == 0) {
2413 return first;
2414 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002415
2416 int length = first_length + second_length;
Steve Blockd0582a62009-12-15 09:54:21 +00002417
2418 // Optimization for 2-byte strings often used as keys in a decompression
2419 // dictionary. Check whether we already have the string in the symbol
2420 // table to prevent creation of many unneccesary strings.
2421 if (length == 2) {
2422 unsigned c1 = first->Get(0);
2423 unsigned c2 = second->Get(0);
2424 return MakeOrFindTwoCharacterString(c1, c2);
2425 }
2426
Steve Block6ded16b2010-05-10 14:33:55 +01002427 bool first_is_ascii = first->IsAsciiRepresentation();
2428 bool second_is_ascii = second->IsAsciiRepresentation();
2429 bool is_ascii = first_is_ascii && second_is_ascii;
Steve Blocka7e24c12009-10-30 11:49:00 +00002430
2431 // Make sure that an out of memory exception is thrown if the length
Steve Block3ce2e202009-11-05 08:53:23 +00002432 // of the new cons string is too large.
2433 if (length > String::kMaxLength || length < 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002434 Top::context()->mark_out_of_memory();
2435 return Failure::OutOfMemoryException();
2436 }
2437
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002438 bool is_ascii_data_in_two_byte_string = false;
2439 if (!is_ascii) {
2440 // At least one of the strings uses two-byte representation so we
2441 // can't use the fast case code for short ascii strings below, but
2442 // we can try to save memory if all chars actually fit in ascii.
2443 is_ascii_data_in_two_byte_string =
2444 first->HasOnlyAsciiChars() && second->HasOnlyAsciiChars();
2445 if (is_ascii_data_in_two_byte_string) {
2446 Counters::string_add_runtime_ext_to_ascii.Increment();
2447 }
2448 }
2449
Steve Blocka7e24c12009-10-30 11:49:00 +00002450 // If the resulting string is small make a flat string.
2451 if (length < String::kMinNonFlatLength) {
2452 ASSERT(first->IsFlat());
2453 ASSERT(second->IsFlat());
2454 if (is_ascii) {
John Reck59135872010-11-02 12:39:01 -07002455 Object* result;
2456 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2457 if (!maybe_result->ToObject(&result)) return maybe_result;
2458 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002459 // Copy the characters into the new object.
2460 char* dest = SeqAsciiString::cast(result)->GetChars();
2461 // Copy first part.
Steve Blockd0582a62009-12-15 09:54:21 +00002462 const char* src;
2463 if (first->IsExternalString()) {
2464 src = ExternalAsciiString::cast(first)->resource()->data();
2465 } else {
2466 src = SeqAsciiString::cast(first)->GetChars();
2467 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002468 for (int i = 0; i < first_length; i++) *dest++ = src[i];
2469 // Copy second part.
Steve Blockd0582a62009-12-15 09:54:21 +00002470 if (second->IsExternalString()) {
2471 src = ExternalAsciiString::cast(second)->resource()->data();
2472 } else {
2473 src = SeqAsciiString::cast(second)->GetChars();
2474 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002475 for (int i = 0; i < second_length; i++) *dest++ = src[i];
2476 return result;
2477 } else {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002478 if (is_ascii_data_in_two_byte_string) {
John Reck59135872010-11-02 12:39:01 -07002479 Object* result;
2480 { MaybeObject* maybe_result = AllocateRawAsciiString(length);
2481 if (!maybe_result->ToObject(&result)) return maybe_result;
2482 }
Steve Block6ded16b2010-05-10 14:33:55 +01002483 // Copy the characters into the new object.
2484 char* dest = SeqAsciiString::cast(result)->GetChars();
2485 String::WriteToFlat(first, dest, 0, first_length);
2486 String::WriteToFlat(second, dest + first_length, 0, second_length);
Steve Block6ded16b2010-05-10 14:33:55 +01002487 return result;
2488 }
2489
John Reck59135872010-11-02 12:39:01 -07002490 Object* result;
2491 { MaybeObject* maybe_result = AllocateRawTwoByteString(length);
2492 if (!maybe_result->ToObject(&result)) return maybe_result;
2493 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002494 // Copy the characters into the new object.
2495 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
2496 String::WriteToFlat(first, dest, 0, first_length);
2497 String::WriteToFlat(second, dest + first_length, 0, second_length);
2498 return result;
2499 }
2500 }
2501
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002502 Map* map = (is_ascii || is_ascii_data_in_two_byte_string) ?
2503 cons_ascii_string_map() : cons_string_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00002504
John Reck59135872010-11-02 12:39:01 -07002505 Object* result;
2506 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2507 if (!maybe_result->ToObject(&result)) return maybe_result;
2508 }
Leon Clarke4515c472010-02-03 11:58:03 +00002509
2510 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00002511 ConsString* cons_string = ConsString::cast(result);
Leon Clarke4515c472010-02-03 11:58:03 +00002512 WriteBarrierMode mode = cons_string->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002513 cons_string->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00002514 cons_string->set_hash_field(String::kEmptyHashField);
2515 cons_string->set_first(first, mode);
2516 cons_string->set_second(second, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002517 return result;
2518}
2519
2520
John Reck59135872010-11-02 12:39:01 -07002521MaybeObject* Heap::AllocateSubString(String* buffer,
Steve Blocka7e24c12009-10-30 11:49:00 +00002522 int start,
Steve Block6ded16b2010-05-10 14:33:55 +01002523 int end,
2524 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002525 int length = end - start;
2526
2527 if (length == 1) {
2528 return Heap::LookupSingleCharacterStringFromCode(
2529 buffer->Get(start));
Steve Blockd0582a62009-12-15 09:54:21 +00002530 } else if (length == 2) {
2531 // Optimization for 2-byte strings often used as keys in a decompression
2532 // dictionary. Check whether we already have the string in the symbol
2533 // table to prevent creation of many unneccesary strings.
2534 unsigned c1 = buffer->Get(start);
2535 unsigned c2 = buffer->Get(start + 1);
2536 return MakeOrFindTwoCharacterString(c1, c2);
Steve Blocka7e24c12009-10-30 11:49:00 +00002537 }
2538
2539 // Make an attempt to flatten the buffer to reduce access time.
Leon Clarkef7060e22010-06-03 12:02:55 +01002540 buffer = buffer->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00002541
John Reck59135872010-11-02 12:39:01 -07002542 Object* result;
2543 { MaybeObject* maybe_result = buffer->IsAsciiRepresentation()
2544 ? AllocateRawAsciiString(length, pretenure )
2545 : AllocateRawTwoByteString(length, pretenure);
2546 if (!maybe_result->ToObject(&result)) return maybe_result;
2547 }
Steve Blockd0582a62009-12-15 09:54:21 +00002548 String* string_result = String::cast(result);
Steve Blocka7e24c12009-10-30 11:49:00 +00002549 // Copy the characters into the new object.
Steve Blockd0582a62009-12-15 09:54:21 +00002550 if (buffer->IsAsciiRepresentation()) {
2551 ASSERT(string_result->IsAsciiRepresentation());
2552 char* dest = SeqAsciiString::cast(string_result)->GetChars();
2553 String::WriteToFlat(buffer, dest, start, end);
2554 } else {
2555 ASSERT(string_result->IsTwoByteRepresentation());
2556 uc16* dest = SeqTwoByteString::cast(string_result)->GetChars();
2557 String::WriteToFlat(buffer, dest, start, end);
Steve Blocka7e24c12009-10-30 11:49:00 +00002558 }
Steve Blockd0582a62009-12-15 09:54:21 +00002559
Steve Blocka7e24c12009-10-30 11:49:00 +00002560 return result;
2561}
2562
2563
John Reck59135872010-11-02 12:39:01 -07002564MaybeObject* Heap::AllocateExternalStringFromAscii(
Steve Blocka7e24c12009-10-30 11:49:00 +00002565 ExternalAsciiString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00002566 size_t length = resource->length();
2567 if (length > static_cast<size_t>(String::kMaxLength)) {
2568 Top::context()->mark_out_of_memory();
2569 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00002570 }
2571
Steve Blockd0582a62009-12-15 09:54:21 +00002572 Map* map = external_ascii_string_map();
John Reck59135872010-11-02 12:39:01 -07002573 Object* result;
2574 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2575 if (!maybe_result->ToObject(&result)) return maybe_result;
2576 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002577
2578 ExternalAsciiString* external_string = ExternalAsciiString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002579 external_string->set_length(static_cast<int>(length));
2580 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002581 external_string->set_resource(resource);
2582
2583 return result;
2584}
2585
2586
John Reck59135872010-11-02 12:39:01 -07002587MaybeObject* Heap::AllocateExternalStringFromTwoByte(
Steve Blocka7e24c12009-10-30 11:49:00 +00002588 ExternalTwoByteString::Resource* resource) {
Steve Blockd0582a62009-12-15 09:54:21 +00002589 size_t length = resource->length();
2590 if (length > static_cast<size_t>(String::kMaxLength)) {
2591 Top::context()->mark_out_of_memory();
2592 return Failure::OutOfMemoryException();
2593 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002594
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002595 // For small strings we check whether the resource contains only
Steve Block9fac8402011-05-12 15:51:54 +01002596 // ASCII characters. If yes, we use a different string map.
2597 static const size_t kAsciiCheckLengthLimit = 32;
2598 bool is_ascii = length <= kAsciiCheckLengthLimit &&
2599 String::IsAscii(resource->data(), static_cast<int>(length));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002600 Map* map = is_ascii ?
2601 Heap::external_string_with_ascii_data_map() : Heap::external_string_map();
John Reck59135872010-11-02 12:39:01 -07002602 Object* result;
2603 { MaybeObject* maybe_result = Allocate(map, NEW_SPACE);
2604 if (!maybe_result->ToObject(&result)) return maybe_result;
2605 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002606
2607 ExternalTwoByteString* external_string = ExternalTwoByteString::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00002608 external_string->set_length(static_cast<int>(length));
2609 external_string->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00002610 external_string->set_resource(resource);
2611
2612 return result;
2613}
2614
2615
John Reck59135872010-11-02 12:39:01 -07002616MaybeObject* Heap::LookupSingleCharacterStringFromCode(uint16_t code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002617 if (code <= String::kMaxAsciiCharCode) {
2618 Object* value = Heap::single_character_string_cache()->get(code);
2619 if (value != Heap::undefined_value()) return value;
2620
2621 char buffer[1];
2622 buffer[0] = static_cast<char>(code);
John Reck59135872010-11-02 12:39:01 -07002623 Object* result;
2624 MaybeObject* maybe_result = LookupSymbol(Vector<const char>(buffer, 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00002625
John Reck59135872010-11-02 12:39:01 -07002626 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002627 Heap::single_character_string_cache()->set(code, result);
2628 return result;
2629 }
2630
John Reck59135872010-11-02 12:39:01 -07002631 Object* result;
2632 { MaybeObject* maybe_result = Heap::AllocateRawTwoByteString(1);
2633 if (!maybe_result->ToObject(&result)) return maybe_result;
2634 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002635 String* answer = String::cast(result);
2636 answer->Set(0, code);
2637 return answer;
2638}
2639
2640
John Reck59135872010-11-02 12:39:01 -07002641MaybeObject* Heap::AllocateByteArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00002642 if (length < 0 || length > ByteArray::kMaxLength) {
2643 return Failure::OutOfMemoryException();
2644 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002645 if (pretenure == NOT_TENURED) {
2646 return AllocateByteArray(length);
2647 }
2648 int size = ByteArray::SizeFor(length);
John Reck59135872010-11-02 12:39:01 -07002649 Object* result;
2650 { MaybeObject* maybe_result = (size <= MaxObjectSizeInPagedSpace())
2651 ? old_data_space_->AllocateRaw(size)
2652 : lo_space_->AllocateRaw(size);
2653 if (!maybe_result->ToObject(&result)) return maybe_result;
2654 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002655
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002656 reinterpret_cast<ByteArray*>(result)->set_map(byte_array_map());
2657 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002658 return result;
2659}
2660
2661
John Reck59135872010-11-02 12:39:01 -07002662MaybeObject* Heap::AllocateByteArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00002663 if (length < 0 || length > ByteArray::kMaxLength) {
2664 return Failure::OutOfMemoryException();
2665 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002666 int size = ByteArray::SizeFor(length);
2667 AllocationSpace space =
Leon Clarkee46be812010-01-19 14:06:41 +00002668 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07002669 Object* result;
2670 { MaybeObject* maybe_result = AllocateRaw(size, space, OLD_DATA_SPACE);
2671 if (!maybe_result->ToObject(&result)) return maybe_result;
2672 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002673
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002674 reinterpret_cast<ByteArray*>(result)->set_map(byte_array_map());
2675 reinterpret_cast<ByteArray*>(result)->set_length(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002676 return result;
2677}
2678
2679
2680void Heap::CreateFillerObjectAt(Address addr, int size) {
2681 if (size == 0) return;
2682 HeapObject* filler = HeapObject::FromAddress(addr);
2683 if (size == kPointerSize) {
Steve Block6ded16b2010-05-10 14:33:55 +01002684 filler->set_map(one_pointer_filler_map());
2685 } else if (size == 2 * kPointerSize) {
2686 filler->set_map(two_pointer_filler_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002687 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002688 filler->set_map(byte_array_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00002689 ByteArray::cast(filler)->set_length(ByteArray::LengthFor(size));
2690 }
2691}
2692
2693
John Reck59135872010-11-02 12:39:01 -07002694MaybeObject* Heap::AllocatePixelArray(int length,
Steve Blocka7e24c12009-10-30 11:49:00 +00002695 uint8_t* external_pointer,
2696 PretenureFlag pretenure) {
2697 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07002698 Object* result;
2699 { MaybeObject* maybe_result =
2700 AllocateRaw(PixelArray::kAlignedSize, space, OLD_DATA_SPACE);
2701 if (!maybe_result->ToObject(&result)) return maybe_result;
2702 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002703
2704 reinterpret_cast<PixelArray*>(result)->set_map(pixel_array_map());
2705 reinterpret_cast<PixelArray*>(result)->set_length(length);
2706 reinterpret_cast<PixelArray*>(result)->set_external_pointer(external_pointer);
2707
2708 return result;
2709}
2710
2711
John Reck59135872010-11-02 12:39:01 -07002712MaybeObject* Heap::AllocateExternalArray(int length,
2713 ExternalArrayType array_type,
2714 void* external_pointer,
2715 PretenureFlag pretenure) {
Steve Block3ce2e202009-11-05 08:53:23 +00002716 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07002717 Object* result;
2718 { MaybeObject* maybe_result = AllocateRaw(ExternalArray::kAlignedSize,
2719 space,
2720 OLD_DATA_SPACE);
2721 if (!maybe_result->ToObject(&result)) return maybe_result;
2722 }
Steve Block3ce2e202009-11-05 08:53:23 +00002723
2724 reinterpret_cast<ExternalArray*>(result)->set_map(
2725 MapForExternalArrayType(array_type));
2726 reinterpret_cast<ExternalArray*>(result)->set_length(length);
2727 reinterpret_cast<ExternalArray*>(result)->set_external_pointer(
2728 external_pointer);
2729
2730 return result;
2731}
2732
2733
John Reck59135872010-11-02 12:39:01 -07002734MaybeObject* Heap::CreateCode(const CodeDesc& desc,
2735 Code::Flags flags,
2736 Handle<Object> self_reference) {
Leon Clarkeac952652010-07-15 11:15:24 +01002737 // Allocate ByteArray before the Code object, so that we do not risk
2738 // leaving uninitialized Code object (and breaking the heap).
John Reck59135872010-11-02 12:39:01 -07002739 Object* reloc_info;
2740 { MaybeObject* maybe_reloc_info = AllocateByteArray(desc.reloc_size, TENURED);
2741 if (!maybe_reloc_info->ToObject(&reloc_info)) return maybe_reloc_info;
2742 }
Leon Clarkeac952652010-07-15 11:15:24 +01002743
Steve Blocka7e24c12009-10-30 11:49:00 +00002744 // Compute size
Leon Clarkeac952652010-07-15 11:15:24 +01002745 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002746 int obj_size = Code::SizeFor(body_size);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002747 ASSERT(IsAligned(static_cast<intptr_t>(obj_size), kCodeAlignment));
John Reck59135872010-11-02 12:39:01 -07002748 MaybeObject* maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002749 if (obj_size > MaxObjectSizeInPagedSpace()) {
John Reck59135872010-11-02 12:39:01 -07002750 maybe_result = lo_space_->AllocateRawCode(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002751 } else {
John Reck59135872010-11-02 12:39:01 -07002752 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002753 }
2754
John Reck59135872010-11-02 12:39:01 -07002755 Object* result;
2756 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002757
2758 // Initialize the object
2759 HeapObject::cast(result)->set_map(code_map());
2760 Code* code = Code::cast(result);
2761 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2762 code->set_instruction_size(desc.instr_size);
Leon Clarkeac952652010-07-15 11:15:24 +01002763 code->set_relocation_info(ByteArray::cast(reloc_info));
Steve Blocka7e24c12009-10-30 11:49:00 +00002764 code->set_flags(flags);
Ben Murdochb8e0da22011-05-16 14:20:40 +01002765 if (code->is_call_stub() || code->is_keyed_call_stub()) {
2766 code->set_check_type(RECEIVER_MAP_CHECK);
2767 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01002768 code->set_deoptimization_data(empty_fixed_array());
Steve Blocka7e24c12009-10-30 11:49:00 +00002769 // Allow self references to created code object by patching the handle to
2770 // point to the newly allocated Code object.
2771 if (!self_reference.is_null()) {
2772 *(self_reference.location()) = code;
2773 }
2774 // Migrate generated code.
2775 // The generated code can contain Object** values (typically from handles)
2776 // that are dereferenced during the copy to point directly to the actual heap
2777 // objects. These pointers can include references to the code object itself,
2778 // through the self_reference parameter.
2779 code->CopyFrom(desc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002780
2781#ifdef DEBUG
2782 code->Verify();
2783#endif
2784 return code;
2785}
2786
2787
John Reck59135872010-11-02 12:39:01 -07002788MaybeObject* Heap::CopyCode(Code* code) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002789 // Allocate an object the same size as the code object.
2790 int obj_size = code->Size();
John Reck59135872010-11-02 12:39:01 -07002791 MaybeObject* maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002792 if (obj_size > MaxObjectSizeInPagedSpace()) {
John Reck59135872010-11-02 12:39:01 -07002793 maybe_result = lo_space_->AllocateRawCode(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002794 } else {
John Reck59135872010-11-02 12:39:01 -07002795 maybe_result = code_space_->AllocateRaw(obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002796 }
2797
John Reck59135872010-11-02 12:39:01 -07002798 Object* result;
2799 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002800
2801 // Copy code object.
2802 Address old_addr = code->address();
2803 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002804 CopyBlock(new_addr, old_addr, obj_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002805 // Relocate the copy.
2806 Code* new_code = Code::cast(result);
2807 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2808 new_code->Relocate(new_addr - old_addr);
2809 return new_code;
2810}
2811
2812
John Reck59135872010-11-02 12:39:01 -07002813MaybeObject* Heap::CopyCode(Code* code, Vector<byte> reloc_info) {
Leon Clarkeac952652010-07-15 11:15:24 +01002814 // Allocate ByteArray before the Code object, so that we do not risk
2815 // leaving uninitialized Code object (and breaking the heap).
John Reck59135872010-11-02 12:39:01 -07002816 Object* reloc_info_array;
2817 { MaybeObject* maybe_reloc_info_array =
2818 AllocateByteArray(reloc_info.length(), TENURED);
2819 if (!maybe_reloc_info_array->ToObject(&reloc_info_array)) {
2820 return maybe_reloc_info_array;
2821 }
2822 }
Leon Clarkeac952652010-07-15 11:15:24 +01002823
2824 int new_body_size = RoundUp(code->instruction_size(), kObjectAlignment);
Steve Block6ded16b2010-05-10 14:33:55 +01002825
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002826 int new_obj_size = Code::SizeFor(new_body_size);
Steve Block6ded16b2010-05-10 14:33:55 +01002827
2828 Address old_addr = code->address();
2829
2830 size_t relocation_offset =
Leon Clarkeac952652010-07-15 11:15:24 +01002831 static_cast<size_t>(code->instruction_end() - old_addr);
Steve Block6ded16b2010-05-10 14:33:55 +01002832
John Reck59135872010-11-02 12:39:01 -07002833 MaybeObject* maybe_result;
Steve Block6ded16b2010-05-10 14:33:55 +01002834 if (new_obj_size > MaxObjectSizeInPagedSpace()) {
John Reck59135872010-11-02 12:39:01 -07002835 maybe_result = lo_space_->AllocateRawCode(new_obj_size);
Steve Block6ded16b2010-05-10 14:33:55 +01002836 } else {
John Reck59135872010-11-02 12:39:01 -07002837 maybe_result = code_space_->AllocateRaw(new_obj_size);
Steve Block6ded16b2010-05-10 14:33:55 +01002838 }
2839
John Reck59135872010-11-02 12:39:01 -07002840 Object* result;
2841 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Block6ded16b2010-05-10 14:33:55 +01002842
2843 // Copy code object.
2844 Address new_addr = reinterpret_cast<HeapObject*>(result)->address();
2845
2846 // Copy header and instructions.
2847 memcpy(new_addr, old_addr, relocation_offset);
2848
Steve Block6ded16b2010-05-10 14:33:55 +01002849 Code* new_code = Code::cast(result);
Leon Clarkeac952652010-07-15 11:15:24 +01002850 new_code->set_relocation_info(ByteArray::cast(reloc_info_array));
Steve Block6ded16b2010-05-10 14:33:55 +01002851
Leon Clarkeac952652010-07-15 11:15:24 +01002852 // Copy patched rinfo.
2853 memcpy(new_code->relocation_start(), reloc_info.start(), reloc_info.length());
Steve Block6ded16b2010-05-10 14:33:55 +01002854
2855 // Relocate the copy.
2856 ASSERT(!CodeRange::exists() || CodeRange::contains(code->address()));
2857 new_code->Relocate(new_addr - old_addr);
2858
2859#ifdef DEBUG
2860 code->Verify();
2861#endif
2862 return new_code;
2863}
2864
2865
John Reck59135872010-11-02 12:39:01 -07002866MaybeObject* Heap::Allocate(Map* map, AllocationSpace space) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002867 ASSERT(gc_state_ == NOT_IN_GC);
2868 ASSERT(map->instance_type() != MAP_TYPE);
Leon Clarkee46be812010-01-19 14:06:41 +00002869 // If allocation failures are disallowed, we may allocate in a different
2870 // space when new space is full and the object is not a large object.
2871 AllocationSpace retry_space =
2872 (space != NEW_SPACE) ? space : TargetSpaceId(map->instance_type());
John Reck59135872010-11-02 12:39:01 -07002873 Object* result;
2874 { MaybeObject* maybe_result =
2875 AllocateRaw(map->instance_size(), space, retry_space);
2876 if (!maybe_result->ToObject(&result)) return maybe_result;
2877 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002878 HeapObject::cast(result)->set_map(map);
Steve Block3ce2e202009-11-05 08:53:23 +00002879#ifdef ENABLE_LOGGING_AND_PROFILING
2880 ProducerHeapProfile::RecordJSObjectAllocation(result);
2881#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00002882 return result;
2883}
2884
2885
John Reck59135872010-11-02 12:39:01 -07002886MaybeObject* Heap::InitializeFunction(JSFunction* function,
2887 SharedFunctionInfo* shared,
2888 Object* prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002889 ASSERT(!prototype->IsMap());
2890 function->initialize_properties();
2891 function->initialize_elements();
2892 function->set_shared(shared);
Iain Merrick75681382010-08-19 15:07:18 +01002893 function->set_code(shared->code());
Steve Blocka7e24c12009-10-30 11:49:00 +00002894 function->set_prototype_or_initial_map(prototype);
2895 function->set_context(undefined_value());
Leon Clarke4515c472010-02-03 11:58:03 +00002896 function->set_literals(empty_fixed_array());
Ben Murdochb0fe1622011-05-05 13:52:32 +01002897 function->set_next_function_link(undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002898 return function;
2899}
2900
2901
John Reck59135872010-11-02 12:39:01 -07002902MaybeObject* Heap::AllocateFunctionPrototype(JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002903 // Allocate the prototype. Make sure to use the object function
2904 // from the function's context, since the function can be from a
2905 // different context.
2906 JSFunction* object_function =
2907 function->context()->global_context()->object_function();
John Reck59135872010-11-02 12:39:01 -07002908 Object* prototype;
2909 { MaybeObject* maybe_prototype = AllocateJSObject(object_function);
2910 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
2911 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002912 // When creating the prototype for the function we must set its
2913 // constructor to the function.
John Reck59135872010-11-02 12:39:01 -07002914 Object* result;
2915 { MaybeObject* maybe_result =
Ben Murdoche0cee9b2011-05-25 10:26:03 +01002916 JSObject::cast(prototype)->SetLocalPropertyIgnoreAttributes(
2917 constructor_symbol(), function, DONT_ENUM);
John Reck59135872010-11-02 12:39:01 -07002918 if (!maybe_result->ToObject(&result)) return maybe_result;
2919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002920 return prototype;
2921}
2922
2923
John Reck59135872010-11-02 12:39:01 -07002924MaybeObject* Heap::AllocateFunction(Map* function_map,
2925 SharedFunctionInfo* shared,
2926 Object* prototype,
2927 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00002928 AllocationSpace space =
2929 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
John Reck59135872010-11-02 12:39:01 -07002930 Object* result;
2931 { MaybeObject* maybe_result = Allocate(function_map, space);
2932 if (!maybe_result->ToObject(&result)) return maybe_result;
2933 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002934 return InitializeFunction(JSFunction::cast(result), shared, prototype);
2935}
2936
2937
John Reck59135872010-11-02 12:39:01 -07002938MaybeObject* Heap::AllocateArgumentsObject(Object* callee, int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002939 // To get fast allocation and map sharing for arguments objects we
2940 // allocate them based on an arguments boilerplate.
2941
2942 // This calls Copy directly rather than using Heap::AllocateRaw so we
2943 // duplicate the check here.
2944 ASSERT(allocation_allowed_ && gc_state_ == NOT_IN_GC);
2945
2946 JSObject* boilerplate =
2947 Top::context()->global_context()->arguments_boilerplate();
2948
Leon Clarkee46be812010-01-19 14:06:41 +00002949 // Check that the size of the boilerplate matches our
2950 // expectations. The ArgumentsAccessStub::GenerateNewObject relies
2951 // on the size being a known constant.
2952 ASSERT(kArgumentsObjectSize == boilerplate->map()->instance_size());
2953
2954 // Do the allocation.
John Reck59135872010-11-02 12:39:01 -07002955 Object* result;
2956 { MaybeObject* maybe_result =
2957 AllocateRaw(kArgumentsObjectSize, NEW_SPACE, OLD_POINTER_SPACE);
2958 if (!maybe_result->ToObject(&result)) return maybe_result;
2959 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002960
2961 // Copy the content. The arguments boilerplate doesn't have any
2962 // fields that point to new space so it's safe to skip the write
2963 // barrier here.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002964 CopyBlock(HeapObject::cast(result)->address(),
2965 boilerplate->address(),
Leon Clarkee46be812010-01-19 14:06:41 +00002966 kArgumentsObjectSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00002967
2968 // Set the two properties.
2969 JSObject::cast(result)->InObjectPropertyAtPut(arguments_callee_index,
2970 callee);
2971 JSObject::cast(result)->InObjectPropertyAtPut(arguments_length_index,
2972 Smi::FromInt(length),
2973 SKIP_WRITE_BARRIER);
2974
2975 // Check the state of the object
2976 ASSERT(JSObject::cast(result)->HasFastProperties());
2977 ASSERT(JSObject::cast(result)->HasFastElements());
2978
2979 return result;
2980}
2981
2982
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002983static bool HasDuplicates(DescriptorArray* descriptors) {
2984 int count = descriptors->number_of_descriptors();
2985 if (count > 1) {
2986 String* prev_key = descriptors->GetKey(0);
2987 for (int i = 1; i != count; i++) {
2988 String* current_key = descriptors->GetKey(i);
2989 if (prev_key == current_key) return true;
2990 prev_key = current_key;
2991 }
2992 }
2993 return false;
2994}
2995
2996
John Reck59135872010-11-02 12:39:01 -07002997MaybeObject* Heap::AllocateInitialMap(JSFunction* fun) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002998 ASSERT(!fun->has_initial_map());
2999
3000 // First create a new map with the size and number of in-object properties
3001 // suggested by the function.
3002 int instance_size = fun->shared()->CalculateInstanceSize();
3003 int in_object_properties = fun->shared()->CalculateInObjectProperties();
John Reck59135872010-11-02 12:39:01 -07003004 Object* map_obj;
3005 { MaybeObject* maybe_map_obj =
3006 Heap::AllocateMap(JS_OBJECT_TYPE, instance_size);
3007 if (!maybe_map_obj->ToObject(&map_obj)) return maybe_map_obj;
3008 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003009
3010 // Fetch or allocate prototype.
3011 Object* prototype;
3012 if (fun->has_instance_prototype()) {
3013 prototype = fun->instance_prototype();
3014 } else {
John Reck59135872010-11-02 12:39:01 -07003015 { MaybeObject* maybe_prototype = AllocateFunctionPrototype(fun);
3016 if (!maybe_prototype->ToObject(&prototype)) return maybe_prototype;
3017 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003018 }
3019 Map* map = Map::cast(map_obj);
3020 map->set_inobject_properties(in_object_properties);
3021 map->set_unused_property_fields(in_object_properties);
3022 map->set_prototype(prototype);
Steve Block8defd9f2010-07-08 12:39:36 +01003023 ASSERT(map->has_fast_elements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003024
Andrei Popescu402d9372010-02-26 13:31:12 +00003025 // If the function has only simple this property assignments add
3026 // field descriptors for these to the initial map as the object
3027 // cannot be constructed without having these properties. Guard by
3028 // the inline_new flag so we only change the map if we generate a
3029 // specialized construct stub.
Steve Blocka7e24c12009-10-30 11:49:00 +00003030 ASSERT(in_object_properties <= Map::kMaxPreAllocatedPropertyFields);
Andrei Popescu402d9372010-02-26 13:31:12 +00003031 if (fun->shared()->CanGenerateInlineConstructor(prototype)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003032 int count = fun->shared()->this_property_assignments_count();
3033 if (count > in_object_properties) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003034 // Inline constructor can only handle inobject properties.
3035 fun->shared()->ForbidInlineConstructor();
3036 } else {
John Reck59135872010-11-02 12:39:01 -07003037 Object* descriptors_obj;
3038 { MaybeObject* maybe_descriptors_obj = DescriptorArray::Allocate(count);
3039 if (!maybe_descriptors_obj->ToObject(&descriptors_obj)) {
3040 return maybe_descriptors_obj;
3041 }
3042 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003043 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_obj);
3044 for (int i = 0; i < count; i++) {
3045 String* name = fun->shared()->GetThisPropertyAssignmentName(i);
3046 ASSERT(name->IsSymbol());
3047 FieldDescriptor field(name, i, NONE);
3048 field.SetEnumerationIndex(i);
3049 descriptors->Set(i, &field);
3050 }
3051 descriptors->SetNextEnumerationIndex(count);
3052 descriptors->SortUnchecked();
3053
3054 // The descriptors may contain duplicates because the compiler does not
3055 // guarantee the uniqueness of property names (it would have required
3056 // quadratic time). Once the descriptors are sorted we can check for
3057 // duplicates in linear time.
3058 if (HasDuplicates(descriptors)) {
3059 fun->shared()->ForbidInlineConstructor();
3060 } else {
3061 map->set_instance_descriptors(descriptors);
3062 map->set_pre_allocated_property_fields(count);
3063 map->set_unused_property_fields(in_object_properties - count);
3064 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003065 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003066 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003067
3068 fun->shared()->StartInobjectSlackTracking(map);
3069
Steve Blocka7e24c12009-10-30 11:49:00 +00003070 return map;
3071}
3072
3073
3074void Heap::InitializeJSObjectFromMap(JSObject* obj,
3075 FixedArray* properties,
3076 Map* map) {
3077 obj->set_properties(properties);
3078 obj->initialize_elements();
3079 // TODO(1240798): Initialize the object's body using valid initial values
3080 // according to the object's initial map. For example, if the map's
3081 // instance type is JS_ARRAY_TYPE, the length field should be initialized
3082 // to a number (eg, Smi::FromInt(0)) and the elements initialized to a
3083 // fixed array (eg, Heap::empty_fixed_array()). Currently, the object
3084 // verification code has to cope with (temporarily) invalid objects. See
3085 // for example, JSArray::JSArrayVerify).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003086 Object* filler;
3087 // We cannot always fill with one_pointer_filler_map because objects
3088 // created from API functions expect their internal fields to be initialized
3089 // with undefined_value.
3090 if (map->constructor()->IsJSFunction() &&
3091 JSFunction::cast(map->constructor())->shared()->
3092 IsInobjectSlackTrackingInProgress()) {
3093 // We might want to shrink the object later.
3094 ASSERT(obj->GetInternalFieldCount() == 0);
3095 filler = Heap::one_pointer_filler_map();
3096 } else {
3097 filler = Heap::undefined_value();
3098 }
3099 obj->InitializeBody(map->instance_size(), filler);
Steve Blocka7e24c12009-10-30 11:49:00 +00003100}
3101
3102
John Reck59135872010-11-02 12:39:01 -07003103MaybeObject* Heap::AllocateJSObjectFromMap(Map* map, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003104 // JSFunctions should be allocated using AllocateFunction to be
3105 // properly initialized.
3106 ASSERT(map->instance_type() != JS_FUNCTION_TYPE);
3107
Steve Block8defd9f2010-07-08 12:39:36 +01003108 // Both types of global objects should be allocated using
3109 // AllocateGlobalObject to be properly initialized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003110 ASSERT(map->instance_type() != JS_GLOBAL_OBJECT_TYPE);
3111 ASSERT(map->instance_type() != JS_BUILTINS_OBJECT_TYPE);
3112
3113 // Allocate the backing storage for the properties.
3114 int prop_size =
3115 map->pre_allocated_property_fields() +
3116 map->unused_property_fields() -
3117 map->inobject_properties();
3118 ASSERT(prop_size >= 0);
John Reck59135872010-11-02 12:39:01 -07003119 Object* properties;
3120 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, pretenure);
3121 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3122 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003123
3124 // Allocate the JSObject.
3125 AllocationSpace space =
3126 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
3127 if (map->instance_size() > MaxObjectSizeInPagedSpace()) space = LO_SPACE;
John Reck59135872010-11-02 12:39:01 -07003128 Object* obj;
3129 { MaybeObject* maybe_obj = Allocate(map, space);
3130 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3131 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003132
3133 // Initialize the JSObject.
3134 InitializeJSObjectFromMap(JSObject::cast(obj),
3135 FixedArray::cast(properties),
3136 map);
Steve Block8defd9f2010-07-08 12:39:36 +01003137 ASSERT(JSObject::cast(obj)->HasFastElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003138 return obj;
3139}
3140
3141
John Reck59135872010-11-02 12:39:01 -07003142MaybeObject* Heap::AllocateJSObject(JSFunction* constructor,
3143 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003144 // Allocate the initial map if absent.
3145 if (!constructor->has_initial_map()) {
John Reck59135872010-11-02 12:39:01 -07003146 Object* initial_map;
3147 { MaybeObject* maybe_initial_map = AllocateInitialMap(constructor);
3148 if (!maybe_initial_map->ToObject(&initial_map)) return maybe_initial_map;
3149 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003150 constructor->set_initial_map(Map::cast(initial_map));
3151 Map::cast(initial_map)->set_constructor(constructor);
3152 }
3153 // Allocate the object based on the constructors initial map.
John Reck59135872010-11-02 12:39:01 -07003154 MaybeObject* result =
Steve Blocka7e24c12009-10-30 11:49:00 +00003155 AllocateJSObjectFromMap(constructor->initial_map(), pretenure);
John Reck59135872010-11-02 12:39:01 -07003156#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00003157 // Make sure result is NOT a global object if valid.
John Reck59135872010-11-02 12:39:01 -07003158 Object* non_failure;
3159 ASSERT(!result->ToObject(&non_failure) || !non_failure->IsGlobalObject());
3160#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003161 return result;
3162}
3163
3164
John Reck59135872010-11-02 12:39:01 -07003165MaybeObject* Heap::AllocateGlobalObject(JSFunction* constructor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003166 ASSERT(constructor->has_initial_map());
3167 Map* map = constructor->initial_map();
3168
3169 // Make sure no field properties are described in the initial map.
3170 // This guarantees us that normalizing the properties does not
3171 // require us to change property values to JSGlobalPropertyCells.
3172 ASSERT(map->NextFreePropertyIndex() == 0);
3173
3174 // Make sure we don't have a ton of pre-allocated slots in the
3175 // global objects. They will be unused once we normalize the object.
3176 ASSERT(map->unused_property_fields() == 0);
3177 ASSERT(map->inobject_properties() == 0);
3178
3179 // Initial size of the backing store to avoid resize of the storage during
3180 // bootstrapping. The size differs between the JS global object ad the
3181 // builtins object.
3182 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
3183
3184 // Allocate a dictionary object for backing storage.
John Reck59135872010-11-02 12:39:01 -07003185 Object* obj;
3186 { MaybeObject* maybe_obj =
3187 StringDictionary::Allocate(
3188 map->NumberOfDescribedProperties() * 2 + initial_size);
3189 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3190 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003191 StringDictionary* dictionary = StringDictionary::cast(obj);
3192
3193 // The global object might be created from an object template with accessors.
3194 // Fill these accessors into the dictionary.
3195 DescriptorArray* descs = map->instance_descriptors();
3196 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3197 PropertyDetails details = descs->GetDetails(i);
3198 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
3199 PropertyDetails d =
3200 PropertyDetails(details.attributes(), CALLBACKS, details.index());
3201 Object* value = descs->GetCallbacksObject(i);
John Reck59135872010-11-02 12:39:01 -07003202 { MaybeObject* maybe_value = Heap::AllocateJSGlobalPropertyCell(value);
3203 if (!maybe_value->ToObject(&value)) return maybe_value;
3204 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003205
John Reck59135872010-11-02 12:39:01 -07003206 Object* result;
3207 { MaybeObject* maybe_result = dictionary->Add(descs->GetKey(i), value, d);
3208 if (!maybe_result->ToObject(&result)) return maybe_result;
3209 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003210 dictionary = StringDictionary::cast(result);
3211 }
3212
3213 // Allocate the global object and initialize it with the backing store.
John Reck59135872010-11-02 12:39:01 -07003214 { MaybeObject* maybe_obj = Allocate(map, OLD_POINTER_SPACE);
3215 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3216 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003217 JSObject* global = JSObject::cast(obj);
3218 InitializeJSObjectFromMap(global, dictionary, map);
3219
3220 // Create a new map for the global object.
John Reck59135872010-11-02 12:39:01 -07003221 { MaybeObject* maybe_obj = map->CopyDropDescriptors();
3222 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3223 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003224 Map* new_map = Map::cast(obj);
3225
3226 // Setup the global object as a normalized object.
3227 global->set_map(new_map);
3228 global->map()->set_instance_descriptors(Heap::empty_descriptor_array());
3229 global->set_properties(dictionary);
3230
3231 // Make sure result is a global object with properties in dictionary.
3232 ASSERT(global->IsGlobalObject());
3233 ASSERT(!global->HasFastProperties());
3234 return global;
3235}
3236
3237
John Reck59135872010-11-02 12:39:01 -07003238MaybeObject* Heap::CopyJSObject(JSObject* source) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003239 // Never used to copy functions. If functions need to be copied we
3240 // have to be careful to clear the literals array.
3241 ASSERT(!source->IsJSFunction());
3242
3243 // Make the clone.
3244 Map* map = source->map();
3245 int object_size = map->instance_size();
3246 Object* clone;
3247
3248 // If we're forced to always allocate, we use the general allocation
3249 // functions which may leave us with an object in old space.
3250 if (always_allocate()) {
John Reck59135872010-11-02 12:39:01 -07003251 { MaybeObject* maybe_clone =
3252 AllocateRaw(object_size, NEW_SPACE, OLD_POINTER_SPACE);
3253 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3254 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003255 Address clone_address = HeapObject::cast(clone)->address();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003256 CopyBlock(clone_address,
3257 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003258 object_size);
3259 // Update write barrier for all fields that lie beyond the header.
Steve Block6ded16b2010-05-10 14:33:55 +01003260 RecordWrites(clone_address,
3261 JSObject::kHeaderSize,
3262 (object_size - JSObject::kHeaderSize) / kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003263 } else {
John Reck59135872010-11-02 12:39:01 -07003264 { MaybeObject* maybe_clone = new_space_.AllocateRaw(object_size);
3265 if (!maybe_clone->ToObject(&clone)) return maybe_clone;
3266 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003267 ASSERT(Heap::InNewSpace(clone));
3268 // Since we know the clone is allocated in new space, we can copy
3269 // the contents without worrying about updating the write barrier.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003270 CopyBlock(HeapObject::cast(clone)->address(),
3271 source->address(),
Steve Blocka7e24c12009-10-30 11:49:00 +00003272 object_size);
3273 }
3274
3275 FixedArray* elements = FixedArray::cast(source->elements());
3276 FixedArray* properties = FixedArray::cast(source->properties());
3277 // Update elements if necessary.
Steve Block6ded16b2010-05-10 14:33:55 +01003278 if (elements->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003279 Object* elem;
3280 { MaybeObject* maybe_elem =
3281 (elements->map() == fixed_cow_array_map()) ?
3282 elements : CopyFixedArray(elements);
3283 if (!maybe_elem->ToObject(&elem)) return maybe_elem;
3284 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003285 JSObject::cast(clone)->set_elements(FixedArray::cast(elem));
3286 }
3287 // Update properties if necessary.
3288 if (properties->length() > 0) {
John Reck59135872010-11-02 12:39:01 -07003289 Object* prop;
3290 { MaybeObject* maybe_prop = CopyFixedArray(properties);
3291 if (!maybe_prop->ToObject(&prop)) return maybe_prop;
3292 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003293 JSObject::cast(clone)->set_properties(FixedArray::cast(prop));
3294 }
3295 // Return the new clone.
Steve Block3ce2e202009-11-05 08:53:23 +00003296#ifdef ENABLE_LOGGING_AND_PROFILING
3297 ProducerHeapProfile::RecordJSObjectAllocation(clone);
3298#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003299 return clone;
3300}
3301
3302
John Reck59135872010-11-02 12:39:01 -07003303MaybeObject* Heap::ReinitializeJSGlobalProxy(JSFunction* constructor,
3304 JSGlobalProxy* object) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003305 ASSERT(constructor->has_initial_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003306 Map* map = constructor->initial_map();
3307
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003308 // Check that the already allocated object has the same size and type as
Steve Blocka7e24c12009-10-30 11:49:00 +00003309 // objects allocated using the constructor.
3310 ASSERT(map->instance_size() == object->map()->instance_size());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003311 ASSERT(map->instance_type() == object->map()->instance_type());
Steve Blocka7e24c12009-10-30 11:49:00 +00003312
3313 // Allocate the backing storage for the properties.
3314 int prop_size = map->unused_property_fields() - map->inobject_properties();
John Reck59135872010-11-02 12:39:01 -07003315 Object* properties;
3316 { MaybeObject* maybe_properties = AllocateFixedArray(prop_size, TENURED);
3317 if (!maybe_properties->ToObject(&properties)) return maybe_properties;
3318 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003319
3320 // Reset the map for the object.
3321 object->set_map(constructor->initial_map());
3322
3323 // Reinitialize the object from the constructor map.
3324 InitializeJSObjectFromMap(object, FixedArray::cast(properties), map);
3325 return object;
3326}
3327
3328
John Reck59135872010-11-02 12:39:01 -07003329MaybeObject* Heap::AllocateStringFromAscii(Vector<const char> string,
3330 PretenureFlag pretenure) {
3331 Object* result;
3332 { MaybeObject* maybe_result =
3333 AllocateRawAsciiString(string.length(), pretenure);
3334 if (!maybe_result->ToObject(&result)) return maybe_result;
3335 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003336
3337 // Copy the characters into the new object.
3338 SeqAsciiString* string_result = SeqAsciiString::cast(result);
3339 for (int i = 0; i < string.length(); i++) {
3340 string_result->SeqAsciiStringSet(i, string[i]);
3341 }
3342 return result;
3343}
3344
3345
Steve Block9fac8402011-05-12 15:51:54 +01003346MaybeObject* Heap::AllocateStringFromUtf8Slow(Vector<const char> string,
3347 PretenureFlag pretenure) {
Leon Clarkeac952652010-07-15 11:15:24 +01003348 // V8 only supports characters in the Basic Multilingual Plane.
3349 const uc32 kMaxSupportedChar = 0xFFFF;
Steve Blocka7e24c12009-10-30 11:49:00 +00003350 // Count the number of characters in the UTF-8 string and check if
3351 // it is an ASCII string.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08003352 Access<ScannerConstants::Utf8Decoder>
3353 decoder(ScannerConstants::utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00003354 decoder->Reset(string.start(), string.length());
3355 int chars = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003356 while (decoder->has_more()) {
Steve Block9fac8402011-05-12 15:51:54 +01003357 decoder->GetNext();
Steve Blocka7e24c12009-10-30 11:49:00 +00003358 chars++;
3359 }
3360
John Reck59135872010-11-02 12:39:01 -07003361 Object* result;
3362 { MaybeObject* maybe_result = AllocateRawTwoByteString(chars, pretenure);
3363 if (!maybe_result->ToObject(&result)) return maybe_result;
3364 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003365
3366 // Convert and copy the characters into the new object.
3367 String* string_result = String::cast(result);
3368 decoder->Reset(string.start(), string.length());
3369 for (int i = 0; i < chars; i++) {
3370 uc32 r = decoder->GetNext();
Leon Clarkeac952652010-07-15 11:15:24 +01003371 if (r > kMaxSupportedChar) { r = unibrow::Utf8::kBadChar; }
Steve Blocka7e24c12009-10-30 11:49:00 +00003372 string_result->Set(i, r);
3373 }
3374 return result;
3375}
3376
3377
John Reck59135872010-11-02 12:39:01 -07003378MaybeObject* Heap::AllocateStringFromTwoByte(Vector<const uc16> string,
3379 PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003380 // Check if the string is an ASCII string.
John Reck59135872010-11-02 12:39:01 -07003381 MaybeObject* maybe_result;
Steve Block9fac8402011-05-12 15:51:54 +01003382 if (String::IsAscii(string.start(), string.length())) {
John Reck59135872010-11-02 12:39:01 -07003383 maybe_result = AllocateRawAsciiString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00003384 } else { // It's not an ASCII string.
John Reck59135872010-11-02 12:39:01 -07003385 maybe_result = AllocateRawTwoByteString(string.length(), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00003386 }
John Reck59135872010-11-02 12:39:01 -07003387 Object* result;
3388 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003389
3390 // Copy the characters into the new object, which may be either ASCII or
3391 // UTF-16.
3392 String* string_result = String::cast(result);
3393 for (int i = 0; i < string.length(); i++) {
3394 string_result->Set(i, string[i]);
3395 }
3396 return result;
3397}
3398
3399
3400Map* Heap::SymbolMapForString(String* string) {
3401 // If the string is in new space it cannot be used as a symbol.
3402 if (InNewSpace(string)) return NULL;
3403
3404 // Find the corresponding symbol map for strings.
3405 Map* map = string->map();
Steve Blockd0582a62009-12-15 09:54:21 +00003406 if (map == ascii_string_map()) return ascii_symbol_map();
3407 if (map == string_map()) return symbol_map();
3408 if (map == cons_string_map()) return cons_symbol_map();
3409 if (map == cons_ascii_string_map()) return cons_ascii_symbol_map();
3410 if (map == external_string_map()) return external_symbol_map();
3411 if (map == external_ascii_string_map()) return external_ascii_symbol_map();
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01003412 if (map == external_string_with_ascii_data_map()) {
3413 return external_symbol_with_ascii_data_map();
3414 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003415
3416 // No match found.
3417 return NULL;
3418}
3419
3420
John Reck59135872010-11-02 12:39:01 -07003421MaybeObject* Heap::AllocateInternalSymbol(unibrow::CharacterStream* buffer,
3422 int chars,
3423 uint32_t hash_field) {
Leon Clarkee46be812010-01-19 14:06:41 +00003424 ASSERT(chars >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003425 // Ensure the chars matches the number of characters in the buffer.
3426 ASSERT(static_cast<unsigned>(chars) == buffer->Length());
3427 // Determine whether the string is ascii.
3428 bool is_ascii = true;
Leon Clarkee46be812010-01-19 14:06:41 +00003429 while (buffer->has_more()) {
3430 if (buffer->GetNext() > unibrow::Utf8::kMaxOneByteChar) {
3431 is_ascii = false;
3432 break;
3433 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003434 }
3435 buffer->Rewind();
3436
3437 // Compute map and object size.
3438 int size;
3439 Map* map;
3440
3441 if (is_ascii) {
Leon Clarkee46be812010-01-19 14:06:41 +00003442 if (chars > SeqAsciiString::kMaxLength) {
3443 return Failure::OutOfMemoryException();
3444 }
Steve Blockd0582a62009-12-15 09:54:21 +00003445 map = ascii_symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00003446 size = SeqAsciiString::SizeFor(chars);
3447 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00003448 if (chars > SeqTwoByteString::kMaxLength) {
3449 return Failure::OutOfMemoryException();
3450 }
Steve Blockd0582a62009-12-15 09:54:21 +00003451 map = symbol_map();
Steve Blocka7e24c12009-10-30 11:49:00 +00003452 size = SeqTwoByteString::SizeFor(chars);
3453 }
3454
3455 // Allocate string.
John Reck59135872010-11-02 12:39:01 -07003456 Object* result;
3457 { MaybeObject* maybe_result = (size > MaxObjectSizeInPagedSpace())
3458 ? lo_space_->AllocateRaw(size)
3459 : old_data_space_->AllocateRaw(size);
3460 if (!maybe_result->ToObject(&result)) return maybe_result;
3461 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003462
3463 reinterpret_cast<HeapObject*>(result)->set_map(map);
Steve Blockd0582a62009-12-15 09:54:21 +00003464 // Set length and hash fields of the allocated string.
Steve Blocka7e24c12009-10-30 11:49:00 +00003465 String* answer = String::cast(result);
Steve Blockd0582a62009-12-15 09:54:21 +00003466 answer->set_length(chars);
3467 answer->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +00003468
3469 ASSERT_EQ(size, answer->Size());
3470
3471 // Fill in the characters.
3472 for (int i = 0; i < chars; i++) {
3473 answer->Set(i, buffer->GetNext());
3474 }
3475 return answer;
3476}
3477
3478
John Reck59135872010-11-02 12:39:01 -07003479MaybeObject* Heap::AllocateRawAsciiString(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003480 if (length < 0 || length > SeqAsciiString::kMaxLength) {
3481 return Failure::OutOfMemoryException();
3482 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003483
3484 int size = SeqAsciiString::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00003485 ASSERT(size <= SeqAsciiString::kMaxSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003486
Leon Clarkee46be812010-01-19 14:06:41 +00003487 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3488 AllocationSpace retry_space = OLD_DATA_SPACE;
3489
Steve Blocka7e24c12009-10-30 11:49:00 +00003490 if (space == NEW_SPACE) {
Leon Clarkee46be812010-01-19 14:06:41 +00003491 if (size > kMaxObjectSizeInNewSpace) {
3492 // Allocate in large object space, retry space will be ignored.
3493 space = LO_SPACE;
3494 } else if (size > MaxObjectSizeInPagedSpace()) {
3495 // Allocate in new space, retry in large object space.
3496 retry_space = LO_SPACE;
3497 }
3498 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
3499 space = LO_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00003500 }
John Reck59135872010-11-02 12:39:01 -07003501 Object* result;
3502 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
3503 if (!maybe_result->ToObject(&result)) return maybe_result;
3504 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003505
Steve Blocka7e24c12009-10-30 11:49:00 +00003506 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00003507 HeapObject::cast(result)->set_map(ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003508 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00003509 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003510 ASSERT_EQ(size, HeapObject::cast(result)->Size());
3511 return result;
3512}
3513
3514
John Reck59135872010-11-02 12:39:01 -07003515MaybeObject* Heap::AllocateRawTwoByteString(int length,
3516 PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003517 if (length < 0 || length > SeqTwoByteString::kMaxLength) {
3518 return Failure::OutOfMemoryException();
Steve Blocka7e24c12009-10-30 11:49:00 +00003519 }
Leon Clarkee46be812010-01-19 14:06:41 +00003520 int size = SeqTwoByteString::SizeFor(length);
3521 ASSERT(size <= SeqTwoByteString::kMaxSize);
3522 AllocationSpace space = (pretenure == TENURED) ? OLD_DATA_SPACE : NEW_SPACE;
3523 AllocationSpace retry_space = OLD_DATA_SPACE;
3524
3525 if (space == NEW_SPACE) {
3526 if (size > kMaxObjectSizeInNewSpace) {
3527 // Allocate in large object space, retry space will be ignored.
3528 space = LO_SPACE;
3529 } else if (size > MaxObjectSizeInPagedSpace()) {
3530 // Allocate in new space, retry in large object space.
3531 retry_space = LO_SPACE;
3532 }
3533 } else if (space == OLD_DATA_SPACE && size > MaxObjectSizeInPagedSpace()) {
3534 space = LO_SPACE;
3535 }
John Reck59135872010-11-02 12:39:01 -07003536 Object* result;
3537 { MaybeObject* maybe_result = AllocateRaw(size, space, retry_space);
3538 if (!maybe_result->ToObject(&result)) return maybe_result;
3539 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003540
Steve Blocka7e24c12009-10-30 11:49:00 +00003541 // Partially initialize the object.
Steve Blockd0582a62009-12-15 09:54:21 +00003542 HeapObject::cast(result)->set_map(string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003543 String::cast(result)->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +00003544 String::cast(result)->set_hash_field(String::kEmptyHashField);
Steve Blocka7e24c12009-10-30 11:49:00 +00003545 ASSERT_EQ(size, HeapObject::cast(result)->Size());
3546 return result;
3547}
3548
3549
John Reck59135872010-11-02 12:39:01 -07003550MaybeObject* Heap::AllocateEmptyFixedArray() {
Steve Blocka7e24c12009-10-30 11:49:00 +00003551 int size = FixedArray::SizeFor(0);
John Reck59135872010-11-02 12:39:01 -07003552 Object* result;
3553 { MaybeObject* maybe_result =
3554 AllocateRaw(size, OLD_DATA_SPACE, OLD_DATA_SPACE);
3555 if (!maybe_result->ToObject(&result)) return maybe_result;
3556 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003557 // Initialize the object.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003558 reinterpret_cast<FixedArray*>(result)->set_map(fixed_array_map());
3559 reinterpret_cast<FixedArray*>(result)->set_length(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003560 return result;
3561}
3562
3563
John Reck59135872010-11-02 12:39:01 -07003564MaybeObject* Heap::AllocateRawFixedArray(int length) {
Leon Clarkee46be812010-01-19 14:06:41 +00003565 if (length < 0 || length > FixedArray::kMaxLength) {
3566 return Failure::OutOfMemoryException();
3567 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003568 ASSERT(length > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003569 // Use the general function if we're forced to always allocate.
3570 if (always_allocate()) return AllocateFixedArray(length, TENURED);
3571 // Allocate the raw data for a fixed array.
3572 int size = FixedArray::SizeFor(length);
3573 return size <= kMaxObjectSizeInNewSpace
3574 ? new_space_.AllocateRaw(size)
3575 : lo_space_->AllocateRawFixedArray(size);
3576}
3577
3578
John Reck59135872010-11-02 12:39:01 -07003579MaybeObject* Heap::CopyFixedArrayWithMap(FixedArray* src, Map* map) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003580 int len = src->length();
John Reck59135872010-11-02 12:39:01 -07003581 Object* obj;
3582 { MaybeObject* maybe_obj = AllocateRawFixedArray(len);
3583 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3584 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003585 if (Heap::InNewSpace(obj)) {
3586 HeapObject* dst = HeapObject::cast(obj);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003587 dst->set_map(map);
3588 CopyBlock(dst->address() + kPointerSize,
3589 src->address() + kPointerSize,
3590 FixedArray::SizeFor(len) - kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00003591 return obj;
3592 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003593 HeapObject::cast(obj)->set_map(map);
Steve Blocka7e24c12009-10-30 11:49:00 +00003594 FixedArray* result = FixedArray::cast(obj);
3595 result->set_length(len);
Leon Clarke4515c472010-02-03 11:58:03 +00003596
Steve Blocka7e24c12009-10-30 11:49:00 +00003597 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003598 AssertNoAllocation no_gc;
3599 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003600 for (int i = 0; i < len; i++) result->set(i, src->get(i), mode);
3601 return result;
3602}
3603
3604
John Reck59135872010-11-02 12:39:01 -07003605MaybeObject* Heap::AllocateFixedArray(int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003606 ASSERT(length >= 0);
3607 if (length == 0) return empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07003608 Object* result;
3609 { MaybeObject* maybe_result = AllocateRawFixedArray(length);
3610 if (!maybe_result->ToObject(&result)) return maybe_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003611 }
John Reck59135872010-11-02 12:39:01 -07003612 // Initialize header.
3613 FixedArray* array = reinterpret_cast<FixedArray*>(result);
3614 array->set_map(fixed_array_map());
3615 array->set_length(length);
3616 // Initialize body.
3617 ASSERT(!Heap::InNewSpace(undefined_value()));
3618 MemsetPointer(array->data_start(), undefined_value(), length);
Steve Blocka7e24c12009-10-30 11:49:00 +00003619 return result;
3620}
3621
3622
John Reck59135872010-11-02 12:39:01 -07003623MaybeObject* Heap::AllocateRawFixedArray(int length, PretenureFlag pretenure) {
Leon Clarkee46be812010-01-19 14:06:41 +00003624 if (length < 0 || length > FixedArray::kMaxLength) {
3625 return Failure::OutOfMemoryException();
3626 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003627
Leon Clarkee46be812010-01-19 14:06:41 +00003628 AllocationSpace space =
3629 (pretenure == TENURED) ? OLD_POINTER_SPACE : NEW_SPACE;
Steve Blocka7e24c12009-10-30 11:49:00 +00003630 int size = FixedArray::SizeFor(length);
Leon Clarkee46be812010-01-19 14:06:41 +00003631 if (space == NEW_SPACE && size > kMaxObjectSizeInNewSpace) {
3632 // Too big for new space.
3633 space = LO_SPACE;
3634 } else if (space == OLD_POINTER_SPACE &&
3635 size > MaxObjectSizeInPagedSpace()) {
3636 // Too big for old pointer space.
3637 space = LO_SPACE;
3638 }
3639
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003640 AllocationSpace retry_space =
3641 (size <= MaxObjectSizeInPagedSpace()) ? OLD_POINTER_SPACE : LO_SPACE;
3642
3643 return AllocateRaw(size, space, retry_space);
Steve Blocka7e24c12009-10-30 11:49:00 +00003644}
3645
3646
John Reck59135872010-11-02 12:39:01 -07003647MUST_USE_RESULT static MaybeObject* AllocateFixedArrayWithFiller(
3648 int length,
3649 PretenureFlag pretenure,
3650 Object* filler) {
Steve Block6ded16b2010-05-10 14:33:55 +01003651 ASSERT(length >= 0);
3652 ASSERT(Heap::empty_fixed_array()->IsFixedArray());
3653 if (length == 0) return Heap::empty_fixed_array();
3654
3655 ASSERT(!Heap::InNewSpace(filler));
John Reck59135872010-11-02 12:39:01 -07003656 Object* result;
3657 { MaybeObject* maybe_result = Heap::AllocateRawFixedArray(length, pretenure);
3658 if (!maybe_result->ToObject(&result)) return maybe_result;
3659 }
Steve Block6ded16b2010-05-10 14:33:55 +01003660
3661 HeapObject::cast(result)->set_map(Heap::fixed_array_map());
3662 FixedArray* array = FixedArray::cast(result);
3663 array->set_length(length);
3664 MemsetPointer(array->data_start(), filler, length);
3665 return array;
3666}
3667
3668
John Reck59135872010-11-02 12:39:01 -07003669MaybeObject* Heap::AllocateFixedArray(int length, PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01003670 return AllocateFixedArrayWithFiller(length, pretenure, undefined_value());
3671}
3672
3673
John Reck59135872010-11-02 12:39:01 -07003674MaybeObject* Heap::AllocateFixedArrayWithHoles(int length,
3675 PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01003676 return AllocateFixedArrayWithFiller(length, pretenure, the_hole_value());
3677}
3678
3679
John Reck59135872010-11-02 12:39:01 -07003680MaybeObject* Heap::AllocateUninitializedFixedArray(int length) {
Steve Block6ded16b2010-05-10 14:33:55 +01003681 if (length == 0) return empty_fixed_array();
3682
John Reck59135872010-11-02 12:39:01 -07003683 Object* obj;
3684 { MaybeObject* maybe_obj = AllocateRawFixedArray(length);
3685 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3686 }
Steve Block6ded16b2010-05-10 14:33:55 +01003687
3688 reinterpret_cast<FixedArray*>(obj)->set_map(fixed_array_map());
3689 FixedArray::cast(obj)->set_length(length);
3690 return obj;
3691}
3692
3693
John Reck59135872010-11-02 12:39:01 -07003694MaybeObject* Heap::AllocateHashTable(int length, PretenureFlag pretenure) {
3695 Object* result;
3696 { MaybeObject* maybe_result = Heap::AllocateFixedArray(length, pretenure);
3697 if (!maybe_result->ToObject(&result)) return maybe_result;
3698 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003699 reinterpret_cast<HeapObject*>(result)->set_map(hash_table_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00003700 ASSERT(result->IsHashTable());
3701 return result;
3702}
3703
3704
John Reck59135872010-11-02 12:39:01 -07003705MaybeObject* Heap::AllocateGlobalContext() {
3706 Object* result;
3707 { MaybeObject* maybe_result =
3708 Heap::AllocateFixedArray(Context::GLOBAL_CONTEXT_SLOTS);
3709 if (!maybe_result->ToObject(&result)) return maybe_result;
3710 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003711 Context* context = reinterpret_cast<Context*>(result);
3712 context->set_map(global_context_map());
3713 ASSERT(context->IsGlobalContext());
3714 ASSERT(result->IsContext());
3715 return result;
3716}
3717
3718
John Reck59135872010-11-02 12:39:01 -07003719MaybeObject* Heap::AllocateFunctionContext(int length, JSFunction* function) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003720 ASSERT(length >= Context::MIN_CONTEXT_SLOTS);
John Reck59135872010-11-02 12:39:01 -07003721 Object* result;
3722 { MaybeObject* maybe_result = Heap::AllocateFixedArray(length);
3723 if (!maybe_result->ToObject(&result)) return maybe_result;
3724 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003725 Context* context = reinterpret_cast<Context*>(result);
3726 context->set_map(context_map());
3727 context->set_closure(function);
3728 context->set_fcontext(context);
3729 context->set_previous(NULL);
3730 context->set_extension(NULL);
3731 context->set_global(function->context()->global());
3732 ASSERT(!context->IsGlobalContext());
3733 ASSERT(context->is_function_context());
3734 ASSERT(result->IsContext());
3735 return result;
3736}
3737
3738
John Reck59135872010-11-02 12:39:01 -07003739MaybeObject* Heap::AllocateWithContext(Context* previous,
3740 JSObject* extension,
3741 bool is_catch_context) {
3742 Object* result;
3743 { MaybeObject* maybe_result =
3744 Heap::AllocateFixedArray(Context::MIN_CONTEXT_SLOTS);
3745 if (!maybe_result->ToObject(&result)) return maybe_result;
3746 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003747 Context* context = reinterpret_cast<Context*>(result);
3748 context->set_map(is_catch_context ? catch_context_map() : context_map());
3749 context->set_closure(previous->closure());
3750 context->set_fcontext(previous->fcontext());
3751 context->set_previous(previous);
3752 context->set_extension(extension);
3753 context->set_global(previous->global());
3754 ASSERT(!context->IsGlobalContext());
3755 ASSERT(!context->is_function_context());
3756 ASSERT(result->IsContext());
3757 return result;
3758}
3759
3760
John Reck59135872010-11-02 12:39:01 -07003761MaybeObject* Heap::AllocateStruct(InstanceType type) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003762 Map* map;
3763 switch (type) {
3764#define MAKE_CASE(NAME, Name, name) case NAME##_TYPE: map = name##_map(); break;
3765STRUCT_LIST(MAKE_CASE)
3766#undef MAKE_CASE
3767 default:
3768 UNREACHABLE();
3769 return Failure::InternalError();
3770 }
3771 int size = map->instance_size();
3772 AllocationSpace space =
3773 (size > MaxObjectSizeInPagedSpace()) ? LO_SPACE : OLD_POINTER_SPACE;
John Reck59135872010-11-02 12:39:01 -07003774 Object* result;
3775 { MaybeObject* maybe_result = Heap::Allocate(map, space);
3776 if (!maybe_result->ToObject(&result)) return maybe_result;
3777 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003778 Struct::cast(result)->InitializeBody(size);
3779 return result;
3780}
3781
3782
3783bool Heap::IdleNotification() {
3784 static const int kIdlesBeforeScavenge = 4;
3785 static const int kIdlesBeforeMarkSweep = 7;
3786 static const int kIdlesBeforeMarkCompact = 8;
Ben Murdochdb5a90a2011-01-06 18:27:03 +00003787 static const int kMaxIdleCount = kIdlesBeforeMarkCompact + 1;
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003788 static const unsigned int kGCsBetweenCleanup = 4;
Steve Blocka7e24c12009-10-30 11:49:00 +00003789 static int number_idle_notifications = 0;
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003790 static unsigned int last_gc_count = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003791
Steve Block6ded16b2010-05-10 14:33:55 +01003792 bool uncommit = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00003793 bool finished = false;
3794
Ben Murdochdb5a90a2011-01-06 18:27:03 +00003795 // Reset the number of idle notifications received when a number of
3796 // GCs have taken place. This allows another round of cleanup based
3797 // on idle notifications if enough work has been carried out to
3798 // provoke a number of garbage collections.
Ben Murdoche0cee9b2011-05-25 10:26:03 +01003799 if (gc_count_ - last_gc_count < kGCsBetweenCleanup) {
Ben Murdochdb5a90a2011-01-06 18:27:03 +00003800 number_idle_notifications =
3801 Min(number_idle_notifications + 1, kMaxIdleCount);
Steve Blocka7e24c12009-10-30 11:49:00 +00003802 } else {
3803 number_idle_notifications = 0;
3804 last_gc_count = gc_count_;
3805 }
3806
3807 if (number_idle_notifications == kIdlesBeforeScavenge) {
Steve Block6ded16b2010-05-10 14:33:55 +01003808 if (contexts_disposed_ > 0) {
3809 HistogramTimerScope scope(&Counters::gc_context);
3810 CollectAllGarbage(false);
3811 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +01003812 CollectGarbage(NEW_SPACE);
Steve Block6ded16b2010-05-10 14:33:55 +01003813 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003814 new_space_.Shrink();
3815 last_gc_count = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003816 } else if (number_idle_notifications == kIdlesBeforeMarkSweep) {
Steve Blockd0582a62009-12-15 09:54:21 +00003817 // Before doing the mark-sweep collections we clear the
3818 // compilation cache to avoid hanging on to source code and
3819 // generated code for cached functions.
3820 CompilationCache::Clear();
3821
Steve Blocka7e24c12009-10-30 11:49:00 +00003822 CollectAllGarbage(false);
3823 new_space_.Shrink();
3824 last_gc_count = gc_count_;
3825
3826 } else if (number_idle_notifications == kIdlesBeforeMarkCompact) {
3827 CollectAllGarbage(true);
3828 new_space_.Shrink();
3829 last_gc_count = gc_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +00003830 finished = true;
Steve Block6ded16b2010-05-10 14:33:55 +01003831
3832 } else if (contexts_disposed_ > 0) {
3833 if (FLAG_expose_gc) {
3834 contexts_disposed_ = 0;
3835 } else {
3836 HistogramTimerScope scope(&Counters::gc_context);
3837 CollectAllGarbage(false);
3838 last_gc_count = gc_count_;
3839 }
3840 // If this is the first idle notification, we reset the
3841 // notification count to avoid letting idle notifications for
3842 // context disposal garbage collections start a potentially too
3843 // aggressive idle GC cycle.
3844 if (number_idle_notifications <= 1) {
3845 number_idle_notifications = 0;
3846 uncommit = false;
3847 }
Ben Murdochdb5a90a2011-01-06 18:27:03 +00003848 } else if (number_idle_notifications > kIdlesBeforeMarkCompact) {
3849 // If we have received more than kIdlesBeforeMarkCompact idle
3850 // notifications we do not perform any cleanup because we don't
3851 // expect to gain much by doing so.
3852 finished = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00003853 }
3854
Steve Block6ded16b2010-05-10 14:33:55 +01003855 // Make sure that we have no pending context disposals and
3856 // conditionally uncommit from space.
3857 ASSERT(contexts_disposed_ == 0);
3858 if (uncommit) Heap::UncommitFromSpace();
Steve Blocka7e24c12009-10-30 11:49:00 +00003859 return finished;
3860}
3861
3862
3863#ifdef DEBUG
3864
3865void Heap::Print() {
3866 if (!HasBeenSetup()) return;
3867 Top::PrintStack();
3868 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00003869 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
3870 space->Print();
Steve Blocka7e24c12009-10-30 11:49:00 +00003871}
3872
3873
3874void Heap::ReportCodeStatistics(const char* title) {
3875 PrintF(">>>>>> Code Stats (%s) >>>>>>\n", title);
3876 PagedSpace::ResetCodeStatistics();
3877 // We do not look for code in new space, map space, or old space. If code
3878 // somehow ends up in those spaces, we would miss it here.
3879 code_space_->CollectCodeStatistics();
3880 lo_space_->CollectCodeStatistics();
3881 PagedSpace::ReportCodeStatistics();
3882}
3883
3884
3885// This function expects that NewSpace's allocated objects histogram is
3886// populated (via a call to CollectStatistics or else as a side effect of a
3887// just-completed scavenge collection).
3888void Heap::ReportHeapStatistics(const char* title) {
3889 USE(title);
3890 PrintF(">>>>>> =============== %s (%d) =============== >>>>>>\n",
3891 title, gc_count_);
3892 PrintF("mark-compact GC : %d\n", mc_count_);
Ben Murdochf87a2032010-10-22 12:50:53 +01003893 PrintF("old_gen_promotion_limit_ %" V8_PTR_PREFIX "d\n",
3894 old_gen_promotion_limit_);
3895 PrintF("old_gen_allocation_limit_ %" V8_PTR_PREFIX "d\n",
3896 old_gen_allocation_limit_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003897
3898 PrintF("\n");
3899 PrintF("Number of handles : %d\n", HandleScope::NumberOfHandles());
3900 GlobalHandles::PrintStats();
3901 PrintF("\n");
3902
3903 PrintF("Heap statistics : ");
3904 MemoryAllocator::ReportStatistics();
3905 PrintF("To space : ");
3906 new_space_.ReportStatistics();
3907 PrintF("Old pointer space : ");
3908 old_pointer_space_->ReportStatistics();
3909 PrintF("Old data space : ");
3910 old_data_space_->ReportStatistics();
3911 PrintF("Code space : ");
3912 code_space_->ReportStatistics();
3913 PrintF("Map space : ");
3914 map_space_->ReportStatistics();
3915 PrintF("Cell space : ");
3916 cell_space_->ReportStatistics();
3917 PrintF("Large object space : ");
3918 lo_space_->ReportStatistics();
3919 PrintF(">>>>>> ========================================= >>>>>>\n");
3920}
3921
3922#endif // DEBUG
3923
3924bool Heap::Contains(HeapObject* value) {
3925 return Contains(value->address());
3926}
3927
3928
3929bool Heap::Contains(Address addr) {
3930 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3931 return HasBeenSetup() &&
3932 (new_space_.ToSpaceContains(addr) ||
3933 old_pointer_space_->Contains(addr) ||
3934 old_data_space_->Contains(addr) ||
3935 code_space_->Contains(addr) ||
3936 map_space_->Contains(addr) ||
3937 cell_space_->Contains(addr) ||
3938 lo_space_->SlowContains(addr));
3939}
3940
3941
3942bool Heap::InSpace(HeapObject* value, AllocationSpace space) {
3943 return InSpace(value->address(), space);
3944}
3945
3946
3947bool Heap::InSpace(Address addr, AllocationSpace space) {
3948 if (OS::IsOutsideAllocatedSpace(addr)) return false;
3949 if (!HasBeenSetup()) return false;
3950
3951 switch (space) {
3952 case NEW_SPACE:
3953 return new_space_.ToSpaceContains(addr);
3954 case OLD_POINTER_SPACE:
3955 return old_pointer_space_->Contains(addr);
3956 case OLD_DATA_SPACE:
3957 return old_data_space_->Contains(addr);
3958 case CODE_SPACE:
3959 return code_space_->Contains(addr);
3960 case MAP_SPACE:
3961 return map_space_->Contains(addr);
3962 case CELL_SPACE:
3963 return cell_space_->Contains(addr);
3964 case LO_SPACE:
3965 return lo_space_->SlowContains(addr);
3966 }
3967
3968 return false;
3969}
3970
3971
3972#ifdef DEBUG
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003973static void DummyScavengePointer(HeapObject** p) {
3974}
3975
3976
3977static void VerifyPointersUnderWatermark(
3978 PagedSpace* space,
3979 DirtyRegionCallback visit_dirty_region) {
3980 PageIterator it(space, PageIterator::PAGES_IN_USE);
3981
3982 while (it.has_next()) {
3983 Page* page = it.next();
3984 Address start = page->ObjectAreaStart();
3985 Address end = page->AllocationWatermark();
3986
3987 Heap::IterateDirtyRegions(Page::kAllRegionsDirtyMarks,
3988 start,
3989 end,
3990 visit_dirty_region,
3991 &DummyScavengePointer);
3992 }
3993}
3994
3995
3996static void VerifyPointersUnderWatermark(LargeObjectSpace* space) {
3997 LargeObjectIterator it(space);
3998 for (HeapObject* object = it.next(); object != NULL; object = it.next()) {
3999 if (object->IsFixedArray()) {
4000 Address slot_address = object->address();
4001 Address end = object->address() + object->Size();
4002
4003 while (slot_address < end) {
4004 HeapObject** slot = reinterpret_cast<HeapObject**>(slot_address);
4005 // When we are not in GC the Heap::InNewSpace() predicate
4006 // checks that pointers which satisfy predicate point into
4007 // the active semispace.
4008 Heap::InNewSpace(*slot);
4009 slot_address += kPointerSize;
4010 }
4011 }
4012 }
4013}
4014
4015
Steve Blocka7e24c12009-10-30 11:49:00 +00004016void Heap::Verify() {
4017 ASSERT(HasBeenSetup());
4018
4019 VerifyPointersVisitor visitor;
Steve Blockd0582a62009-12-15 09:54:21 +00004020 IterateRoots(&visitor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00004021
4022 new_space_.Verify();
4023
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004024 VerifyPointersAndDirtyRegionsVisitor dirty_regions_visitor;
4025 old_pointer_space_->Verify(&dirty_regions_visitor);
4026 map_space_->Verify(&dirty_regions_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00004027
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004028 VerifyPointersUnderWatermark(old_pointer_space_,
4029 &IteratePointersInDirtyRegion);
4030 VerifyPointersUnderWatermark(map_space_,
4031 &IteratePointersInDirtyMapsRegion);
4032 VerifyPointersUnderWatermark(lo_space_);
4033
4034 VerifyPageWatermarkValidity(old_pointer_space_, ALL_INVALID);
4035 VerifyPageWatermarkValidity(map_space_, ALL_INVALID);
4036
4037 VerifyPointersVisitor no_dirty_regions_visitor;
4038 old_data_space_->Verify(&no_dirty_regions_visitor);
4039 code_space_->Verify(&no_dirty_regions_visitor);
4040 cell_space_->Verify(&no_dirty_regions_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00004041
4042 lo_space_->Verify();
4043}
4044#endif // DEBUG
4045
4046
John Reck59135872010-11-02 12:39:01 -07004047MaybeObject* Heap::LookupSymbol(Vector<const char> string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004048 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004049 Object* new_table;
4050 { MaybeObject* maybe_new_table =
4051 symbol_table()->LookupSymbol(string, &symbol);
4052 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4053 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004054 // Can't use set_symbol_table because SymbolTable::cast knows that
4055 // SymbolTable is a singleton and checks for identity.
4056 roots_[kSymbolTableRootIndex] = new_table;
4057 ASSERT(symbol != NULL);
4058 return symbol;
4059}
4060
4061
Steve Block9fac8402011-05-12 15:51:54 +01004062MaybeObject* Heap::LookupAsciiSymbol(Vector<const char> string) {
4063 Object* symbol = NULL;
4064 Object* new_table;
4065 { MaybeObject* maybe_new_table =
4066 symbol_table()->LookupAsciiSymbol(string, &symbol);
4067 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4068 }
4069 // Can't use set_symbol_table because SymbolTable::cast knows that
4070 // SymbolTable is a singleton and checks for identity.
4071 roots_[kSymbolTableRootIndex] = new_table;
4072 ASSERT(symbol != NULL);
4073 return symbol;
4074}
4075
4076
4077MaybeObject* Heap::LookupTwoByteSymbol(Vector<const uc16> string) {
4078 Object* symbol = NULL;
4079 Object* new_table;
4080 { MaybeObject* maybe_new_table =
4081 symbol_table()->LookupTwoByteSymbol(string, &symbol);
4082 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4083 }
4084 // Can't use set_symbol_table because SymbolTable::cast knows that
4085 // SymbolTable is a singleton and checks for identity.
4086 roots_[kSymbolTableRootIndex] = new_table;
4087 ASSERT(symbol != NULL);
4088 return symbol;
4089}
4090
4091
John Reck59135872010-11-02 12:39:01 -07004092MaybeObject* Heap::LookupSymbol(String* string) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004093 if (string->IsSymbol()) return string;
4094 Object* symbol = NULL;
John Reck59135872010-11-02 12:39:01 -07004095 Object* new_table;
4096 { MaybeObject* maybe_new_table =
4097 symbol_table()->LookupString(string, &symbol);
4098 if (!maybe_new_table->ToObject(&new_table)) return maybe_new_table;
4099 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004100 // Can't use set_symbol_table because SymbolTable::cast knows that
4101 // SymbolTable is a singleton and checks for identity.
4102 roots_[kSymbolTableRootIndex] = new_table;
4103 ASSERT(symbol != NULL);
4104 return symbol;
4105}
4106
4107
4108bool Heap::LookupSymbolIfExists(String* string, String** symbol) {
4109 if (string->IsSymbol()) {
4110 *symbol = string;
4111 return true;
4112 }
4113 return symbol_table()->LookupSymbolIfExists(string, symbol);
4114}
4115
4116
4117#ifdef DEBUG
4118void Heap::ZapFromSpace() {
Steve Block1e0659c2011-05-24 12:43:12 +01004119 ASSERT(reinterpret_cast<Object*>(kFromSpaceZapValue)->IsFailure());
Steve Blocka7e24c12009-10-30 11:49:00 +00004120 for (Address a = new_space_.FromSpaceLow();
4121 a < new_space_.FromSpaceHigh();
4122 a += kPointerSize) {
4123 Memory::Address_at(a) = kFromSpaceZapValue;
4124 }
4125}
4126#endif // DEBUG
4127
4128
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004129bool Heap::IteratePointersInDirtyRegion(Address start,
4130 Address end,
4131 ObjectSlotCallback copy_object_func) {
4132 Address slot_address = start;
4133 bool pointers_to_new_space_found = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00004134
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004135 while (slot_address < end) {
4136 Object** slot = reinterpret_cast<Object**>(slot_address);
4137 if (Heap::InNewSpace(*slot)) {
4138 ASSERT((*slot)->IsHeapObject());
4139 copy_object_func(reinterpret_cast<HeapObject**>(slot));
4140 if (Heap::InNewSpace(*slot)) {
4141 ASSERT((*slot)->IsHeapObject());
4142 pointers_to_new_space_found = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00004143 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004144 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004145 slot_address += kPointerSize;
Steve Blocka7e24c12009-10-30 11:49:00 +00004146 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004147 return pointers_to_new_space_found;
Steve Blocka7e24c12009-10-30 11:49:00 +00004148}
4149
4150
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004151// Compute start address of the first map following given addr.
4152static inline Address MapStartAlign(Address addr) {
4153 Address page = Page::FromAddress(addr)->ObjectAreaStart();
4154 return page + (((addr - page) + (Map::kSize - 1)) / Map::kSize * Map::kSize);
4155}
Steve Blocka7e24c12009-10-30 11:49:00 +00004156
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004157
4158// Compute end address of the first map preceding given addr.
4159static inline Address MapEndAlign(Address addr) {
4160 Address page = Page::FromAllocationTop(addr)->ObjectAreaStart();
4161 return page + ((addr - page) / Map::kSize * Map::kSize);
4162}
4163
4164
4165static bool IteratePointersInDirtyMaps(Address start,
4166 Address end,
4167 ObjectSlotCallback copy_object_func) {
4168 ASSERT(MapStartAlign(start) == start);
4169 ASSERT(MapEndAlign(end) == end);
4170
4171 Address map_address = start;
4172 bool pointers_to_new_space_found = false;
4173
4174 while (map_address < end) {
4175 ASSERT(!Heap::InNewSpace(Memory::Object_at(map_address)));
4176 ASSERT(Memory::Object_at(map_address)->IsMap());
4177
4178 Address pointer_fields_start = map_address + Map::kPointerFieldsBeginOffset;
4179 Address pointer_fields_end = map_address + Map::kPointerFieldsEndOffset;
4180
4181 if (Heap::IteratePointersInDirtyRegion(pointer_fields_start,
4182 pointer_fields_end,
4183 copy_object_func)) {
4184 pointers_to_new_space_found = true;
4185 }
4186
4187 map_address += Map::kSize;
4188 }
4189
4190 return pointers_to_new_space_found;
4191}
4192
4193
4194bool Heap::IteratePointersInDirtyMapsRegion(
4195 Address start,
4196 Address end,
4197 ObjectSlotCallback copy_object_func) {
4198 Address map_aligned_start = MapStartAlign(start);
4199 Address map_aligned_end = MapEndAlign(end);
4200
4201 bool contains_pointers_to_new_space = false;
4202
4203 if (map_aligned_start != start) {
4204 Address prev_map = map_aligned_start - Map::kSize;
4205 ASSERT(Memory::Object_at(prev_map)->IsMap());
4206
4207 Address pointer_fields_start =
4208 Max(start, prev_map + Map::kPointerFieldsBeginOffset);
4209
4210 Address pointer_fields_end =
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004211 Min(prev_map + Map::kPointerFieldsEndOffset, end);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004212
4213 contains_pointers_to_new_space =
4214 IteratePointersInDirtyRegion(pointer_fields_start,
4215 pointer_fields_end,
4216 copy_object_func)
4217 || contains_pointers_to_new_space;
4218 }
4219
4220 contains_pointers_to_new_space =
4221 IteratePointersInDirtyMaps(map_aligned_start,
4222 map_aligned_end,
4223 copy_object_func)
4224 || contains_pointers_to_new_space;
4225
4226 if (map_aligned_end != end) {
4227 ASSERT(Memory::Object_at(map_aligned_end)->IsMap());
4228
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004229 Address pointer_fields_start =
4230 map_aligned_end + Map::kPointerFieldsBeginOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004231
4232 Address pointer_fields_end =
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004233 Min(end, map_aligned_end + Map::kPointerFieldsEndOffset);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004234
4235 contains_pointers_to_new_space =
4236 IteratePointersInDirtyRegion(pointer_fields_start,
4237 pointer_fields_end,
4238 copy_object_func)
4239 || contains_pointers_to_new_space;
4240 }
4241
4242 return contains_pointers_to_new_space;
4243}
4244
4245
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004246void Heap::IterateAndMarkPointersToFromSpace(Address start,
4247 Address end,
4248 ObjectSlotCallback callback) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004249 Address slot_address = start;
4250 Page* page = Page::FromAddress(start);
4251
4252 uint32_t marks = page->GetRegionMarks();
4253
4254 while (slot_address < end) {
4255 Object** slot = reinterpret_cast<Object**>(slot_address);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01004256 if (Heap::InFromSpace(*slot)) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004257 ASSERT((*slot)->IsHeapObject());
4258 callback(reinterpret_cast<HeapObject**>(slot));
4259 if (Heap::InNewSpace(*slot)) {
4260 ASSERT((*slot)->IsHeapObject());
4261 marks |= page->GetRegionMaskForAddress(slot_address);
4262 }
4263 }
4264 slot_address += kPointerSize;
4265 }
4266
4267 page->SetRegionMarks(marks);
4268}
4269
4270
4271uint32_t Heap::IterateDirtyRegions(
4272 uint32_t marks,
4273 Address area_start,
4274 Address area_end,
4275 DirtyRegionCallback visit_dirty_region,
4276 ObjectSlotCallback copy_object_func) {
4277 uint32_t newmarks = 0;
4278 uint32_t mask = 1;
4279
4280 if (area_start >= area_end) {
4281 return newmarks;
4282 }
4283
4284 Address region_start = area_start;
4285
4286 // area_start does not necessarily coincide with start of the first region.
4287 // Thus to calculate the beginning of the next region we have to align
4288 // area_start by Page::kRegionSize.
4289 Address second_region =
4290 reinterpret_cast<Address>(
4291 reinterpret_cast<intptr_t>(area_start + Page::kRegionSize) &
4292 ~Page::kRegionAlignmentMask);
4293
4294 // Next region might be beyond area_end.
4295 Address region_end = Min(second_region, area_end);
4296
4297 if (marks & mask) {
4298 if (visit_dirty_region(region_start, region_end, copy_object_func)) {
4299 newmarks |= mask;
4300 }
4301 }
4302 mask <<= 1;
4303
4304 // Iterate subsequent regions which fully lay inside [area_start, area_end[.
4305 region_start = region_end;
4306 region_end = region_start + Page::kRegionSize;
4307
4308 while (region_end <= area_end) {
4309 if (marks & mask) {
4310 if (visit_dirty_region(region_start, region_end, copy_object_func)) {
4311 newmarks |= mask;
4312 }
4313 }
4314
4315 region_start = region_end;
4316 region_end = region_start + Page::kRegionSize;
4317
4318 mask <<= 1;
4319 }
4320
4321 if (region_start != area_end) {
4322 // A small piece of area left uniterated because area_end does not coincide
4323 // with region end. Check whether region covering last part of area is
4324 // dirty.
4325 if (marks & mask) {
4326 if (visit_dirty_region(region_start, area_end, copy_object_func)) {
4327 newmarks |= mask;
4328 }
4329 }
4330 }
4331
4332 return newmarks;
4333}
4334
4335
4336
4337void Heap::IterateDirtyRegions(
4338 PagedSpace* space,
4339 DirtyRegionCallback visit_dirty_region,
4340 ObjectSlotCallback copy_object_func,
4341 ExpectedPageWatermarkState expected_page_watermark_state) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004342
4343 PageIterator it(space, PageIterator::PAGES_IN_USE);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004344
Steve Blocka7e24c12009-10-30 11:49:00 +00004345 while (it.has_next()) {
4346 Page* page = it.next();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004347 uint32_t marks = page->GetRegionMarks();
4348
4349 if (marks != Page::kAllRegionsCleanMarks) {
4350 Address start = page->ObjectAreaStart();
4351
4352 // Do not try to visit pointers beyond page allocation watermark.
4353 // Page can contain garbage pointers there.
4354 Address end;
4355
4356 if ((expected_page_watermark_state == WATERMARK_SHOULD_BE_VALID) ||
4357 page->IsWatermarkValid()) {
4358 end = page->AllocationWatermark();
4359 } else {
4360 end = page->CachedAllocationWatermark();
4361 }
4362
4363 ASSERT(space == old_pointer_space_ ||
4364 (space == map_space_ &&
4365 ((page->ObjectAreaStart() - end) % Map::kSize == 0)));
4366
4367 page->SetRegionMarks(IterateDirtyRegions(marks,
4368 start,
4369 end,
4370 visit_dirty_region,
4371 copy_object_func));
Steve Blocka7e24c12009-10-30 11:49:00 +00004372 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004373
4374 // Mark page watermark as invalid to maintain watermark validity invariant.
4375 // See Page::FlipMeaningOfInvalidatedWatermarkFlag() for details.
4376 page->InvalidateWatermark(true);
Steve Blocka7e24c12009-10-30 11:49:00 +00004377 }
4378}
4379
4380
Steve Blockd0582a62009-12-15 09:54:21 +00004381void Heap::IterateRoots(ObjectVisitor* v, VisitMode mode) {
4382 IterateStrongRoots(v, mode);
Leon Clarked91b9f72010-01-27 17:25:45 +00004383 IterateWeakRoots(v, mode);
4384}
4385
4386
4387void Heap::IterateWeakRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004388 v->VisitPointer(reinterpret_cast<Object**>(&roots_[kSymbolTableRootIndex]));
Steve Blockd0582a62009-12-15 09:54:21 +00004389 v->Synchronize("symbol_table");
Leon Clarkee46be812010-01-19 14:06:41 +00004390 if (mode != VISIT_ALL_IN_SCAVENGE) {
4391 // Scavenge collections have special processing for this.
4392 ExternalStringTable::Iterate(v);
4393 }
4394 v->Synchronize("external_string_table");
Steve Blocka7e24c12009-10-30 11:49:00 +00004395}
4396
4397
Steve Blockd0582a62009-12-15 09:54:21 +00004398void Heap::IterateStrongRoots(ObjectVisitor* v, VisitMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004399 v->VisitPointers(&roots_[0], &roots_[kStrongRootListLength]);
Steve Blockd0582a62009-12-15 09:54:21 +00004400 v->Synchronize("strong_root_list");
Steve Blocka7e24c12009-10-30 11:49:00 +00004401
Iain Merrick75681382010-08-19 15:07:18 +01004402 v->VisitPointer(BitCast<Object**>(&hidden_symbol_));
Steve Blockd0582a62009-12-15 09:54:21 +00004403 v->Synchronize("symbol");
Steve Blocka7e24c12009-10-30 11:49:00 +00004404
4405 Bootstrapper::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004406 v->Synchronize("bootstrapper");
Steve Blocka7e24c12009-10-30 11:49:00 +00004407 Top::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004408 v->Synchronize("top");
Steve Blocka7e24c12009-10-30 11:49:00 +00004409 Relocatable::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004410 v->Synchronize("relocatable");
Steve Blocka7e24c12009-10-30 11:49:00 +00004411
4412#ifdef ENABLE_DEBUGGER_SUPPORT
4413 Debug::Iterate(v);
4414#endif
Steve Blockd0582a62009-12-15 09:54:21 +00004415 v->Synchronize("debug");
Steve Blocka7e24c12009-10-30 11:49:00 +00004416 CompilationCache::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004417 v->Synchronize("compilationcache");
Steve Blocka7e24c12009-10-30 11:49:00 +00004418
4419 // Iterate over local handles in handle scopes.
4420 HandleScopeImplementer::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004421 v->Synchronize("handlescope");
Steve Blocka7e24c12009-10-30 11:49:00 +00004422
Leon Clarkee46be812010-01-19 14:06:41 +00004423 // Iterate over the builtin code objects and code stubs in the
4424 // heap. Note that it is not necessary to iterate over code objects
4425 // on scavenge collections.
4426 if (mode != VISIT_ALL_IN_SCAVENGE) {
4427 Builtins::IterateBuiltins(v);
4428 }
Steve Blockd0582a62009-12-15 09:54:21 +00004429 v->Synchronize("builtins");
Steve Blocka7e24c12009-10-30 11:49:00 +00004430
4431 // Iterate over global handles.
Steve Blockd0582a62009-12-15 09:54:21 +00004432 if (mode == VISIT_ONLY_STRONG) {
4433 GlobalHandles::IterateStrongRoots(v);
4434 } else {
4435 GlobalHandles::IterateAllRoots(v);
4436 }
4437 v->Synchronize("globalhandles");
Steve Blocka7e24c12009-10-30 11:49:00 +00004438
4439 // Iterate over pointers being held by inactive threads.
4440 ThreadManager::Iterate(v);
Steve Blockd0582a62009-12-15 09:54:21 +00004441 v->Synchronize("threadmanager");
Leon Clarked91b9f72010-01-27 17:25:45 +00004442
4443 // Iterate over the pointers the Serialization/Deserialization code is
4444 // holding.
4445 // During garbage collection this keeps the partial snapshot cache alive.
4446 // During deserialization of the startup snapshot this creates the partial
4447 // snapshot cache and deserializes the objects it refers to. During
4448 // serialization this does nothing, since the partial snapshot cache is
4449 // empty. However the next thing we do is create the partial snapshot,
4450 // filling up the partial snapshot cache with objects it needs as we go.
4451 SerializerDeserializer::Iterate(v);
4452 // We don't do a v->Synchronize call here, because in debug mode that will
4453 // output a flag to the snapshot. However at this point the serializer and
4454 // deserializer are deliberately a little unsynchronized (see above) so the
4455 // checking of the sync flag in the snapshot would fail.
Steve Blocka7e24c12009-10-30 11:49:00 +00004456}
Steve Blocka7e24c12009-10-30 11:49:00 +00004457
4458
4459// Flag is set when the heap has been configured. The heap can be repeatedly
4460// configured through the API until it is setup.
4461static bool heap_configured = false;
4462
4463// TODO(1236194): Since the heap size is configurable on the command line
4464// and through the API, we should gracefully handle the case that the heap
4465// size is not big enough to fit all the initial objects.
Russell Brenner90bac252010-11-18 13:33:46 -08004466bool Heap::ConfigureHeap(int max_semispace_size,
4467 int max_old_gen_size,
4468 int max_executable_size) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004469 if (HasBeenSetup()) return false;
4470
Steve Block3ce2e202009-11-05 08:53:23 +00004471 if (max_semispace_size > 0) max_semispace_size_ = max_semispace_size;
4472
4473 if (Snapshot::IsEnabled()) {
4474 // If we are using a snapshot we always reserve the default amount
4475 // of memory for each semispace because code in the snapshot has
4476 // write-barrier code that relies on the size and alignment of new
4477 // space. We therefore cannot use a larger max semispace size
4478 // than the default reserved semispace size.
4479 if (max_semispace_size_ > reserved_semispace_size_) {
4480 max_semispace_size_ = reserved_semispace_size_;
4481 }
4482 } else {
4483 // If we are not using snapshots we reserve space for the actual
4484 // max semispace size.
4485 reserved_semispace_size_ = max_semispace_size_;
4486 }
4487
4488 if (max_old_gen_size > 0) max_old_generation_size_ = max_old_gen_size;
Russell Brenner90bac252010-11-18 13:33:46 -08004489 if (max_executable_size > 0) {
4490 max_executable_size_ = RoundUp(max_executable_size, Page::kPageSize);
4491 }
4492
4493 // The max executable size must be less than or equal to the max old
4494 // generation size.
4495 if (max_executable_size_ > max_old_generation_size_) {
4496 max_executable_size_ = max_old_generation_size_;
4497 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004498
4499 // The new space size must be a power of two to support single-bit testing
4500 // for containment.
Steve Block3ce2e202009-11-05 08:53:23 +00004501 max_semispace_size_ = RoundUpToPowerOf2(max_semispace_size_);
4502 reserved_semispace_size_ = RoundUpToPowerOf2(reserved_semispace_size_);
4503 initial_semispace_size_ = Min(initial_semispace_size_, max_semispace_size_);
4504 external_allocation_limit_ = 10 * max_semispace_size_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004505
4506 // The old generation is paged.
Steve Block3ce2e202009-11-05 08:53:23 +00004507 max_old_generation_size_ = RoundUp(max_old_generation_size_, Page::kPageSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00004508
4509 heap_configured = true;
4510 return true;
4511}
4512
4513
4514bool Heap::ConfigureHeapDefault() {
Russell Brenner90bac252010-11-18 13:33:46 -08004515 return ConfigureHeap(FLAG_max_new_space_size / 2 * KB,
4516 FLAG_max_old_space_size * MB,
4517 FLAG_max_executable_size * MB);
Steve Blocka7e24c12009-10-30 11:49:00 +00004518}
4519
4520
Ben Murdochbb769b22010-08-11 14:56:33 +01004521void Heap::RecordStats(HeapStats* stats, bool take_snapshot) {
Iain Merrick75681382010-08-19 15:07:18 +01004522 *stats->start_marker = HeapStats::kStartMarker;
4523 *stats->end_marker = HeapStats::kEndMarker;
Ben Murdochf87a2032010-10-22 12:50:53 +01004524 *stats->new_space_size = new_space_.SizeAsInt();
4525 *stats->new_space_capacity = static_cast<int>(new_space_.Capacity());
Steve Blockd0582a62009-12-15 09:54:21 +00004526 *stats->old_pointer_space_size = old_pointer_space_->Size();
4527 *stats->old_pointer_space_capacity = old_pointer_space_->Capacity();
4528 *stats->old_data_space_size = old_data_space_->Size();
4529 *stats->old_data_space_capacity = old_data_space_->Capacity();
4530 *stats->code_space_size = code_space_->Size();
4531 *stats->code_space_capacity = code_space_->Capacity();
4532 *stats->map_space_size = map_space_->Size();
4533 *stats->map_space_capacity = map_space_->Capacity();
4534 *stats->cell_space_size = cell_space_->Size();
4535 *stats->cell_space_capacity = cell_space_->Capacity();
4536 *stats->lo_space_size = lo_space_->Size();
4537 GlobalHandles::RecordStats(stats);
Ben Murdochbb769b22010-08-11 14:56:33 +01004538 *stats->memory_allocator_size = MemoryAllocator::Size();
4539 *stats->memory_allocator_capacity =
4540 MemoryAllocator::Size() + MemoryAllocator::Available();
Iain Merrick75681382010-08-19 15:07:18 +01004541 *stats->os_error = OS::GetLastError();
Ben Murdochbb769b22010-08-11 14:56:33 +01004542 if (take_snapshot) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01004543 HeapIterator iterator(HeapIterator::kFilterFreeListNodes);
Ben Murdochbb769b22010-08-11 14:56:33 +01004544 for (HeapObject* obj = iterator.next();
4545 obj != NULL;
4546 obj = iterator.next()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01004547 InstanceType type = obj->map()->instance_type();
4548 ASSERT(0 <= type && type <= LAST_TYPE);
4549 stats->objects_per_type[type]++;
4550 stats->size_per_type[type] += obj->Size();
4551 }
4552 }
Steve Blockd0582a62009-12-15 09:54:21 +00004553}
4554
4555
Ben Murdochf87a2032010-10-22 12:50:53 +01004556intptr_t Heap::PromotedSpaceSize() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004557 return old_pointer_space_->Size()
4558 + old_data_space_->Size()
4559 + code_space_->Size()
4560 + map_space_->Size()
4561 + cell_space_->Size()
4562 + lo_space_->Size();
4563}
4564
4565
4566int Heap::PromotedExternalMemorySize() {
4567 if (amount_of_external_allocated_memory_
4568 <= amount_of_external_allocated_memory_at_last_global_gc_) return 0;
4569 return amount_of_external_allocated_memory_
4570 - amount_of_external_allocated_memory_at_last_global_gc_;
4571}
4572
4573
4574bool Heap::Setup(bool create_heap_objects) {
4575 // Initialize heap spaces and initial maps and objects. Whenever something
4576 // goes wrong, just return false. The caller should check the results and
4577 // call Heap::TearDown() to release allocated memory.
4578 //
4579 // If the heap is not yet configured (eg, through the API), configure it.
4580 // Configuration is based on the flags new-space-size (really the semispace
4581 // size) and old-space-size if set or the initial values of semispace_size_
4582 // and old_generation_size_ otherwise.
4583 if (!heap_configured) {
4584 if (!ConfigureHeapDefault()) return false;
4585 }
4586
Iain Merrick75681382010-08-19 15:07:18 +01004587 ScavengingVisitor::Initialize();
4588 NewSpaceScavenger::Initialize();
4589 MarkCompactCollector::Initialize();
4590
Kristian Monsen80d68ea2010-09-08 11:05:35 +01004591 MarkMapPointersAsEncoded(false);
4592
Steve Blocka7e24c12009-10-30 11:49:00 +00004593 // Setup memory allocator and reserve a chunk of memory for new
Steve Block3ce2e202009-11-05 08:53:23 +00004594 // space. The chunk is double the size of the requested reserved
4595 // new space size to ensure that we can find a pair of semispaces that
4596 // are contiguous and aligned to their size.
Russell Brenner90bac252010-11-18 13:33:46 -08004597 if (!MemoryAllocator::Setup(MaxReserved(), MaxExecutableSize())) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00004598 void* chunk =
Steve Block3ce2e202009-11-05 08:53:23 +00004599 MemoryAllocator::ReserveInitialChunk(4 * reserved_semispace_size_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004600 if (chunk == NULL) return false;
4601
4602 // Align the pair of semispaces to their size, which must be a power
4603 // of 2.
Steve Blocka7e24c12009-10-30 11:49:00 +00004604 Address new_space_start =
Steve Block3ce2e202009-11-05 08:53:23 +00004605 RoundUp(reinterpret_cast<byte*>(chunk), 2 * reserved_semispace_size_);
4606 if (!new_space_.Setup(new_space_start, 2 * reserved_semispace_size_)) {
4607 return false;
4608 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004609
4610 // Initialize old pointer space.
4611 old_pointer_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00004612 new OldSpace(max_old_generation_size_, OLD_POINTER_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004613 if (old_pointer_space_ == NULL) return false;
4614 if (!old_pointer_space_->Setup(NULL, 0)) return false;
4615
4616 // Initialize old data space.
4617 old_data_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00004618 new OldSpace(max_old_generation_size_, OLD_DATA_SPACE, NOT_EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004619 if (old_data_space_ == NULL) return false;
4620 if (!old_data_space_->Setup(NULL, 0)) return false;
4621
4622 // Initialize the code space, set its maximum capacity to the old
4623 // generation size. It needs executable memory.
4624 // On 64-bit platform(s), we put all code objects in a 2 GB range of
4625 // virtual address space, so that they can call each other with near calls.
4626 if (code_range_size_ > 0) {
4627 if (!CodeRange::Setup(code_range_size_)) {
4628 return false;
4629 }
4630 }
4631
4632 code_space_ =
Steve Block3ce2e202009-11-05 08:53:23 +00004633 new OldSpace(max_old_generation_size_, CODE_SPACE, EXECUTABLE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004634 if (code_space_ == NULL) return false;
4635 if (!code_space_->Setup(NULL, 0)) return false;
4636
4637 // Initialize map space.
Leon Clarkee46be812010-01-19 14:06:41 +00004638 map_space_ = new MapSpace(FLAG_use_big_map_space
4639 ? max_old_generation_size_
Leon Clarked91b9f72010-01-27 17:25:45 +00004640 : MapSpace::kMaxMapPageIndex * Page::kPageSize,
4641 FLAG_max_map_space_pages,
Leon Clarkee46be812010-01-19 14:06:41 +00004642 MAP_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004643 if (map_space_ == NULL) return false;
4644 if (!map_space_->Setup(NULL, 0)) return false;
4645
4646 // Initialize global property cell space.
Steve Block3ce2e202009-11-05 08:53:23 +00004647 cell_space_ = new CellSpace(max_old_generation_size_, CELL_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00004648 if (cell_space_ == NULL) return false;
4649 if (!cell_space_->Setup(NULL, 0)) return false;
4650
4651 // The large object code space may contain code or data. We set the memory
4652 // to be non-executable here for safety, but this means we need to enable it
4653 // explicitly when allocating large code objects.
4654 lo_space_ = new LargeObjectSpace(LO_SPACE);
4655 if (lo_space_ == NULL) return false;
4656 if (!lo_space_->Setup()) return false;
4657
4658 if (create_heap_objects) {
4659 // Create initial maps.
4660 if (!CreateInitialMaps()) return false;
4661 if (!CreateApiObjects()) return false;
4662
4663 // Create initial objects
4664 if (!CreateInitialObjects()) return false;
Ben Murdochf87a2032010-10-22 12:50:53 +01004665
4666 global_contexts_list_ = undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00004667 }
4668
Ben Murdochf87a2032010-10-22 12:50:53 +01004669 LOG(IntPtrTEvent("heap-capacity", Capacity()));
4670 LOG(IntPtrTEvent("heap-available", Available()));
Steve Blocka7e24c12009-10-30 11:49:00 +00004671
Steve Block3ce2e202009-11-05 08:53:23 +00004672#ifdef ENABLE_LOGGING_AND_PROFILING
4673 // This should be called only after initial objects have been created.
4674 ProducerHeapProfile::Setup();
4675#endif
4676
Steve Blocka7e24c12009-10-30 11:49:00 +00004677 return true;
4678}
4679
4680
Steve Blockd0582a62009-12-15 09:54:21 +00004681void Heap::SetStackLimits() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004682 // On 64 bit machines, pointers are generally out of range of Smis. We write
4683 // something that looks like an out of range Smi to the GC.
4684
Steve Blockd0582a62009-12-15 09:54:21 +00004685 // Set up the special root array entries containing the stack limits.
4686 // These are actually addresses, but the tag makes the GC ignore it.
Steve Blocka7e24c12009-10-30 11:49:00 +00004687 roots_[kStackLimitRootIndex] =
Steve Blockd0582a62009-12-15 09:54:21 +00004688 reinterpret_cast<Object*>(
4689 (StackGuard::jslimit() & ~kSmiTagMask) | kSmiTag);
4690 roots_[kRealStackLimitRootIndex] =
4691 reinterpret_cast<Object*>(
4692 (StackGuard::real_jslimit() & ~kSmiTagMask) | kSmiTag);
Steve Blocka7e24c12009-10-30 11:49:00 +00004693}
4694
4695
4696void Heap::TearDown() {
Leon Clarkef7060e22010-06-03 12:02:55 +01004697 if (FLAG_print_cumulative_gc_stat) {
4698 PrintF("\n\n");
4699 PrintF("gc_count=%d ", gc_count_);
4700 PrintF("mark_sweep_count=%d ", ms_count_);
4701 PrintF("mark_compact_count=%d ", mc_count_);
4702 PrintF("max_gc_pause=%d ", GCTracer::get_max_gc_pause());
4703 PrintF("min_in_mutator=%d ", GCTracer::get_min_in_mutator());
Ben Murdochf87a2032010-10-22 12:50:53 +01004704 PrintF("max_alive_after_gc=%" V8_PTR_PREFIX "d ",
4705 GCTracer::get_max_alive_after_gc());
Leon Clarkef7060e22010-06-03 12:02:55 +01004706 PrintF("\n\n");
4707 }
4708
Steve Blocka7e24c12009-10-30 11:49:00 +00004709 GlobalHandles::TearDown();
4710
Leon Clarkee46be812010-01-19 14:06:41 +00004711 ExternalStringTable::TearDown();
4712
Steve Blocka7e24c12009-10-30 11:49:00 +00004713 new_space_.TearDown();
4714
4715 if (old_pointer_space_ != NULL) {
4716 old_pointer_space_->TearDown();
4717 delete old_pointer_space_;
4718 old_pointer_space_ = NULL;
4719 }
4720
4721 if (old_data_space_ != NULL) {
4722 old_data_space_->TearDown();
4723 delete old_data_space_;
4724 old_data_space_ = NULL;
4725 }
4726
4727 if (code_space_ != NULL) {
4728 code_space_->TearDown();
4729 delete code_space_;
4730 code_space_ = NULL;
4731 }
4732
4733 if (map_space_ != NULL) {
4734 map_space_->TearDown();
4735 delete map_space_;
4736 map_space_ = NULL;
4737 }
4738
4739 if (cell_space_ != NULL) {
4740 cell_space_->TearDown();
4741 delete cell_space_;
4742 cell_space_ = NULL;
4743 }
4744
4745 if (lo_space_ != NULL) {
4746 lo_space_->TearDown();
4747 delete lo_space_;
4748 lo_space_ = NULL;
4749 }
4750
4751 MemoryAllocator::TearDown();
4752}
4753
4754
4755void Heap::Shrink() {
4756 // Try to shrink all paged spaces.
4757 PagedSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004758 for (PagedSpace* space = spaces.next(); space != NULL; space = spaces.next())
4759 space->Shrink();
Steve Blocka7e24c12009-10-30 11:49:00 +00004760}
4761
4762
4763#ifdef ENABLE_HEAP_PROTECTION
4764
4765void Heap::Protect() {
4766 if (HasBeenSetup()) {
4767 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004768 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4769 space->Protect();
Steve Blocka7e24c12009-10-30 11:49:00 +00004770 }
4771}
4772
4773
4774void Heap::Unprotect() {
4775 if (HasBeenSetup()) {
4776 AllSpaces spaces;
Leon Clarked91b9f72010-01-27 17:25:45 +00004777 for (Space* space = spaces.next(); space != NULL; space = spaces.next())
4778 space->Unprotect();
Steve Blocka7e24c12009-10-30 11:49:00 +00004779 }
4780}
4781
4782#endif
4783
4784
Steve Block6ded16b2010-05-10 14:33:55 +01004785void Heap::AddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type) {
4786 ASSERT(callback != NULL);
4787 GCPrologueCallbackPair pair(callback, gc_type);
4788 ASSERT(!gc_prologue_callbacks_.Contains(pair));
4789 return gc_prologue_callbacks_.Add(pair);
4790}
4791
4792
4793void Heap::RemoveGCPrologueCallback(GCPrologueCallback callback) {
4794 ASSERT(callback != NULL);
4795 for (int i = 0; i < gc_prologue_callbacks_.length(); ++i) {
4796 if (gc_prologue_callbacks_[i].callback == callback) {
4797 gc_prologue_callbacks_.Remove(i);
4798 return;
4799 }
4800 }
4801 UNREACHABLE();
4802}
4803
4804
4805void Heap::AddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type) {
4806 ASSERT(callback != NULL);
4807 GCEpilogueCallbackPair pair(callback, gc_type);
4808 ASSERT(!gc_epilogue_callbacks_.Contains(pair));
4809 return gc_epilogue_callbacks_.Add(pair);
4810}
4811
4812
4813void Heap::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
4814 ASSERT(callback != NULL);
4815 for (int i = 0; i < gc_epilogue_callbacks_.length(); ++i) {
4816 if (gc_epilogue_callbacks_[i].callback == callback) {
4817 gc_epilogue_callbacks_.Remove(i);
4818 return;
4819 }
4820 }
4821 UNREACHABLE();
4822}
4823
4824
Steve Blocka7e24c12009-10-30 11:49:00 +00004825#ifdef DEBUG
4826
4827class PrintHandleVisitor: public ObjectVisitor {
4828 public:
4829 void VisitPointers(Object** start, Object** end) {
4830 for (Object** p = start; p < end; p++)
Ben Murdochf87a2032010-10-22 12:50:53 +01004831 PrintF(" handle %p to %p\n",
4832 reinterpret_cast<void*>(p),
4833 reinterpret_cast<void*>(*p));
Steve Blocka7e24c12009-10-30 11:49:00 +00004834 }
4835};
4836
4837void Heap::PrintHandles() {
4838 PrintF("Handles:\n");
4839 PrintHandleVisitor v;
4840 HandleScopeImplementer::Iterate(&v);
4841}
4842
4843#endif
4844
4845
4846Space* AllSpaces::next() {
4847 switch (counter_++) {
4848 case NEW_SPACE:
4849 return Heap::new_space();
4850 case OLD_POINTER_SPACE:
4851 return Heap::old_pointer_space();
4852 case OLD_DATA_SPACE:
4853 return Heap::old_data_space();
4854 case CODE_SPACE:
4855 return Heap::code_space();
4856 case MAP_SPACE:
4857 return Heap::map_space();
4858 case CELL_SPACE:
4859 return Heap::cell_space();
4860 case LO_SPACE:
4861 return Heap::lo_space();
4862 default:
4863 return NULL;
4864 }
4865}
4866
4867
4868PagedSpace* PagedSpaces::next() {
4869 switch (counter_++) {
4870 case OLD_POINTER_SPACE:
4871 return Heap::old_pointer_space();
4872 case OLD_DATA_SPACE:
4873 return Heap::old_data_space();
4874 case CODE_SPACE:
4875 return Heap::code_space();
4876 case MAP_SPACE:
4877 return Heap::map_space();
4878 case CELL_SPACE:
4879 return Heap::cell_space();
4880 default:
4881 return NULL;
4882 }
4883}
4884
4885
4886
4887OldSpace* OldSpaces::next() {
4888 switch (counter_++) {
4889 case OLD_POINTER_SPACE:
4890 return Heap::old_pointer_space();
4891 case OLD_DATA_SPACE:
4892 return Heap::old_data_space();
4893 case CODE_SPACE:
4894 return Heap::code_space();
4895 default:
4896 return NULL;
4897 }
4898}
4899
4900
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004901SpaceIterator::SpaceIterator()
4902 : current_space_(FIRST_SPACE),
4903 iterator_(NULL),
4904 size_func_(NULL) {
4905}
4906
4907
4908SpaceIterator::SpaceIterator(HeapObjectCallback size_func)
4909 : current_space_(FIRST_SPACE),
4910 iterator_(NULL),
4911 size_func_(size_func) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004912}
4913
4914
4915SpaceIterator::~SpaceIterator() {
4916 // Delete active iterator if any.
4917 delete iterator_;
4918}
4919
4920
4921bool SpaceIterator::has_next() {
4922 // Iterate until no more spaces.
4923 return current_space_ != LAST_SPACE;
4924}
4925
4926
4927ObjectIterator* SpaceIterator::next() {
4928 if (iterator_ != NULL) {
4929 delete iterator_;
4930 iterator_ = NULL;
4931 // Move to the next space
4932 current_space_++;
4933 if (current_space_ > LAST_SPACE) {
4934 return NULL;
4935 }
4936 }
4937
4938 // Return iterator for the new current space.
4939 return CreateIterator();
4940}
4941
4942
4943// Create an iterator for the space to iterate.
4944ObjectIterator* SpaceIterator::CreateIterator() {
4945 ASSERT(iterator_ == NULL);
4946
4947 switch (current_space_) {
4948 case NEW_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004949 iterator_ = new SemiSpaceIterator(Heap::new_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004950 break;
4951 case OLD_POINTER_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004952 iterator_ = new HeapObjectIterator(Heap::old_pointer_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004953 break;
4954 case OLD_DATA_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004955 iterator_ = new HeapObjectIterator(Heap::old_data_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004956 break;
4957 case CODE_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004958 iterator_ = new HeapObjectIterator(Heap::code_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004959 break;
4960 case MAP_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004961 iterator_ = new HeapObjectIterator(Heap::map_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004962 break;
4963 case CELL_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004964 iterator_ = new HeapObjectIterator(Heap::cell_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004965 break;
4966 case LO_SPACE:
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004967 iterator_ = new LargeObjectIterator(Heap::lo_space(), size_func_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004968 break;
4969 }
4970
4971 // Return the newly allocated iterator;
4972 ASSERT(iterator_ != NULL);
4973 return iterator_;
4974}
4975
4976
Ben Murdochb0fe1622011-05-05 13:52:32 +01004977class HeapObjectsFilter {
4978 public:
4979 virtual ~HeapObjectsFilter() {}
4980 virtual bool SkipObject(HeapObject* object) = 0;
4981};
4982
4983
4984class FreeListNodesFilter : public HeapObjectsFilter {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004985 public:
4986 FreeListNodesFilter() {
4987 MarkFreeListNodes();
4988 }
4989
Ben Murdochb0fe1622011-05-05 13:52:32 +01004990 bool SkipObject(HeapObject* object) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08004991 if (object->IsMarked()) {
4992 object->ClearMark();
4993 return true;
4994 } else {
4995 return false;
4996 }
4997 }
4998
4999 private:
5000 void MarkFreeListNodes() {
5001 Heap::old_pointer_space()->MarkFreeListNodes();
5002 Heap::old_data_space()->MarkFreeListNodes();
5003 MarkCodeSpaceFreeListNodes();
5004 Heap::map_space()->MarkFreeListNodes();
5005 Heap::cell_space()->MarkFreeListNodes();
5006 }
5007
5008 void MarkCodeSpaceFreeListNodes() {
5009 // For code space, using FreeListNode::IsFreeListNode is OK.
5010 HeapObjectIterator iter(Heap::code_space());
5011 for (HeapObject* obj = iter.next_object();
5012 obj != NULL;
5013 obj = iter.next_object()) {
5014 if (FreeListNode::IsFreeListNode(obj)) obj->SetMark();
5015 }
5016 }
5017
5018 AssertNoAllocation no_alloc;
5019};
5020
5021
Ben Murdochb0fe1622011-05-05 13:52:32 +01005022class UnreachableObjectsFilter : public HeapObjectsFilter {
5023 public:
5024 UnreachableObjectsFilter() {
5025 MarkUnreachableObjects();
5026 }
5027
5028 bool SkipObject(HeapObject* object) {
5029 if (object->IsMarked()) {
5030 object->ClearMark();
5031 return true;
5032 } else {
5033 return false;
5034 }
5035 }
5036
5037 private:
5038 class UnmarkingVisitor : public ObjectVisitor {
5039 public:
5040 UnmarkingVisitor() : list_(10) {}
5041
5042 void VisitPointers(Object** start, Object** end) {
5043 for (Object** p = start; p < end; p++) {
5044 if (!(*p)->IsHeapObject()) continue;
5045 HeapObject* obj = HeapObject::cast(*p);
5046 if (obj->IsMarked()) {
5047 obj->ClearMark();
5048 list_.Add(obj);
5049 }
5050 }
5051 }
5052
5053 bool can_process() { return !list_.is_empty(); }
5054
5055 void ProcessNext() {
5056 HeapObject* obj = list_.RemoveLast();
5057 obj->Iterate(this);
5058 }
5059
5060 private:
5061 List<HeapObject*> list_;
5062 };
5063
5064 void MarkUnreachableObjects() {
5065 HeapIterator iterator;
5066 for (HeapObject* obj = iterator.next();
5067 obj != NULL;
5068 obj = iterator.next()) {
5069 obj->SetMark();
5070 }
5071 UnmarkingVisitor visitor;
Ben Murdochb8e0da22011-05-16 14:20:40 +01005072 Heap::IterateRoots(&visitor, VISIT_ALL);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005073 while (visitor.can_process())
5074 visitor.ProcessNext();
5075 }
5076
5077 AssertNoAllocation no_alloc;
5078};
5079
5080
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005081HeapIterator::HeapIterator()
5082 : filtering_(HeapIterator::kNoFiltering),
5083 filter_(NULL) {
5084 Init();
5085}
5086
5087
Ben Murdochb0fe1622011-05-05 13:52:32 +01005088HeapIterator::HeapIterator(HeapIterator::HeapObjectsFiltering filtering)
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005089 : filtering_(filtering),
5090 filter_(NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005091 Init();
5092}
5093
5094
5095HeapIterator::~HeapIterator() {
5096 Shutdown();
5097}
5098
5099
5100void HeapIterator::Init() {
5101 // Start the iteration.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005102 space_iterator_ = filtering_ == kNoFiltering ? new SpaceIterator :
5103 new SpaceIterator(MarkCompactCollector::SizeOfMarkedObject);
5104 switch (filtering_) {
5105 case kFilterFreeListNodes:
5106 filter_ = new FreeListNodesFilter;
5107 break;
5108 case kFilterUnreachable:
5109 filter_ = new UnreachableObjectsFilter;
5110 break;
5111 default:
5112 break;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005113 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005114 object_iterator_ = space_iterator_->next();
5115}
5116
5117
5118void HeapIterator::Shutdown() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005119#ifdef DEBUG
Ben Murdochb0fe1622011-05-05 13:52:32 +01005120 // Assert that in filtering mode we have iterated through all
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005121 // objects. Otherwise, heap will be left in an inconsistent state.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005122 if (filtering_ != kNoFiltering) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005123 ASSERT(object_iterator_ == NULL);
5124 }
5125#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005126 // Make sure the last iterator is deallocated.
5127 delete space_iterator_;
5128 space_iterator_ = NULL;
5129 object_iterator_ = NULL;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005130 delete filter_;
5131 filter_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00005132}
5133
5134
Leon Clarked91b9f72010-01-27 17:25:45 +00005135HeapObject* HeapIterator::next() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005136 if (filter_ == NULL) return NextObject();
5137
5138 HeapObject* obj = NextObject();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005139 while (obj != NULL && filter_->SkipObject(obj)) obj = NextObject();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005140 return obj;
5141}
5142
5143
5144HeapObject* HeapIterator::NextObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005145 // No iterator means we are done.
Leon Clarked91b9f72010-01-27 17:25:45 +00005146 if (object_iterator_ == NULL) return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00005147
Leon Clarked91b9f72010-01-27 17:25:45 +00005148 if (HeapObject* obj = object_iterator_->next_object()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005149 // If the current iterator has more objects we are fine.
Leon Clarked91b9f72010-01-27 17:25:45 +00005150 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005151 } else {
5152 // Go though the spaces looking for one that has objects.
5153 while (space_iterator_->has_next()) {
5154 object_iterator_ = space_iterator_->next();
Leon Clarked91b9f72010-01-27 17:25:45 +00005155 if (HeapObject* obj = object_iterator_->next_object()) {
5156 return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005157 }
5158 }
5159 }
5160 // Done with the last space.
5161 object_iterator_ = NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00005162 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00005163}
5164
5165
5166void HeapIterator::reset() {
5167 // Restart the iterator.
5168 Shutdown();
5169 Init();
5170}
5171
5172
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005173#if defined(DEBUG) || defined(LIVE_OBJECT_LIST)
Steve Blocka7e24c12009-10-30 11:49:00 +00005174
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005175Object* const PathTracer::kAnyGlobalObject = reinterpret_cast<Object*>(NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +00005176
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005177class PathTracer::MarkVisitor: public ObjectVisitor {
Steve Blocka7e24c12009-10-30 11:49:00 +00005178 public:
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005179 explicit MarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00005180 void VisitPointers(Object** start, Object** end) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005181 // Scan all HeapObject pointers in [start, end)
5182 for (Object** p = start; !tracer_->found() && (p < end); p++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005183 if ((*p)->IsHeapObject())
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005184 tracer_->MarkRecursively(p, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00005185 }
5186 }
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005187
5188 private:
5189 PathTracer* tracer_;
Steve Blocka7e24c12009-10-30 11:49:00 +00005190};
5191
Steve Blocka7e24c12009-10-30 11:49:00 +00005192
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005193class PathTracer::UnmarkVisitor: public ObjectVisitor {
5194 public:
5195 explicit UnmarkVisitor(PathTracer* tracer) : tracer_(tracer) {}
5196 void VisitPointers(Object** start, Object** end) {
5197 // Scan all HeapObject pointers in [start, end)
5198 for (Object** p = start; p < end; p++) {
5199 if ((*p)->IsHeapObject())
5200 tracer_->UnmarkRecursively(p, this);
5201 }
5202 }
5203
5204 private:
5205 PathTracer* tracer_;
5206};
5207
5208
5209void PathTracer::VisitPointers(Object** start, Object** end) {
5210 bool done = ((what_to_find_ == FIND_FIRST) && found_target_);
5211 // Visit all HeapObject pointers in [start, end)
5212 for (Object** p = start; !done && (p < end); p++) {
5213 if ((*p)->IsHeapObject()) {
5214 TracePathFrom(p);
5215 done = ((what_to_find_ == FIND_FIRST) && found_target_);
5216 }
5217 }
5218}
5219
5220
5221void PathTracer::Reset() {
5222 found_target_ = false;
5223 object_stack_.Clear();
5224}
5225
5226
5227void PathTracer::TracePathFrom(Object** root) {
5228 ASSERT((search_target_ == kAnyGlobalObject) ||
5229 search_target_->IsHeapObject());
5230 found_target_in_trace_ = false;
5231 object_stack_.Clear();
5232
5233 MarkVisitor mark_visitor(this);
5234 MarkRecursively(root, &mark_visitor);
5235
5236 UnmarkVisitor unmark_visitor(this);
5237 UnmarkRecursively(root, &unmark_visitor);
5238
5239 ProcessResults();
5240}
5241
5242
5243void PathTracer::MarkRecursively(Object** p, MarkVisitor* mark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005244 if (!(*p)->IsHeapObject()) return;
5245
5246 HeapObject* obj = HeapObject::cast(*p);
5247
5248 Object* map = obj->map();
5249
5250 if (!map->IsHeapObject()) return; // visited before
5251
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005252 if (found_target_in_trace_) return; // stop if target found
5253 object_stack_.Add(obj);
5254 if (((search_target_ == kAnyGlobalObject) && obj->IsJSGlobalObject()) ||
5255 (obj == search_target_)) {
5256 found_target_in_trace_ = true;
5257 found_target_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00005258 return;
5259 }
5260
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005261 bool is_global_context = obj->IsGlobalContext();
5262
Steve Blocka7e24c12009-10-30 11:49:00 +00005263 // not visited yet
5264 Map* map_p = reinterpret_cast<Map*>(HeapObject::cast(map));
5265
5266 Address map_addr = map_p->address();
5267
5268 obj->set_map(reinterpret_cast<Map*>(map_addr + kMarkTag));
5269
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005270 // Scan the object body.
5271 if (is_global_context && (visit_mode_ == VISIT_ONLY_STRONG)) {
5272 // This is specialized to scan Context's properly.
5273 Object** start = reinterpret_cast<Object**>(obj->address() +
5274 Context::kHeaderSize);
5275 Object** end = reinterpret_cast<Object**>(obj->address() +
5276 Context::kHeaderSize + Context::FIRST_WEAK_SLOT * kPointerSize);
5277 mark_visitor->VisitPointers(start, end);
5278 } else {
5279 obj->IterateBody(map_p->instance_type(),
5280 obj->SizeFromMap(map_p),
5281 mark_visitor);
5282 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005283
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005284 // Scan the map after the body because the body is a lot more interesting
5285 // when doing leak detection.
5286 MarkRecursively(&map, mark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00005287
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005288 if (!found_target_in_trace_) // don't pop if found the target
5289 object_stack_.RemoveLast();
Steve Blocka7e24c12009-10-30 11:49:00 +00005290}
5291
5292
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005293void PathTracer::UnmarkRecursively(Object** p, UnmarkVisitor* unmark_visitor) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005294 if (!(*p)->IsHeapObject()) return;
5295
5296 HeapObject* obj = HeapObject::cast(*p);
5297
5298 Object* map = obj->map();
5299
5300 if (map->IsHeapObject()) return; // unmarked already
5301
5302 Address map_addr = reinterpret_cast<Address>(map);
5303
5304 map_addr -= kMarkTag;
5305
5306 ASSERT_TAG_ALIGNED(map_addr);
5307
5308 HeapObject* map_p = HeapObject::FromAddress(map_addr);
5309
5310 obj->set_map(reinterpret_cast<Map*>(map_p));
5311
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005312 UnmarkRecursively(reinterpret_cast<Object**>(&map_p), unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00005313
5314 obj->IterateBody(Map::cast(map_p)->instance_type(),
5315 obj->SizeFromMap(Map::cast(map_p)),
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005316 unmark_visitor);
Steve Blocka7e24c12009-10-30 11:49:00 +00005317}
5318
5319
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005320void PathTracer::ProcessResults() {
5321 if (found_target_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005322 PrintF("=====================================\n");
5323 PrintF("==== Path to object ====\n");
5324 PrintF("=====================================\n\n");
5325
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005326 ASSERT(!object_stack_.is_empty());
5327 for (int i = 0; i < object_stack_.length(); i++) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005328 if (i > 0) PrintF("\n |\n |\n V\n\n");
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005329 Object* obj = object_stack_[i];
5330#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00005331 obj->Print();
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005332#else
5333 obj->ShortPrint();
5334#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005335 }
5336 PrintF("=====================================\n");
5337 }
5338}
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005339#endif // DEBUG || LIVE_OBJECT_LIST
Steve Blocka7e24c12009-10-30 11:49:00 +00005340
5341
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005342#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +00005343// Triggers a depth-first traversal of reachable objects from roots
5344// and finds a path to a specific heap object and prints it.
Leon Clarkee46be812010-01-19 14:06:41 +00005345void Heap::TracePathToObject(Object* target) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005346 PathTracer tracer(target, PathTracer::FIND_ALL, VISIT_ALL);
5347 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00005348}
5349
5350
5351// Triggers a depth-first traversal of reachable objects from roots
5352// and finds a path to any global object and prints it. Useful for
5353// determining the source for leaks of global objects.
5354void Heap::TracePathToGlobal() {
Ben Murdoche0cee9b2011-05-25 10:26:03 +01005355 PathTracer tracer(PathTracer::kAnyGlobalObject,
5356 PathTracer::FIND_ALL,
5357 VISIT_ALL);
5358 IterateRoots(&tracer, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00005359}
5360#endif
5361
5362
Ben Murdochf87a2032010-10-22 12:50:53 +01005363static intptr_t CountTotalHolesSize() {
5364 intptr_t holes_size = 0;
Leon Clarkef7060e22010-06-03 12:02:55 +01005365 OldSpaces spaces;
5366 for (OldSpace* space = spaces.next();
5367 space != NULL;
5368 space = spaces.next()) {
5369 holes_size += space->Waste() + space->AvailableFree();
5370 }
5371 return holes_size;
5372}
5373
5374
Steve Blocka7e24c12009-10-30 11:49:00 +00005375GCTracer::GCTracer()
5376 : start_time_(0.0),
Leon Clarkef7060e22010-06-03 12:02:55 +01005377 start_size_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +00005378 gc_count_(0),
5379 full_gc_count_(0),
5380 is_compacting_(false),
Leon Clarkef7060e22010-06-03 12:02:55 +01005381 marked_count_(0),
5382 allocated_since_last_gc_(0),
5383 spent_in_mutator_(0),
5384 promoted_objects_size_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005385 // These two fields reflect the state of the previous full collection.
5386 // Set them before they are changed by the collector.
5387 previous_has_compacted_ = MarkCompactCollector::HasCompacted();
5388 previous_marked_count_ = MarkCompactCollector::previous_marked_count();
Leon Clarkef7060e22010-06-03 12:02:55 +01005389 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00005390 start_time_ = OS::TimeCurrentMillis();
Leon Clarkef7060e22010-06-03 12:02:55 +01005391 start_size_ = Heap::SizeOfObjects();
5392
5393 for (int i = 0; i < Scope::kNumberOfScopes; i++) {
5394 scopes_[i] = 0;
5395 }
5396
5397 in_free_list_or_wasted_before_gc_ = CountTotalHolesSize();
5398
5399 allocated_since_last_gc_ = Heap::SizeOfObjects() - alive_after_last_gc_;
5400
5401 if (last_gc_end_timestamp_ > 0) {
5402 spent_in_mutator_ = Max(start_time_ - last_gc_end_timestamp_, 0.0);
5403 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005404}
5405
5406
5407GCTracer::~GCTracer() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005408 // Printf ONE line iff flag is set.
Leon Clarkef7060e22010-06-03 12:02:55 +01005409 if (!FLAG_trace_gc && !FLAG_print_cumulative_gc_stat) return;
5410
5411 bool first_gc = (last_gc_end_timestamp_ == 0);
5412
5413 alive_after_last_gc_ = Heap::SizeOfObjects();
5414 last_gc_end_timestamp_ = OS::TimeCurrentMillis();
5415
5416 int time = static_cast<int>(last_gc_end_timestamp_ - start_time_);
5417
5418 // Update cumulative GC statistics if required.
5419 if (FLAG_print_cumulative_gc_stat) {
5420 max_gc_pause_ = Max(max_gc_pause_, time);
5421 max_alive_after_gc_ = Max(max_alive_after_gc_, alive_after_last_gc_);
5422 if (!first_gc) {
5423 min_in_mutator_ = Min(min_in_mutator_,
5424 static_cast<int>(spent_in_mutator_));
5425 }
5426 }
5427
5428 if (!FLAG_trace_gc_nvp) {
5429 int external_time = static_cast<int>(scopes_[Scope::EXTERNAL]);
5430
5431 PrintF("%s %.1f -> %.1f MB, ",
5432 CollectorString(),
5433 static_cast<double>(start_size_) / MB,
5434 SizeOfHeapObjects());
5435
5436 if (external_time > 0) PrintF("%d / ", external_time);
5437 PrintF("%d ms.\n", time);
5438 } else {
5439 PrintF("pause=%d ", time);
5440 PrintF("mutator=%d ",
5441 static_cast<int>(spent_in_mutator_));
5442
5443 PrintF("gc=");
5444 switch (collector_) {
5445 case SCAVENGER:
5446 PrintF("s");
5447 break;
5448 case MARK_COMPACTOR:
5449 PrintF(MarkCompactCollector::HasCompacted() ? "mc" : "ms");
5450 break;
5451 default:
5452 UNREACHABLE();
5453 }
5454 PrintF(" ");
5455
5456 PrintF("external=%d ", static_cast<int>(scopes_[Scope::EXTERNAL]));
5457 PrintF("mark=%d ", static_cast<int>(scopes_[Scope::MC_MARK]));
5458 PrintF("sweep=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP]));
Iain Merrick75681382010-08-19 15:07:18 +01005459 PrintF("sweepns=%d ", static_cast<int>(scopes_[Scope::MC_SWEEP_NEWSPACE]));
Leon Clarkef7060e22010-06-03 12:02:55 +01005460 PrintF("compact=%d ", static_cast<int>(scopes_[Scope::MC_COMPACT]));
5461
Ben Murdochf87a2032010-10-22 12:50:53 +01005462 PrintF("total_size_before=%" V8_PTR_PREFIX "d ", start_size_);
5463 PrintF("total_size_after=%" V8_PTR_PREFIX "d ", Heap::SizeOfObjects());
5464 PrintF("holes_size_before=%" V8_PTR_PREFIX "d ",
5465 in_free_list_or_wasted_before_gc_);
5466 PrintF("holes_size_after=%" V8_PTR_PREFIX "d ", CountTotalHolesSize());
Leon Clarkef7060e22010-06-03 12:02:55 +01005467
Ben Murdochf87a2032010-10-22 12:50:53 +01005468 PrintF("allocated=%" V8_PTR_PREFIX "d ", allocated_since_last_gc_);
5469 PrintF("promoted=%" V8_PTR_PREFIX "d ", promoted_objects_size_);
Leon Clarkef7060e22010-06-03 12:02:55 +01005470
5471 PrintF("\n");
5472 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005473
5474#if defined(ENABLE_LOGGING_AND_PROFILING)
5475 Heap::PrintShortHeapStatistics();
5476#endif
5477}
5478
5479
5480const char* GCTracer::CollectorString() {
5481 switch (collector_) {
5482 case SCAVENGER:
5483 return "Scavenge";
5484 case MARK_COMPACTOR:
5485 return MarkCompactCollector::HasCompacted() ? "Mark-compact"
5486 : "Mark-sweep";
5487 }
5488 return "Unknown GC";
5489}
5490
5491
5492int KeyedLookupCache::Hash(Map* map, String* name) {
5493 // Uses only lower 32 bits if pointers are larger.
5494 uintptr_t addr_hash =
Leon Clarkee46be812010-01-19 14:06:41 +00005495 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(map)) >> kMapHashShift;
Andrei Popescu402d9372010-02-26 13:31:12 +00005496 return static_cast<uint32_t>((addr_hash ^ name->Hash()) & kCapacityMask);
Steve Blocka7e24c12009-10-30 11:49:00 +00005497}
5498
5499
5500int KeyedLookupCache::Lookup(Map* map, String* name) {
5501 int index = Hash(map, name);
5502 Key& key = keys_[index];
5503 if ((key.map == map) && key.name->Equals(name)) {
5504 return field_offsets_[index];
5505 }
5506 return -1;
5507}
5508
5509
5510void KeyedLookupCache::Update(Map* map, String* name, int field_offset) {
5511 String* symbol;
5512 if (Heap::LookupSymbolIfExists(name, &symbol)) {
5513 int index = Hash(map, symbol);
5514 Key& key = keys_[index];
5515 key.map = map;
5516 key.name = symbol;
5517 field_offsets_[index] = field_offset;
5518 }
5519}
5520
5521
5522void KeyedLookupCache::Clear() {
5523 for (int index = 0; index < kLength; index++) keys_[index].map = NULL;
5524}
5525
5526
5527KeyedLookupCache::Key KeyedLookupCache::keys_[KeyedLookupCache::kLength];
5528
5529
5530int KeyedLookupCache::field_offsets_[KeyedLookupCache::kLength];
5531
5532
5533void DescriptorLookupCache::Clear() {
5534 for (int index = 0; index < kLength; index++) keys_[index].array = NULL;
5535}
5536
5537
5538DescriptorLookupCache::Key
5539DescriptorLookupCache::keys_[DescriptorLookupCache::kLength];
5540
5541int DescriptorLookupCache::results_[DescriptorLookupCache::kLength];
5542
5543
5544#ifdef DEBUG
Ben Murdochf87a2032010-10-22 12:50:53 +01005545void Heap::GarbageCollectionGreedyCheck() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005546 ASSERT(FLAG_gc_greedy);
Ben Murdochf87a2032010-10-22 12:50:53 +01005547 if (Bootstrapper::IsActive()) return;
5548 if (disallow_allocation_failure()) return;
5549 CollectGarbage(NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005550}
5551#endif
5552
5553
5554TranscendentalCache::TranscendentalCache(TranscendentalCache::Type t)
5555 : type_(t) {
5556 uint32_t in0 = 0xffffffffu; // Bit-pattern for a NaN that isn't
5557 uint32_t in1 = 0xffffffffu; // generated by the FPU.
5558 for (int i = 0; i < kCacheSize; i++) {
5559 elements_[i].in[0] = in0;
5560 elements_[i].in[1] = in1;
5561 elements_[i].output = NULL;
5562 }
5563}
5564
5565
5566TranscendentalCache* TranscendentalCache::caches_[kNumberOfCaches];
5567
5568
5569void TranscendentalCache::Clear() {
5570 for (int i = 0; i < kNumberOfCaches; i++) {
5571 if (caches_[i] != NULL) {
5572 delete caches_[i];
5573 caches_[i] = NULL;
5574 }
5575 }
5576}
5577
5578
Leon Clarkee46be812010-01-19 14:06:41 +00005579void ExternalStringTable::CleanUp() {
5580 int last = 0;
5581 for (int i = 0; i < new_space_strings_.length(); ++i) {
5582 if (new_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
5583 if (Heap::InNewSpace(new_space_strings_[i])) {
5584 new_space_strings_[last++] = new_space_strings_[i];
5585 } else {
5586 old_space_strings_.Add(new_space_strings_[i]);
5587 }
5588 }
5589 new_space_strings_.Rewind(last);
5590 last = 0;
5591 for (int i = 0; i < old_space_strings_.length(); ++i) {
5592 if (old_space_strings_[i] == Heap::raw_unchecked_null_value()) continue;
5593 ASSERT(!Heap::InNewSpace(old_space_strings_[i]));
5594 old_space_strings_[last++] = old_space_strings_[i];
5595 }
5596 old_space_strings_.Rewind(last);
5597 Verify();
5598}
5599
5600
5601void ExternalStringTable::TearDown() {
5602 new_space_strings_.Free();
5603 old_space_strings_.Free();
5604}
5605
5606
5607List<Object*> ExternalStringTable::new_space_strings_;
5608List<Object*> ExternalStringTable::old_space_strings_;
5609
Steve Blocka7e24c12009-10-30 11:49:00 +00005610} } // namespace v8::internal