blob: 337f0143bc026e72e65b68ec70a391b38eea7b1c [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "macro-assembler.h"
31#include "mark-compact.h"
32#include "platform.h"
33
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034namespace v8 {
35namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000037// For contiguous spaces, top should be in the space (or at the end) and limit
38// should be the end of the space.
39#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +000040 ASSERT((space).low() <= (info).top \
41 && (info).top <= (space).high() \
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +000042 && (info).limit == (space).high())
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044
45// ----------------------------------------------------------------------------
46// HeapObjectIterator
47
48HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
49 Initialize(space->bottom(), space->top(), NULL);
50}
51
52
53HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
54 HeapObjectCallback size_func) {
55 Initialize(space->bottom(), space->top(), size_func);
56}
57
58
59HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start) {
60 Initialize(start, space->top(), NULL);
61}
62
63
64HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start,
65 HeapObjectCallback size_func) {
66 Initialize(start, space->top(), size_func);
67}
68
69
70void HeapObjectIterator::Initialize(Address cur, Address end,
71 HeapObjectCallback size_f) {
72 cur_addr_ = cur;
73 end_addr_ = end;
74 end_page_ = Page::FromAllocationTop(end);
75 size_func_ = size_f;
76 Page* p = Page::FromAllocationTop(cur_addr_);
77 cur_limit_ = (p == end_page_) ? end_addr_ : p->AllocationTop();
78
79#ifdef DEBUG
80 Verify();
81#endif
82}
83
84
85bool HeapObjectIterator::HasNextInNextPage() {
86 if (cur_addr_ == end_addr_) return false;
87
88 Page* cur_page = Page::FromAllocationTop(cur_addr_);
89 cur_page = cur_page->next_page();
90 ASSERT(cur_page->is_valid());
91
92 cur_addr_ = cur_page->ObjectAreaStart();
93 cur_limit_ = (cur_page == end_page_) ? end_addr_ : cur_page->AllocationTop();
94
95 ASSERT(cur_addr_ < cur_limit_);
96#ifdef DEBUG
97 Verify();
98#endif
99 return true;
100}
101
102
103#ifdef DEBUG
104void HeapObjectIterator::Verify() {
105 Page* p = Page::FromAllocationTop(cur_addr_);
106 ASSERT(p == Page::FromAllocationTop(cur_limit_));
107 ASSERT(p->Offset(cur_addr_) <= p->Offset(cur_limit_));
108}
109#endif
110
111
112// -----------------------------------------------------------------------------
113// PageIterator
114
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000115PageIterator::PageIterator(PagedSpace* space, Mode mode) : space_(space) {
116 prev_page_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 switch (mode) {
118 case PAGES_IN_USE:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000119 stop_page_ = space->AllocationTopPage();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000120 break;
121 case PAGES_USED_BY_MC:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000122 stop_page_ = space->MCRelocationTopPage();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 break;
124 case ALL_PAGES:
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000125#ifdef DEBUG
126 // Verify that the cached last page in the space is actually the
127 // last page.
128 for (Page* p = space->first_page_; p->is_valid(); p = p->next_page()) {
129 if (!p->next_page()->is_valid()) {
130 ASSERT(space->last_page_ == p);
131 }
132 }
133#endif
134 stop_page_ = space->last_page_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000135 break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000136 }
137}
138
139
140// -----------------------------------------------------------------------------
141// Page
142
143#ifdef DEBUG
144Page::RSetState Page::rset_state_ = Page::IN_USE;
145#endif
146
147// -----------------------------------------------------------------------------
148// MemoryAllocator
149//
150int MemoryAllocator::capacity_ = 0;
151int MemoryAllocator::size_ = 0;
152
153VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
154
155// 270 is an estimate based on the static default heap size of a pair of 256K
156// semispaces and a 64M old generation.
157const int kEstimatedNumberOfChunks = 270;
158List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
159 kEstimatedNumberOfChunks);
160List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
161int MemoryAllocator::max_nof_chunks_ = 0;
162int MemoryAllocator::top_ = 0;
163
164
165void MemoryAllocator::Push(int free_chunk_id) {
166 ASSERT(max_nof_chunks_ > 0);
167 ASSERT(top_ < max_nof_chunks_);
168 free_chunk_ids_[top_++] = free_chunk_id;
169}
170
171
172int MemoryAllocator::Pop() {
173 ASSERT(top_ > 0);
174 return free_chunk_ids_[--top_];
175}
176
177
178bool MemoryAllocator::Setup(int capacity) {
179 capacity_ = RoundUp(capacity, Page::kPageSize);
180
181 // Over-estimate the size of chunks_ array. It assumes the expansion of old
182 // space is always in the unit of a chunk (kChunkSize) except the last
183 // expansion.
184 //
185 // Due to alignment, allocated space might be one page less than required
186 // number (kPagesPerChunk) of pages for old spaces.
187 //
kasper.lund7276f142008-07-30 08:49:36 +0000188 // Reserve two chunk ids for semispaces, one for map space, one for old
189 // space, and one for code space.
190 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000191 if (max_nof_chunks_ > kMaxNofChunks) return false;
192
193 size_ = 0;
194 ChunkInfo info; // uninitialized element.
195 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
196 chunks_.Add(info);
197 free_chunk_ids_.Add(i);
198 }
199 top_ = max_nof_chunks_;
200 return true;
201}
202
203
204void MemoryAllocator::TearDown() {
205 for (int i = 0; i < max_nof_chunks_; i++) {
206 if (chunks_[i].address() != NULL) DeleteChunk(i);
207 }
208 chunks_.Clear();
209 free_chunk_ids_.Clear();
210
211 if (initial_chunk_ != NULL) {
212 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
213 delete initial_chunk_;
214 initial_chunk_ = NULL;
215 }
216
217 ASSERT(top_ == max_nof_chunks_); // all chunks are free
218 top_ = 0;
219 capacity_ = 0;
220 size_ = 0;
221 max_nof_chunks_ = 0;
222}
223
224
225void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000226 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000227 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
229
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000230 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000231 int alloced = *allocated;
232 size_ += alloced;
233 Counters::memory_allocated.Increment(alloced);
234 return mem;
235}
236
237
238void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
239 OS::Free(mem, length);
240 Counters::memory_allocated.Decrement(length);
241 size_ -= length;
242 ASSERT(size_ >= 0);
243}
244
245
246void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
247 ASSERT(initial_chunk_ == NULL);
248
249 initial_chunk_ = new VirtualMemory(requested);
250 CHECK(initial_chunk_ != NULL);
251 if (!initial_chunk_->IsReserved()) {
252 delete initial_chunk_;
253 initial_chunk_ = NULL;
254 return NULL;
255 }
256
257 // We are sure that we have mapped a block of requested addresses.
258 ASSERT(initial_chunk_->size() == requested);
259 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
260 size_ += requested;
261 return initial_chunk_->address();
262}
263
264
265static int PagesInChunk(Address start, size_t size) {
266 // The first page starts on the first page-aligned address from start onward
267 // and the last page ends on the last page-aligned address before
268 // start+size. Page::kPageSize is a power of two so we can divide by
269 // shifting.
270 return (RoundDown(start + size, Page::kPageSize)
271 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
272}
273
274
275Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
276 PagedSpace* owner) {
277 if (requested_pages <= 0) return Page::FromAddress(NULL);
278 size_t chunk_size = requested_pages * Page::kPageSize;
279
280 // There is not enough space to guarantee the desired number pages can be
281 // allocated.
282 if (size_ + static_cast<int>(chunk_size) > capacity_) {
283 // Request as many pages as we can.
284 chunk_size = capacity_ - size_;
285 requested_pages = chunk_size >> Page::kPageSizeBits;
286
287 if (requested_pages <= 0) return Page::FromAddress(NULL);
288 }
kasper.lund7276f142008-07-30 08:49:36 +0000289 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 if (chunk == NULL) return Page::FromAddress(NULL);
291 LOG(NewEvent("PagedChunk", chunk, chunk_size));
292
293 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
294 if (*allocated_pages == 0) {
295 FreeRawMemory(chunk, chunk_size);
296 LOG(DeleteEvent("PagedChunk", chunk));
297 return Page::FromAddress(NULL);
298 }
299
300 int chunk_id = Pop();
301 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
302
303 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
304}
305
306
307Page* MemoryAllocator::CommitPages(Address start, size_t size,
308 PagedSpace* owner, int* num_pages) {
309 ASSERT(start != NULL);
310 *num_pages = PagesInChunk(start, size);
311 ASSERT(*num_pages > 0);
312 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000313 ASSERT(InInitialChunk(start));
314 ASSERT(InInitialChunk(start + size - 1));
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000315 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316 return Page::FromAddress(NULL);
317 }
318 Counters::memory_allocated.Increment(size);
319
320 // So long as we correctly overestimated the number of chunks we should not
321 // run out of chunk ids.
322 CHECK(!OutOfChunkIds());
323 int chunk_id = Pop();
324 chunks_[chunk_id].init(start, size, owner);
325 return InitializePagesInChunk(chunk_id, *num_pages, owner);
326}
327
328
kasper.lund7276f142008-07-30 08:49:36 +0000329bool MemoryAllocator::CommitBlock(Address start,
330 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000331 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000332 ASSERT(start != NULL);
333 ASSERT(size > 0);
334 ASSERT(initial_chunk_ != NULL);
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000335 ASSERT(InInitialChunk(start));
336 ASSERT(InInitialChunk(start + size - 1));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000337
kasper.lund7276f142008-07-30 08:49:36 +0000338 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 Counters::memory_allocated.Increment(size);
340 return true;
341}
342
ager@chromium.orgadd848f2009-08-13 12:44:13 +0000343bool MemoryAllocator::UncommitBlock(Address start, size_t size) {
344 ASSERT(start != NULL);
345 ASSERT(size > 0);
346 ASSERT(initial_chunk_ != NULL);
347 ASSERT(InInitialChunk(start));
348 ASSERT(InInitialChunk(start + size - 1));
349
350 if (!initial_chunk_->Uncommit(start, size)) return false;
351 Counters::memory_allocated.Decrement(size);
352 return true;
353}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000354
355Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
356 PagedSpace* owner) {
357 ASSERT(IsValidChunk(chunk_id));
358 ASSERT(pages_in_chunk > 0);
359
360 Address chunk_start = chunks_[chunk_id].address();
361
362 Address low = RoundUp(chunk_start, Page::kPageSize);
363
364#ifdef DEBUG
365 size_t chunk_size = chunks_[chunk_id].size();
366 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
367 ASSERT(pages_in_chunk <=
368 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
369#endif
370
371 Address page_addr = low;
372 for (int i = 0; i < pages_in_chunk; i++) {
373 Page* p = Page::FromAddress(page_addr);
374 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
375 p->is_normal_page = 1;
376 page_addr += Page::kPageSize;
377 }
378
379 // Set the next page of the last page to 0.
380 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
381 last_page->opaque_header = OffsetFrom(0) | chunk_id;
382
383 return Page::FromAddress(low);
384}
385
386
387Page* MemoryAllocator::FreePages(Page* p) {
388 if (!p->is_valid()) return p;
389
390 // Find the first page in the same chunk as 'p'
391 Page* first_page = FindFirstPageInSameChunk(p);
392 Page* page_to_return = Page::FromAddress(NULL);
393
394 if (p != first_page) {
395 // Find the last page in the same chunk as 'prev'.
396 Page* last_page = FindLastPageInSameChunk(p);
397 first_page = GetNextPage(last_page); // first page in next chunk
398
399 // set the next_page of last_page to NULL
400 SetNextPage(last_page, Page::FromAddress(NULL));
401 page_to_return = p; // return 'p' when exiting
402 }
403
404 while (first_page->is_valid()) {
405 int chunk_id = GetChunkId(first_page);
406 ASSERT(IsValidChunk(chunk_id));
407
408 // Find the first page of the next chunk before deleting this chunk.
409 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
410
411 // Free the current chunk.
412 DeleteChunk(chunk_id);
413 }
414
415 return page_to_return;
416}
417
418
419void MemoryAllocator::DeleteChunk(int chunk_id) {
420 ASSERT(IsValidChunk(chunk_id));
421
422 ChunkInfo& c = chunks_[chunk_id];
423
424 // We cannot free a chunk contained in the initial chunk because it was not
425 // allocated with AllocateRawMemory. Instead we uncommit the virtual
426 // memory.
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000427 if (InInitialChunk(c.address())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000428 // TODO(1240712): VirtualMemory::Uncommit has a return value which
429 // is ignored here.
430 initial_chunk_->Uncommit(c.address(), c.size());
431 Counters::memory_allocated.Decrement(c.size());
432 } else {
433 LOG(DeleteEvent("PagedChunk", c.address()));
434 FreeRawMemory(c.address(), c.size());
435 }
436 c.init(NULL, 0, NULL);
437 Push(chunk_id);
438}
439
440
441Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
442 int chunk_id = GetChunkId(p);
443 ASSERT(IsValidChunk(chunk_id));
444
445 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
446 return Page::FromAddress(low);
447}
448
449
450Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
451 int chunk_id = GetChunkId(p);
452 ASSERT(IsValidChunk(chunk_id));
453
454 Address chunk_start = chunks_[chunk_id].address();
455 size_t chunk_size = chunks_[chunk_id].size();
456
457 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
458 ASSERT(chunk_start <= p->address() && p->address() < high);
459
460 return Page::FromAddress(high - Page::kPageSize);
461}
462
463
464#ifdef DEBUG
465void MemoryAllocator::ReportStatistics() {
466 float pct = static_cast<float>(capacity_ - size_) / capacity_;
467 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
468 capacity_, size_, static_cast<int>(pct*100));
469}
470#endif
471
472
473// -----------------------------------------------------------------------------
474// PagedSpace implementation
475
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000476PagedSpace::PagedSpace(int max_capacity,
477 AllocationSpace id,
478 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000479 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
481 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000482 accounting_stats_.Clear();
483
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000484 allocation_info_.top = NULL;
485 allocation_info_.limit = NULL;
486
487 mc_forwarding_info_.top = NULL;
488 mc_forwarding_info_.limit = NULL;
489}
490
491
492bool PagedSpace::Setup(Address start, size_t size) {
493 if (HasBeenSetup()) return false;
494
495 int num_pages = 0;
496 // Try to use the virtual memory range passed to us. If it is too small to
497 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000498 int pages_in_chunk = PagesInChunk(start, size);
499 if (pages_in_chunk > 0) {
500 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
501 Page::kPageSize * pages_in_chunk,
502 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000503 } else {
504 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
505 max_capacity_ / Page::kObjectAreaSize);
506 first_page_ =
507 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
508 if (!first_page_->is_valid()) return false;
509 }
510
511 // We are sure that the first page is valid and that we have at least one
512 // page.
513 ASSERT(first_page_->is_valid());
514 ASSERT(num_pages > 0);
515 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
516 ASSERT(Capacity() <= max_capacity_);
517
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000518 // Sequentially initialize remembered sets in the newly allocated
519 // pages and cache the current last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
521 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000522 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000523 }
524
525 // Use first_page_ for allocation.
526 SetAllocationInfo(&allocation_info_, first_page_);
527
528 return true;
529}
530
531
532bool PagedSpace::HasBeenSetup() {
533 return (Capacity() > 0);
534}
535
536
537void PagedSpace::TearDown() {
538 first_page_ = MemoryAllocator::FreePages(first_page_);
539 ASSERT(!first_page_->is_valid());
540
541 accounting_stats_.Clear();
542}
543
544
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000545#ifdef ENABLE_HEAP_PROTECTION
546
547void PagedSpace::Protect() {
548 Page* page = first_page_;
549 while (page->is_valid()) {
550 MemoryAllocator::ProtectChunkFromPage(page);
551 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
552 }
553}
554
555
556void PagedSpace::Unprotect() {
557 Page* page = first_page_;
558 while (page->is_valid()) {
559 MemoryAllocator::UnprotectChunkFromPage(page);
560 page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
561 }
562}
563
564#endif
565
566
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000567void PagedSpace::ClearRSet() {
568 PageIterator it(this, PageIterator::ALL_PAGES);
569 while (it.has_next()) {
570 it.next()->ClearRSet();
571 }
572}
573
574
575Object* PagedSpace::FindObject(Address addr) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 // Note: this function can only be called before or after mark-compact GC
577 // because it accesses map pointers.
578 ASSERT(!MarkCompactCollector::in_use());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579
580 if (!Contains(addr)) return Failure::Exception();
581
582 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000583 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000584 Address cur = p->ObjectAreaStart();
585 Address end = p->AllocationTop();
586 while (cur < end) {
587 HeapObject* obj = HeapObject::FromAddress(cur);
588 Address next = cur + obj->Size();
589 if ((cur <= addr) && (addr < next)) return obj;
590 cur = next;
591 }
592
kasper.lund7276f142008-07-30 08:49:36 +0000593 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594 return Failure::Exception();
595}
596
597
kasper.lund7276f142008-07-30 08:49:36 +0000598bool PagedSpace::IsUsed(Page* page) {
599 PageIterator it(this, PageIterator::PAGES_IN_USE);
600 while (it.has_next()) {
601 if (page == it.next()) return true;
602 }
603 return false;
604}
605
606
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
608 alloc_info->top = p->ObjectAreaStart();
609 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000610 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000611}
612
613
614void PagedSpace::MCResetRelocationInfo() {
615 // Set page indexes.
616 int i = 0;
617 PageIterator it(this, PageIterator::ALL_PAGES);
618 while (it.has_next()) {
619 Page* p = it.next();
620 p->mc_page_index = i++;
621 }
622
623 // Set mc_forwarding_info_ to the first page in the space.
624 SetAllocationInfo(&mc_forwarding_info_, first_page_);
625 // All the bytes in the space are 'available'. We will rediscover
626 // allocated and wasted bytes during GC.
627 accounting_stats_.Reset();
628}
629
630
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
632#ifdef DEBUG
633 // The Contains function considers the address at the beginning of a
634 // page in the page, MCSpaceOffsetForAddress considers it is in the
635 // previous page.
636 if (Page::IsAlignedToPageSize(addr)) {
637 ASSERT(Contains(addr - kPointerSize));
638 } else {
639 ASSERT(Contains(addr));
640 }
641#endif
642
643 // If addr is at the end of a page, it belongs to previous page
644 Page* p = Page::IsAlignedToPageSize(addr)
645 ? Page::FromAllocationTop(addr)
646 : Page::FromAddress(addr);
647 int index = p->mc_page_index;
648 return (index * Page::kPageSize) + p->Offset(addr);
649}
650
651
kasper.lund7276f142008-07-30 08:49:36 +0000652// Slow case for reallocating and promoting objects during a compacting
653// collection. This function is not space-specific.
654HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
655 Page* current_page = TopPageOf(mc_forwarding_info_);
656 if (!current_page->next_page()->is_valid()) {
657 if (!Expand(current_page)) {
658 return NULL;
659 }
660 }
661
662 // There are surely more pages in the space now.
663 ASSERT(current_page->next_page()->is_valid());
664 // We do not add the top of page block for current page to the space's
665 // free list---the block may contain live objects so we cannot write
666 // bookkeeping information to it. Instead, we will recover top of page
667 // blocks when we move objects to their new locations.
668 //
669 // We do however write the allocation pointer to the page. The encoding
670 // of forwarding addresses is as an offset in terms of live bytes, so we
671 // need quick access to the allocation top of each page to decode
672 // forwarding addresses.
673 current_page->mc_relocation_top = mc_forwarding_info_.top;
674 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
675 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
676}
677
678
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000679bool PagedSpace::Expand(Page* last_page) {
680 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
681 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
682
683 if (Capacity() == max_capacity_) return false;
684
685 ASSERT(Capacity() < max_capacity_);
686 // Last page must be valid and its next page is invalid.
687 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
688
689 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
690 if (available_pages <= 0) return false;
691
692 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
693 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
694 if (!p->is_valid()) return false;
695
696 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
697 ASSERT(Capacity() <= max_capacity_);
698
699 MemoryAllocator::SetNextPage(last_page, p);
700
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000701 // Sequentially clear remembered set of new pages and and cache the
702 // new last page in the space.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703 while (p->is_valid()) {
704 p->ClearRSet();
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000705 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706 p = p->next_page();
707 }
708
709 return true;
710}
711
712
713#ifdef DEBUG
714int PagedSpace::CountTotalPages() {
715 int count = 0;
716 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
717 count++;
718 }
719 return count;
720}
721#endif
722
723
724void PagedSpace::Shrink() {
725 // Release half of free pages.
726 Page* top_page = AllocationTopPage();
727 ASSERT(top_page->is_valid());
728
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000729 // Count the number of pages we would like to free.
730 int pages_to_free = 0;
731 for (Page* p = top_page->next_page(); p->is_valid(); p = p->next_page()) {
732 pages_to_free++;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000733 }
734
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000735 // Free pages after top_page.
736 Page* p = MemoryAllocator::FreePages(top_page->next_page());
737 MemoryAllocator::SetNextPage(top_page, p);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000738
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000739 // Find out how many pages we failed to free and update last_page_.
740 // Please note pages can only be freed in whole chunks.
741 last_page_ = top_page;
742 for (Page* p = top_page->next_page(); p->is_valid(); p = p->next_page()) {
743 pages_to_free--;
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000744 last_page_ = p;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 }
746
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000747 accounting_stats_.ShrinkSpace(pages_to_free * Page::kObjectAreaSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000748 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
749}
750
751
752bool PagedSpace::EnsureCapacity(int capacity) {
753 if (Capacity() >= capacity) return true;
754
755 // Start from the allocation top and loop to the last page in the space.
756 Page* last_page = AllocationTopPage();
757 Page* next_page = last_page->next_page();
758 while (next_page->is_valid()) {
759 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
760 next_page = last_page->next_page();
761 }
762
763 // Expand the space until it has the required capacity or expansion fails.
764 do {
765 if (!Expand(last_page)) return false;
766 ASSERT(last_page->next_page()->is_valid());
767 last_page =
768 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
769 } while (Capacity() < capacity);
770
771 return true;
772}
773
774
775#ifdef DEBUG
776void PagedSpace::Print() { }
777#endif
778
779
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +0000780#ifdef DEBUG
781// We do not assume that the PageIterator works, because it depends on the
782// invariants we are checking during verification.
783void PagedSpace::Verify(ObjectVisitor* visitor) {
784 // The allocation pointer should be valid, and it should be in a page in the
785 // space.
786 ASSERT(allocation_info_.VerifyPagedAllocation());
787 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
788 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
789
790 // Loop over all the pages.
791 bool above_allocation_top = false;
792 Page* current_page = first_page_;
793 while (current_page->is_valid()) {
794 if (above_allocation_top) {
795 // We don't care what's above the allocation top.
796 } else {
797 // Unless this is the last page in the space containing allocated
798 // objects, the allocation top should be at a constant offset from the
799 // object area end.
800 Address top = current_page->AllocationTop();
801 if (current_page == top_page) {
802 ASSERT(top == allocation_info_.top);
803 // The next page will be above the allocation top.
804 above_allocation_top = true;
805 } else {
806 ASSERT(top == current_page->ObjectAreaEnd() - page_extra_);
807 }
808
809 // It should be packed with objects from the bottom to the top.
810 Address current = current_page->ObjectAreaStart();
811 while (current < top) {
812 HeapObject* object = HeapObject::FromAddress(current);
813
814 // The first word should be a map, and we expect all map pointers to
815 // be in map space.
816 Map* map = object->map();
817 ASSERT(map->IsMap());
818 ASSERT(Heap::map_space()->Contains(map));
819
820 // Perform space-specific object verification.
821 VerifyObject(object);
822
823 // The object itself should look OK.
824 object->Verify();
825
826 // All the interior pointers should be contained in the heap and
827 // have their remembered set bits set if required as determined
828 // by the visitor.
829 int size = object->Size();
830 if (object->IsCode()) {
831 Code::cast(object)->ConvertICTargetsFromAddressToObject();
832 object->IterateBody(map->instance_type(), size, visitor);
833 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
834 } else {
835 object->IterateBody(map->instance_type(), size, visitor);
836 }
837
838 current += size;
839 }
840
841 // The allocation pointer should not be in the middle of an object.
842 ASSERT(current == top);
843 }
844
845 current_page = current_page->next_page();
846 }
847}
848#endif
849
850
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000851// -----------------------------------------------------------------------------
852// NewSpace implementation
853
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000854
855bool NewSpace::Setup(Address start, int size) {
856 // Setup new space based on the preallocated memory block defined by
857 // start and size. The provided space is divided into two semi-spaces.
858 // To support fast containment testing in the new space, the size of
859 // this chunk must be a power of two and it must be aligned to its size.
860 int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
861 int maximum_semispace_capacity = Heap::SemiSpaceSize();
862
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
864 ASSERT(IsPowerOf2(maximum_semispace_capacity));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000865
866 // Allocate and setup the histogram arrays if necessary.
867#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
868 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
869 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
870
871#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
872 promoted_histogram_[name].set_name(#name);
873 INSTANCE_TYPE_LIST(SET_NAME)
874#undef SET_NAME
875#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000876
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000877 ASSERT(size == 2 * maximum_semispace_capacity);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878 ASSERT(IsAddressAligned(start, size, 0));
879
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000880 if (!to_space_.Setup(start,
881 initial_semispace_capacity,
882 maximum_semispace_capacity)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000883 return false;
884 }
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000885 if (!from_space_.Setup(start + maximum_semispace_capacity,
886 initial_semispace_capacity,
887 maximum_semispace_capacity)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000888 return false;
889 }
890
891 start_ = start;
892 address_mask_ = ~(size - 1);
893 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +0000894 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000895
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000896 allocation_info_.top = to_space_.low();
897 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898 mc_forwarding_info_.top = NULL;
899 mc_forwarding_info_.limit = NULL;
900
901 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
902 return true;
903}
904
905
906void NewSpace::TearDown() {
907#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
908 if (allocated_histogram_) {
909 DeleteArray(allocated_histogram_);
910 allocated_histogram_ = NULL;
911 }
912 if (promoted_histogram_) {
913 DeleteArray(promoted_histogram_);
914 promoted_histogram_ = NULL;
915 }
916#endif
917
918 start_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000919 allocation_info_.top = NULL;
920 allocation_info_.limit = NULL;
921 mc_forwarding_info_.top = NULL;
922 mc_forwarding_info_.limit = NULL;
923
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000924 to_space_.TearDown();
925 from_space_.TearDown();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000926}
927
928
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +0000929#ifdef ENABLE_HEAP_PROTECTION
930
931void NewSpace::Protect() {
932 MemoryAllocator::Protect(ToSpaceLow(), Capacity());
933 MemoryAllocator::Protect(FromSpaceLow(), Capacity());
934}
935
936
937void NewSpace::Unprotect() {
938 MemoryAllocator::Unprotect(ToSpaceLow(), Capacity(),
939 to_space_.executable());
940 MemoryAllocator::Unprotect(FromSpaceLow(), Capacity(),
941 from_space_.executable());
942}
943
944#endif
945
946
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000947void NewSpace::Flip() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000948 SemiSpace tmp = from_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000949 from_space_ = to_space_;
950 to_space_ = tmp;
951}
952
953
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000954bool NewSpace::Grow() {
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000955 ASSERT(Capacity() < MaximumCapacity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000956 // TODO(1240712): Failure to double the from space can result in
957 // semispaces of different sizes. In the event of that failure, the
958 // to space doubling should be rolled back before returning false.
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +0000959 if (!to_space_.Grow() || !from_space_.Grow()) return false;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000960 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000961 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
962 return true;
963}
964
965
966void NewSpace::ResetAllocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000967 allocation_info_.top = to_space_.low();
968 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000969 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
970}
971
972
973void NewSpace::MCResetRelocationInfo() {
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000974 mc_forwarding_info_.top = from_space_.low();
975 mc_forwarding_info_.limit = from_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000976 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
977}
978
979
980void NewSpace::MCCommitRelocationInfo() {
981 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
982 // valid allocation info for the to space.
983 allocation_info_.top = mc_forwarding_info_.top;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000984 allocation_info_.limit = to_space_.high();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000985 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
986}
987
988
989#ifdef DEBUG
990// We do not use the SemispaceIterator because verification doesn't assume
991// that it works (it depends on the invariants we are checking).
992void NewSpace::Verify() {
993 // The allocation pointer should be in the space or at the very end.
994 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
995
996 // There should be objects packed in from the low address up to the
997 // allocation pointer.
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000998 Address current = to_space_.low();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000999 while (current < top()) {
1000 HeapObject* object = HeapObject::FromAddress(current);
1001
1002 // The first word should be a map, and we expect all map pointers to
1003 // be in map space.
1004 Map* map = object->map();
1005 ASSERT(map->IsMap());
1006 ASSERT(Heap::map_space()->Contains(map));
1007
1008 // The object should not be code or a map.
1009 ASSERT(!object->IsMap());
1010 ASSERT(!object->IsCode());
1011
1012 // The object itself should look OK.
1013 object->Verify();
1014
1015 // All the interior pointers should be contained in the heap.
1016 VerifyPointersVisitor visitor;
1017 int size = object->Size();
1018 object->IterateBody(map->instance_type(), size, &visitor);
1019
1020 current += size;
1021 }
1022
1023 // The allocation pointer should not be in the middle of an object.
1024 ASSERT(current == top());
1025}
1026#endif
1027
1028
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001029bool SemiSpace::Commit() {
1030 ASSERT(!is_committed());
1031 if (!MemoryAllocator::CommitBlock(start_, capacity_, executable())) {
1032 return false;
1033 }
1034 committed_ = true;
1035 return true;
1036}
1037
1038
1039bool SemiSpace::Uncommit() {
1040 ASSERT(is_committed());
1041 if (!MemoryAllocator::UncommitBlock(start_, capacity_)) {
1042 return false;
1043 }
1044 committed_ = false;
1045 return true;
1046}
1047
1048
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001049// -----------------------------------------------------------------------------
1050// SemiSpace implementation
1051
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001052bool SemiSpace::Setup(Address start,
1053 int initial_capacity,
1054 int maximum_capacity) {
1055 // Creates a space in the young generation. The constructor does not
1056 // allocate memory from the OS. A SemiSpace is given a contiguous chunk of
1057 // memory of size 'capacity' when set up, and does not grow or shrink
1058 // otherwise. In the mark-compact collector, the memory region of the from
1059 // space is used as the marking stack. It requires contiguous memory
1060 // addresses.
1061 capacity_ = initial_capacity;
1062 maximum_capacity_ = maximum_capacity;
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001063 committed_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001064
1065 start_ = start;
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001066 address_mask_ = ~(maximum_capacity - 1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067 object_mask_ = address_mask_ | kHeapObjectTag;
ager@chromium.org9085a012009-05-11 19:22:57 +00001068 object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001069 age_mark_ = start_;
ager@chromium.orgadd848f2009-08-13 12:44:13 +00001070
1071 return Commit();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001072}
1073
1074
1075void SemiSpace::TearDown() {
1076 start_ = NULL;
1077 capacity_ = 0;
1078}
1079
1080
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001081bool SemiSpace::Grow() {
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001082 // Double the semispace size but only up to maximum capacity.
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001083 int maximum_extra = maximum_capacity_ - capacity_;
sgjesse@chromium.orgc81c8942009-08-21 10:54:26 +00001084 int extra = Min(RoundUp(capacity_, OS::AllocateAlignment()),
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001085 maximum_extra);
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001086 if (!MemoryAllocator::CommitBlock(high(), extra, executable())) {
kasper.lund7276f142008-07-30 08:49:36 +00001087 return false;
1088 }
christian.plesner.hansen@gmail.com5a6af922009-08-12 14:20:51 +00001089 capacity_ += extra;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001090 return true;
1091}
1092
1093
1094#ifdef DEBUG
1095void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001096
1097
1098void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001099#endif
1100
1101
1102// -----------------------------------------------------------------------------
1103// SemiSpaceIterator implementation.
1104SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
1105 Initialize(space, space->bottom(), space->top(), NULL);
1106}
1107
1108
1109SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
1110 HeapObjectCallback size_func) {
1111 Initialize(space, space->bottom(), space->top(), size_func);
1112}
1113
1114
1115SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
1116 Initialize(space, start, space->top(), NULL);
1117}
1118
1119
1120void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
1121 Address end,
1122 HeapObjectCallback size_func) {
1123 ASSERT(space->ToSpaceContains(start));
1124 ASSERT(space->ToSpaceLow() <= end
1125 && end <= space->ToSpaceHigh());
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +00001126 space_ = &space->to_space_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001127 current_ = start;
1128 limit_ = end;
1129 size_func_ = size_func;
1130}
1131
1132
1133#ifdef DEBUG
1134// A static array of histogram info for each type.
1135static HistogramInfo heap_histograms[LAST_TYPE+1];
1136static JSObject::SpillInformation js_spill_information;
1137
1138// heap_histograms is shared, always clear it before using it.
1139static void ClearHistograms() {
1140 // We reset the name each time, though it hasn't changed.
1141#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1142 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1143#undef DEF_TYPE_NAME
1144
1145#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1146 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1147#undef CLEAR_HISTOGRAM
1148
1149 js_spill_information.Clear();
1150}
1151
1152
1153static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1154
1155
1156static void ClearCodeKindStatistics() {
1157 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1158 code_kind_statistics[i] = 0;
1159 }
1160}
1161
1162
1163static void ReportCodeKindStatistics() {
1164 const char* table[Code::NUMBER_OF_KINDS];
1165
1166#define CASE(name) \
1167 case Code::name: table[Code::name] = #name; \
1168 break
1169
1170 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1171 switch (static_cast<Code::Kind>(i)) {
1172 CASE(FUNCTION);
1173 CASE(STUB);
1174 CASE(BUILTIN);
1175 CASE(LOAD_IC);
1176 CASE(KEYED_LOAD_IC);
1177 CASE(STORE_IC);
1178 CASE(KEYED_STORE_IC);
1179 CASE(CALL_IC);
1180 }
1181 }
1182
1183#undef CASE
1184
1185 PrintF("\n Code kind histograms: \n");
1186 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1187 if (code_kind_statistics[i] > 0) {
1188 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1189 }
1190 }
1191 PrintF("\n");
1192}
1193
1194
1195static int CollectHistogramInfo(HeapObject* obj) {
1196 InstanceType type = obj->map()->instance_type();
1197 ASSERT(0 <= type && type <= LAST_TYPE);
1198 ASSERT(heap_histograms[type].name() != NULL);
1199 heap_histograms[type].increment_number(1);
1200 heap_histograms[type].increment_bytes(obj->Size());
1201
1202 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1203 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1204 }
1205
1206 return obj->Size();
1207}
1208
1209
1210static void ReportHistogram(bool print_spill) {
1211 PrintF("\n Object Histogram:\n");
1212 for (int i = 0; i <= LAST_TYPE; i++) {
1213 if (heap_histograms[i].number() > 0) {
1214 PrintF(" %-33s%10d (%10d bytes)\n",
1215 heap_histograms[i].name(),
1216 heap_histograms[i].number(),
1217 heap_histograms[i].bytes());
1218 }
1219 }
1220 PrintF("\n");
1221
1222 // Summarize string types.
1223 int string_number = 0;
1224 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001225#define INCREMENT(type, size, name, camel_name) \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001226 string_number += heap_histograms[type].number(); \
1227 string_bytes += heap_histograms[type].bytes();
1228 STRING_TYPE_LIST(INCREMENT)
1229#undef INCREMENT
1230 if (string_number > 0) {
1231 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1232 string_bytes);
1233 }
1234
1235 if (FLAG_collect_heap_spill_statistics && print_spill) {
1236 js_spill_information.Print();
1237 }
1238}
1239#endif // DEBUG
1240
1241
1242// Support for statistics gathering for --heap-stats and --log-gc.
1243#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1244void NewSpace::ClearHistograms() {
1245 for (int i = 0; i <= LAST_TYPE; i++) {
1246 allocated_histogram_[i].clear();
1247 promoted_histogram_[i].clear();
1248 }
1249}
1250
1251// Because the copying collector does not touch garbage objects, we iterate
1252// the new space before a collection to get a histogram of allocated objects.
1253// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1254// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1255// flag is set.
1256void NewSpace::CollectStatistics() {
1257 ClearHistograms();
1258 SemiSpaceIterator it(this);
1259 while (it.has_next()) RecordAllocation(it.next());
1260}
1261
1262
1263#ifdef ENABLE_LOGGING_AND_PROFILING
1264static void DoReportStatistics(HistogramInfo* info, const char* description) {
1265 LOG(HeapSampleBeginEvent("NewSpace", description));
1266 // Lump all the string types together.
1267 int string_number = 0;
1268 int string_bytes = 0;
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001269#define INCREMENT(type, size, name, camel_name) \
1270 string_number += info[type].number(); \
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001271 string_bytes += info[type].bytes();
1272 STRING_TYPE_LIST(INCREMENT)
1273#undef INCREMENT
1274 if (string_number > 0) {
1275 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1276 }
1277
1278 // Then do the other types.
1279 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1280 if (info[i].number() > 0) {
1281 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1282 info[i].bytes()));
1283 }
1284 }
1285 LOG(HeapSampleEndEvent("NewSpace", description));
1286}
1287#endif // ENABLE_LOGGING_AND_PROFILING
1288
1289
1290void NewSpace::ReportStatistics() {
1291#ifdef DEBUG
1292 if (FLAG_heap_stats) {
1293 float pct = static_cast<float>(Available()) / Capacity();
1294 PrintF(" capacity: %d, available: %d, %%%d\n",
1295 Capacity(), Available(), static_cast<int>(pct*100));
1296 PrintF("\n Object Histogram:\n");
1297 for (int i = 0; i <= LAST_TYPE; i++) {
1298 if (allocated_histogram_[i].number() > 0) {
1299 PrintF(" %-33s%10d (%10d bytes)\n",
1300 allocated_histogram_[i].name(),
1301 allocated_histogram_[i].number(),
1302 allocated_histogram_[i].bytes());
1303 }
1304 }
1305 PrintF("\n");
1306 }
1307#endif // DEBUG
1308
1309#ifdef ENABLE_LOGGING_AND_PROFILING
1310 if (FLAG_log_gc) {
1311 DoReportStatistics(allocated_histogram_, "allocated");
1312 DoReportStatistics(promoted_histogram_, "promoted");
1313 }
1314#endif // ENABLE_LOGGING_AND_PROFILING
1315}
1316
1317
1318void NewSpace::RecordAllocation(HeapObject* obj) {
1319 InstanceType type = obj->map()->instance_type();
1320 ASSERT(0 <= type && type <= LAST_TYPE);
1321 allocated_histogram_[type].increment_number(1);
1322 allocated_histogram_[type].increment_bytes(obj->Size());
1323}
1324
1325
1326void NewSpace::RecordPromotion(HeapObject* obj) {
1327 InstanceType type = obj->map()->instance_type();
1328 ASSERT(0 <= type && type <= LAST_TYPE);
1329 promoted_histogram_[type].increment_number(1);
1330 promoted_histogram_[type].increment_bytes(obj->Size());
1331}
1332#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1333
1334
1335// -----------------------------------------------------------------------------
1336// Free lists for old object spaces implementation
1337
1338void FreeListNode::set_size(int size_in_bytes) {
1339 ASSERT(size_in_bytes > 0);
1340 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1341
1342 // We write a map and possibly size information to the block. If the block
1343 // is big enough to be a ByteArray with at least one extra word (the next
1344 // pointer), we set its map to be the byte array map and its size to an
1345 // appropriate array length for the desired size from HeapObject::Size().
1346 // If the block is too small (eg, one or two words), to hold both a size
1347 // field and a next pointer, we give it a filler map that gives it the
1348 // correct size.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001349 if (size_in_bytes > ByteArray::kAlignedSize) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001350 set_map(Heap::raw_unchecked_byte_array_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001351 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1352 } else if (size_in_bytes == kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001353 set_map(Heap::raw_unchecked_one_pointer_filler_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001354 } else if (size_in_bytes == 2 * kPointerSize) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001355 set_map(Heap::raw_unchecked_two_pointer_filler_map());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001356 } else {
1357 UNREACHABLE();
1358 }
kasper.lund7276f142008-07-30 08:49:36 +00001359 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360}
1361
1362
1363Address FreeListNode::next() {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001364 ASSERT(map() == Heap::raw_unchecked_byte_array_map() ||
1365 map() == Heap::raw_unchecked_two_pointer_filler_map());
1366 if (map() == Heap::raw_unchecked_byte_array_map()) {
1367 ASSERT(Size() >= kNextOffset + kPointerSize);
1368 return Memory::Address_at(address() + kNextOffset);
1369 } else {
1370 return Memory::Address_at(address() + kPointerSize);
1371 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001372}
1373
1374
1375void FreeListNode::set_next(Address next) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001376 ASSERT(map() == Heap::raw_unchecked_byte_array_map() ||
1377 map() == Heap::raw_unchecked_two_pointer_filler_map());
1378 if (map() == Heap::raw_unchecked_byte_array_map()) {
1379 ASSERT(Size() >= kNextOffset + kPointerSize);
1380 Memory::Address_at(address() + kNextOffset) = next;
1381 } else {
1382 Memory::Address_at(address() + kPointerSize) = next;
1383 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001384}
1385
1386
1387OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1388 Reset();
1389}
1390
1391
1392void OldSpaceFreeList::Reset() {
1393 available_ = 0;
1394 for (int i = 0; i < kFreeListsLength; i++) {
1395 free_[i].head_node_ = NULL;
1396 }
1397 needs_rebuild_ = false;
1398 finger_ = kHead;
1399 free_[kHead].next_size_ = kEnd;
1400}
1401
1402
1403void OldSpaceFreeList::RebuildSizeList() {
1404 ASSERT(needs_rebuild_);
1405 int cur = kHead;
1406 for (int i = cur + 1; i < kFreeListsLength; i++) {
1407 if (free_[i].head_node_ != NULL) {
1408 free_[cur].next_size_ = i;
1409 cur = i;
1410 }
1411 }
1412 free_[cur].next_size_ = kEnd;
1413 needs_rebuild_ = false;
1414}
1415
1416
1417int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1418#ifdef DEBUG
1419 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1420 Memory::Address_at(start + i) = kZapValue;
1421 }
1422#endif
1423 FreeListNode* node = FreeListNode::FromAddress(start);
1424 node->set_size(size_in_bytes);
1425
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001426 // We don't use the freelists in compacting mode. This makes it more like a
1427 // GC that only has mark-sweep-compact and doesn't have a mark-sweep
1428 // collector.
1429 if (FLAG_always_compact) {
1430 return size_in_bytes;
1431 }
1432
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001433 // Early return to drop too-small blocks on the floor (one or two word
1434 // blocks cannot hold a map pointer, a size field, and a pointer to the
1435 // next block in the free list).
1436 if (size_in_bytes < kMinBlockSize) {
1437 return size_in_bytes;
1438 }
1439
1440 // Insert other blocks at the head of an exact free list.
1441 int index = size_in_bytes >> kPointerSizeLog2;
1442 node->set_next(free_[index].head_node_);
1443 free_[index].head_node_ = node->address();
1444 available_ += size_in_bytes;
1445 needs_rebuild_ = true;
1446 return 0;
1447}
1448
1449
1450Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1451 ASSERT(0 < size_in_bytes);
1452 ASSERT(size_in_bytes <= kMaxBlockSize);
1453 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1454
1455 if (needs_rebuild_) RebuildSizeList();
1456 int index = size_in_bytes >> kPointerSizeLog2;
1457 // Check for a perfect fit.
1458 if (free_[index].head_node_ != NULL) {
1459 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1460 // If this was the last block of its size, remove the size.
1461 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1462 available_ -= size_in_bytes;
1463 *wasted_bytes = 0;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001464 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001465 return node;
1466 }
1467 // Search the size list for the best fit.
1468 int prev = finger_ < index ? finger_ : kHead;
1469 int cur = FindSize(index, &prev);
1470 ASSERT(index < cur);
1471 if (cur == kEnd) {
1472 // No large enough size in list.
1473 *wasted_bytes = 0;
1474 return Failure::RetryAfterGC(size_in_bytes, owner_);
1475 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001476 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001477 int rem = cur - index;
1478 int rem_bytes = rem << kPointerSizeLog2;
1479 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001480 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001481 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1482 size_in_bytes);
1483 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1484 // to avoid many redundant tests and calls to Insert/RemoveSize.
1485 if (prev < rem) {
1486 // Simple case: insert rem between prev and cur.
1487 finger_ = prev;
1488 free_[prev].next_size_ = rem;
1489 // If this was the last block of size cur, remove the size.
1490 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1491 free_[rem].next_size_ = free_[cur].next_size_;
1492 } else {
1493 free_[rem].next_size_ = cur;
1494 }
1495 // Add the remainder block.
1496 rem_node->set_size(rem_bytes);
1497 rem_node->set_next(free_[rem].head_node_);
1498 free_[rem].head_node_ = rem_node->address();
1499 } else {
1500 // If this was the last block of size cur, remove the size.
1501 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1502 finger_ = prev;
1503 free_[prev].next_size_ = free_[cur].next_size_;
1504 }
1505 if (rem_bytes < kMinBlockSize) {
1506 // Too-small remainder is wasted.
1507 rem_node->set_size(rem_bytes);
1508 available_ -= size_in_bytes + rem_bytes;
1509 *wasted_bytes = rem_bytes;
1510 return cur_node;
1511 }
1512 // Add the remainder block and, if needed, insert its size.
1513 rem_node->set_size(rem_bytes);
1514 rem_node->set_next(free_[rem].head_node_);
1515 free_[rem].head_node_ = rem_node->address();
1516 if (rem_node->next() == NULL) InsertSize(rem);
1517 }
1518 available_ -= size_in_bytes;
1519 *wasted_bytes = 0;
1520 return cur_node;
1521}
1522
1523
kasper.lund7276f142008-07-30 08:49:36 +00001524#ifdef DEBUG
1525bool OldSpaceFreeList::Contains(FreeListNode* node) {
1526 for (int i = 0; i < kFreeListsLength; i++) {
1527 Address cur_addr = free_[i].head_node_;
1528 while (cur_addr != NULL) {
1529 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1530 if (cur_node == node) return true;
1531 cur_addr = cur_node->next();
1532 }
1533 }
1534 return false;
1535}
1536#endif
1537
1538
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001539FixedSizeFreeList::FixedSizeFreeList(AllocationSpace owner, int object_size)
1540 : owner_(owner), object_size_(object_size) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001541 Reset();
1542}
1543
1544
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001545void FixedSizeFreeList::Reset() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001546 available_ = 0;
1547 head_ = NULL;
1548}
1549
1550
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001551void FixedSizeFreeList::Free(Address start) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001552#ifdef DEBUG
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001553 for (int i = 0; i < object_size_; i += kPointerSize) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554 Memory::Address_at(start + i) = kZapValue;
1555 }
1556#endif
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001557 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001558 FreeListNode* node = FreeListNode::FromAddress(start);
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001559 node->set_size(object_size_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001560 node->set_next(head_);
1561 head_ = node->address();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001562 available_ += object_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001563}
1564
1565
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001566Object* FixedSizeFreeList::Allocate() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001567 if (head_ == NULL) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001568 return Failure::RetryAfterGC(object_size_, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001569 }
1570
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001571 ASSERT(!FLAG_always_compact); // We only use the freelists with mark-sweep.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001572 FreeListNode* node = FreeListNode::FromAddress(head_);
1573 head_ = node->next();
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001574 available_ -= object_size_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001575 return node;
1576}
1577
1578
1579// -----------------------------------------------------------------------------
1580// OldSpace implementation
1581
1582void OldSpace::PrepareForMarkCompact(bool will_compact) {
1583 if (will_compact) {
1584 // Reset relocation info. During a compacting collection, everything in
1585 // the space is considered 'available' and we will rediscover live data
1586 // and waste during the collection.
1587 MCResetRelocationInfo();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001588 ASSERT(Available() == Capacity());
1589 } else {
1590 // During a non-compacting collection, everything below the linear
1591 // allocation pointer is considered allocated (everything above is
1592 // available) and we will rediscover available and wasted bytes during
1593 // the collection.
1594 accounting_stats_.AllocateBytes(free_list_.available());
1595 accounting_stats_.FillWastedBytes(Waste());
1596 }
1597
kasper.lund7276f142008-07-30 08:49:36 +00001598 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001599 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001600}
1601
1602
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001603void OldSpace::MCCommitRelocationInfo() {
1604 // Update fast allocation info.
1605 allocation_info_.top = mc_forwarding_info_.top;
1606 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001607 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608
1609 // The space is compacted and we haven't yet built free lists or
1610 // wasted any space.
1611 ASSERT(Waste() == 0);
1612 ASSERT(AvailableFree() == 0);
1613
1614 // Build the free list for the space.
1615 int computed_size = 0;
1616 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1617 while (it.has_next()) {
1618 Page* p = it.next();
1619 // Space below the relocation pointer is allocated.
1620 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1621 if (it.has_next()) {
1622 // Free the space at the top of the page. We cannot use
1623 // p->mc_relocation_top after the call to Free (because Free will clear
1624 // remembered set bits).
1625 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1626 if (extra_size > 0) {
1627 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1628 // The bytes we have just "freed" to add to the free list were
1629 // already accounted as available.
1630 accounting_stats_.WasteBytes(wasted_bytes);
1631 }
1632 }
1633 }
1634
1635 // Make sure the computed size - based on the used portion of the pages in
1636 // use - matches the size obtained while computing forwarding addresses.
1637 ASSERT(computed_size == Size());
1638}
1639
1640
kasper.lund7276f142008-07-30 08:49:36 +00001641// Slow case for normal allocation. Try in order: (1) allocate in the next
1642// page in the space, (2) allocate off the space's free list, (3) expand the
1643// space, (4) fail.
1644HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1645 // Linear allocation in this space has failed. If there is another page
1646 // in the space, move to that page and allocate there. This allocation
1647 // should succeed (size_in_bytes should not be greater than a page's
1648 // object area size).
1649 Page* current_page = TopPageOf(allocation_info_);
1650 if (current_page->next_page()->is_valid()) {
1651 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001652 }
kasper.lund7276f142008-07-30 08:49:36 +00001653
1654 // There is no next page in this space. Try free list allocation.
1655 int wasted_bytes;
1656 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1657 accounting_stats_.WasteBytes(wasted_bytes);
1658 if (!result->IsFailure()) {
1659 accounting_stats_.AllocateBytes(size_in_bytes);
1660 return HeapObject::cast(result);
1661 }
1662
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00001663 // Free list allocation failed and there is no next page. Fail if we have
1664 // hit the old generation size limit that should cause a garbage
1665 // collection.
1666 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
1667 return NULL;
1668 }
1669
1670 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00001671 ASSERT(!current_page->next_page()->is_valid());
1672 if (Expand(current_page)) {
1673 return AllocateInNextPage(current_page, size_in_bytes);
1674 }
1675
1676 // Finally, fail.
1677 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001678}
1679
1680
kasper.lund7276f142008-07-30 08:49:36 +00001681// Add the block at the top of the page to the space's free list, set the
1682// allocation info to the next page (assumed to be one), and allocate
1683// linearly there.
1684HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1685 int size_in_bytes) {
1686 ASSERT(current_page->next_page()->is_valid());
1687 // Add the block at the top of this page to the free list.
1688 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1689 if (free_size > 0) {
1690 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1691 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001692 }
kasper.lund7276f142008-07-30 08:49:36 +00001693 SetAllocationInfo(&allocation_info_, current_page->next_page());
1694 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001695}
1696
1697
1698#ifdef DEBUG
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001699struct CommentStatistic {
1700 const char* comment;
1701 int size;
1702 int count;
1703 void Clear() {
1704 comment = NULL;
1705 size = 0;
1706 count = 0;
1707 }
1708};
1709
1710
1711// must be small, since an iteration is used for lookup
1712const int kMaxComments = 64;
1713static CommentStatistic comments_statistics[kMaxComments+1];
1714
1715
1716void PagedSpace::ReportCodeStatistics() {
1717 ReportCodeKindStatistics();
1718 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1719 "count (average)\"):\n");
1720 for (int i = 0; i <= kMaxComments; i++) {
1721 const CommentStatistic& cs = comments_statistics[i];
1722 if (cs.size > 0) {
1723 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1724 cs.size/cs.count);
1725 }
1726 }
1727 PrintF("\n");
1728}
1729
1730
1731void PagedSpace::ResetCodeStatistics() {
1732 ClearCodeKindStatistics();
1733 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1734 comments_statistics[kMaxComments].comment = "Unknown";
1735 comments_statistics[kMaxComments].size = 0;
1736 comments_statistics[kMaxComments].count = 0;
1737}
1738
1739
1740// Adds comment to 'comment_statistics' table. Performance OK sa long as
1741// 'kMaxComments' is small
1742static void EnterComment(const char* comment, int delta) {
1743 // Do not count empty comments
1744 if (delta <= 0) return;
1745 CommentStatistic* cs = &comments_statistics[kMaxComments];
1746 // Search for a free or matching entry in 'comments_statistics': 'cs'
1747 // points to result.
1748 for (int i = 0; i < kMaxComments; i++) {
1749 if (comments_statistics[i].comment == NULL) {
1750 cs = &comments_statistics[i];
1751 cs->comment = comment;
1752 break;
1753 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1754 cs = &comments_statistics[i];
1755 break;
1756 }
1757 }
1758 // Update entry for 'comment'
1759 cs->size += delta;
1760 cs->count += 1;
1761}
1762
1763
1764// Call for each nested comment start (start marked with '[ xxx', end marked
1765// with ']'. RelocIterator 'it' must point to a comment reloc info.
1766static void CollectCommentStatistics(RelocIterator* it) {
1767 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001768 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001769 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1770 if (tmp[0] != '[') {
1771 // Not a nested comment; skip
1772 return;
1773 }
1774
1775 // Search for end of nested comment or a new nested comment
1776 const char* const comment_txt =
1777 reinterpret_cast<const char*>(it->rinfo()->data());
1778 const byte* prev_pc = it->rinfo()->pc();
1779 int flat_delta = 0;
1780 it->next();
1781 while (true) {
1782 // All nested comments must be terminated properly, and therefore exit
1783 // from loop.
1784 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001785 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001786 const char* const txt =
1787 reinterpret_cast<const char*>(it->rinfo()->data());
1788 flat_delta += it->rinfo()->pc() - prev_pc;
1789 if (txt[0] == ']') break; // End of nested comment
1790 // A new comment
1791 CollectCommentStatistics(it);
1792 // Skip code that was covered with previous comment
1793 prev_pc = it->rinfo()->pc();
1794 }
1795 it->next();
1796 }
1797 EnterComment(comment_txt, flat_delta);
1798}
1799
1800
1801// Collects code size statistics:
1802// - by code kind
1803// - by code comment
1804void PagedSpace::CollectCodeStatistics() {
1805 HeapObjectIterator obj_it(this);
1806 while (obj_it.has_next()) {
1807 HeapObject* obj = obj_it.next();
1808 if (obj->IsCode()) {
1809 Code* code = Code::cast(obj);
1810 code_kind_statistics[code->kind()] += code->Size();
1811 RelocIterator it(code);
1812 int delta = 0;
1813 const byte* prev_pc = code->instruction_start();
1814 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001815 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001816 delta += it.rinfo()->pc() - prev_pc;
1817 CollectCommentStatistics(&it);
1818 prev_pc = it.rinfo()->pc();
1819 }
1820 it.next();
1821 }
1822
1823 ASSERT(code->instruction_start() <= prev_pc &&
1824 prev_pc <= code->relocation_start());
1825 delta += code->relocation_start() - prev_pc;
1826 EnterComment("NoComment", delta);
1827 }
1828 }
1829}
1830
1831
1832void OldSpace::ReportStatistics() {
1833 int pct = Available() * 100 / Capacity();
1834 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1835 Capacity(), Waste(), Available(), pct);
1836
1837 // Report remembered set statistics.
1838 int rset_marked_pointers = 0;
1839 int rset_marked_arrays = 0;
1840 int rset_marked_array_elements = 0;
1841 int cross_gen_pointers = 0;
1842 int cross_gen_array_elements = 0;
1843
1844 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1845 while (page_it.has_next()) {
1846 Page* p = page_it.next();
1847
1848 for (Address rset_addr = p->RSetStart();
1849 rset_addr < p->RSetEnd();
1850 rset_addr += kIntSize) {
1851 int rset = Memory::int_at(rset_addr);
1852 if (rset != 0) {
1853 // Bits were set
1854 int intoff = rset_addr - p->address();
1855 int bitoff = 0;
1856 for (; bitoff < kBitsPerInt; ++bitoff) {
1857 if ((rset & (1 << bitoff)) != 0) {
1858 int bitpos = intoff*kBitsPerByte + bitoff;
1859 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1860 Object** obj = reinterpret_cast<Object**>(slot);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +00001861 if (*obj == Heap::raw_unchecked_fixed_array_map()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001862 rset_marked_arrays++;
1863 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1864
1865 rset_marked_array_elements += fa->length();
1866 // Manually inline FixedArray::IterateBody
1867 Address elm_start = slot + FixedArray::kHeaderSize;
1868 Address elm_stop = elm_start + fa->length() * kPointerSize;
1869 for (Address elm_addr = elm_start;
1870 elm_addr < elm_stop; elm_addr += kPointerSize) {
1871 // Filter non-heap-object pointers
1872 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1873 if (Heap::InNewSpace(*elm_p))
1874 cross_gen_array_elements++;
1875 }
1876 } else {
1877 rset_marked_pointers++;
1878 if (Heap::InNewSpace(*obj))
1879 cross_gen_pointers++;
1880 }
1881 }
1882 }
1883 }
1884 }
1885 }
1886
1887 pct = rset_marked_pointers == 0 ?
1888 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1889 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1890 rset_marked_pointers, cross_gen_pointers, pct);
1891 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1892 PrintF(" elements %d, ", rset_marked_array_elements);
1893 pct = rset_marked_array_elements == 0 ? 0
1894 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1895 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1896 PrintF(" total rset-marked bits %d\n",
1897 (rset_marked_pointers + rset_marked_arrays));
1898 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1899 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1900 (rset_marked_pointers + rset_marked_array_elements);
1901 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1902 (rset_marked_pointers + rset_marked_array_elements),
1903 (cross_gen_pointers + cross_gen_array_elements),
1904 pct);
1905
1906 ClearHistograms();
1907 HeapObjectIterator obj_it(this);
1908 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1909 ReportHistogram(true);
1910}
1911
1912
1913// Dump the range of remembered set words between [start, end) corresponding
1914// to the pointers starting at object_p. The allocation_top is an object
1915// pointer which should not be read past. This is important for large object
1916// pages, where some bits in the remembered set range do not correspond to
1917// allocated addresses.
1918static void PrintRSetRange(Address start, Address end, Object** object_p,
1919 Address allocation_top) {
1920 Address rset_address = start;
1921
1922 // If the range starts on on odd numbered word (eg, for large object extra
1923 // remembered set ranges), print some spaces.
ager@chromium.org9085a012009-05-11 19:22:57 +00001924 if ((reinterpret_cast<uintptr_t>(start) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001925 PrintF(" ");
1926 }
1927
1928 // Loop over all the words in the range.
1929 while (rset_address < end) {
1930 uint32_t rset_word = Memory::uint32_at(rset_address);
1931 int bit_position = 0;
1932
1933 // Loop over all the bits in the word.
1934 while (bit_position < kBitsPerInt) {
1935 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1936 // Print a bar at the allocation pointer.
1937 PrintF("|");
1938 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1939 // Do not dereference object_p past the allocation pointer.
1940 PrintF("#");
1941 } else if ((rset_word & (1 << bit_position)) == 0) {
1942 // Print a dot for zero bits.
1943 PrintF(".");
1944 } else if (Heap::InNewSpace(*object_p)) {
1945 // Print an X for one bits for pointers to new space.
1946 PrintF("X");
1947 } else {
1948 // Print a circle for one bits for pointers to old space.
1949 PrintF("o");
1950 }
1951
1952 // Print a space after every 8th bit except the last.
1953 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1954 PrintF(" ");
1955 }
1956
1957 // Advance to next bit.
1958 bit_position++;
1959 object_p++;
1960 }
1961
1962 // Print a newline after every odd numbered word, otherwise a space.
ager@chromium.org9085a012009-05-11 19:22:57 +00001963 if ((reinterpret_cast<uintptr_t>(rset_address) / kIntSize) % 2 == 1) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001964 PrintF("\n");
1965 } else {
1966 PrintF(" ");
1967 }
1968
1969 // Advance to next remembered set word.
1970 rset_address += kIntSize;
1971 }
1972}
1973
1974
1975void PagedSpace::DoPrintRSet(const char* space_name) {
1976 PageIterator it(this, PageIterator::PAGES_IN_USE);
1977 while (it.has_next()) {
1978 Page* p = it.next();
1979 PrintF("%s page 0x%x:\n", space_name, p);
1980 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
1981 reinterpret_cast<Object**>(p->ObjectAreaStart()),
1982 p->AllocationTop());
1983 PrintF("\n");
1984 }
1985}
1986
1987
1988void OldSpace::PrintRSet() { DoPrintRSet("old"); }
1989#endif
1990
1991// -----------------------------------------------------------------------------
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001992// FixedSpace implementation
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001993
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001994void FixedSpace::PrepareForMarkCompact(bool will_compact) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001995 if (will_compact) {
1996 // Reset relocation info.
1997 MCResetRelocationInfo();
1998
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001999 // During a compacting collection, everything in the space is considered
2000 // 'available' (set by the call to MCResetRelocationInfo) and we will
2001 // rediscover live and wasted bytes during the collection.
2002 ASSERT(Available() == Capacity());
2003 } else {
2004 // During a non-compacting collection, everything below the linear
2005 // allocation pointer except wasted top-of-page blocks is considered
2006 // allocated and we will rediscover available bytes during the
2007 // collection.
2008 accounting_stats_.AllocateBytes(free_list_.available());
2009 }
2010
kasper.lund7276f142008-07-30 08:49:36 +00002011 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002012 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002013}
2014
2015
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002016void FixedSpace::MCCommitRelocationInfo() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002017 // Update fast allocation info.
2018 allocation_info_.top = mc_forwarding_info_.top;
2019 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00002020 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002021
2022 // The space is compacted and we haven't yet wasted any space.
2023 ASSERT(Waste() == 0);
2024
2025 // Update allocation_top of each page in use and compute waste.
2026 int computed_size = 0;
2027 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
2028 while (it.has_next()) {
2029 Page* page = it.next();
2030 Address page_top = page->AllocationTop();
2031 computed_size += page_top - page->ObjectAreaStart();
2032 if (it.has_next()) {
2033 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
2034 }
2035 }
2036
2037 // Make sure the computed size - based on the used portion of the
2038 // pages in use - matches the size we adjust during allocation.
2039 ASSERT(computed_size == Size());
2040}
2041
2042
kasper.lund7276f142008-07-30 08:49:36 +00002043// Slow case for normal allocation. Try in order: (1) allocate in the next
2044// page in the space, (2) allocate off the space's free list, (3) expand the
2045// space, (4) fail.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002046HeapObject* FixedSpace::SlowAllocateRaw(int size_in_bytes) {
2047 ASSERT_EQ(object_size_in_bytes_, size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002048 // Linear allocation in this space has failed. If there is another page
2049 // in the space, move to that page and allocate there. This allocation
2050 // should succeed.
2051 Page* current_page = TopPageOf(allocation_info_);
2052 if (current_page->next_page()->is_valid()) {
2053 return AllocateInNextPage(current_page, size_in_bytes);
2054 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002055
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002056 // There is no next page in this space. Try free list allocation.
2057 // The fixed space free list implicitly assumes that all free blocks
2058 // are of the fixed size.
2059 if (size_in_bytes == object_size_in_bytes_) {
kasper.lund7276f142008-07-30 08:49:36 +00002060 Object* result = free_list_.Allocate();
2061 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002062 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002063 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002064 }
2065 }
kasper.lund7276f142008-07-30 08:49:36 +00002066
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002067 // Free list allocation failed and there is no next page. Fail if we have
2068 // hit the old generation size limit that should cause a garbage
2069 // collection.
2070 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2071 return NULL;
2072 }
2073
2074 // Try to expand the space and allocate in the new next page.
kasper.lund7276f142008-07-30 08:49:36 +00002075 ASSERT(!current_page->next_page()->is_valid());
2076 if (Expand(current_page)) {
2077 return AllocateInNextPage(current_page, size_in_bytes);
2078 }
2079
2080 // Finally, fail.
2081 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002082}
2083
2084
kasper.lund7276f142008-07-30 08:49:36 +00002085// Move to the next page (there is assumed to be one) and allocate there.
2086// The top of page block is always wasted, because it is too small to hold a
2087// map.
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002088HeapObject* FixedSpace::AllocateInNextPage(Page* current_page,
2089 int size_in_bytes) {
kasper.lund7276f142008-07-30 08:49:36 +00002090 ASSERT(current_page->next_page()->is_valid());
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002091 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == page_extra_);
2092 ASSERT_EQ(object_size_in_bytes_, size_in_bytes);
2093 accounting_stats_.WasteBytes(page_extra_);
kasper.lund7276f142008-07-30 08:49:36 +00002094 SetAllocationInfo(&allocation_info_, current_page->next_page());
2095 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002096}
2097
2098
2099#ifdef DEBUG
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002100void FixedSpace::ReportStatistics() {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002101 int pct = Available() * 100 / Capacity();
2102 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2103 Capacity(), Waste(), Available(), pct);
2104
2105 // Report remembered set statistics.
2106 int rset_marked_pointers = 0;
2107 int cross_gen_pointers = 0;
2108
2109 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2110 while (page_it.has_next()) {
2111 Page* p = page_it.next();
2112
2113 for (Address rset_addr = p->RSetStart();
2114 rset_addr < p->RSetEnd();
2115 rset_addr += kIntSize) {
2116 int rset = Memory::int_at(rset_addr);
2117 if (rset != 0) {
2118 // Bits were set
2119 int intoff = rset_addr - p->address();
2120 int bitoff = 0;
2121 for (; bitoff < kBitsPerInt; ++bitoff) {
2122 if ((rset & (1 << bitoff)) != 0) {
2123 int bitpos = intoff*kBitsPerByte + bitoff;
2124 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2125 Object** obj = reinterpret_cast<Object**>(slot);
2126 rset_marked_pointers++;
2127 if (Heap::InNewSpace(*obj))
2128 cross_gen_pointers++;
2129 }
2130 }
2131 }
2132 }
2133 }
2134
2135 pct = rset_marked_pointers == 0 ?
2136 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2137 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2138 rset_marked_pointers, cross_gen_pointers, pct);
2139
2140 ClearHistograms();
2141 HeapObjectIterator obj_it(this);
2142 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2143 ReportHistogram(false);
2144}
2145
2146
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00002147void FixedSpace::PrintRSet() { DoPrintRSet(name_); }
2148#endif
2149
2150
2151// -----------------------------------------------------------------------------
2152// MapSpace implementation
2153
2154void MapSpace::PrepareForMarkCompact(bool will_compact) {
2155 // Call prepare of the super class.
2156 FixedSpace::PrepareForMarkCompact(will_compact);
2157
2158 if (will_compact) {
2159 // Initialize map index entry.
2160 int page_count = 0;
2161 PageIterator it(this, PageIterator::ALL_PAGES);
2162 while (it.has_next()) {
2163 ASSERT_MAP_PAGE_INDEX(page_count);
2164
2165 Page* p = it.next();
2166 ASSERT(p->mc_page_index == page_count);
2167
2168 page_addresses_[page_count++] = p->address();
2169 }
2170 }
2171}
2172
2173
2174#ifdef DEBUG
2175void MapSpace::VerifyObject(HeapObject* object) {
2176 // The object should be a map or a free-list node.
2177 ASSERT(object->IsMap() || object->IsByteArray());
2178}
2179#endif
2180
2181
2182// -----------------------------------------------------------------------------
2183// GlobalPropertyCellSpace implementation
2184
2185#ifdef DEBUG
2186void CellSpace::VerifyObject(HeapObject* object) {
2187 // The object should be a global object property cell or a free-list node.
2188 ASSERT(object->IsJSGlobalPropertyCell() ||
2189 object->map() == Heap::two_pointer_filler_map());
2190}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002191#endif
2192
2193
2194// -----------------------------------------------------------------------------
2195// LargeObjectIterator
2196
2197LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2198 current_ = space->first_chunk_;
2199 size_func_ = NULL;
2200}
2201
2202
2203LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2204 HeapObjectCallback size_func) {
2205 current_ = space->first_chunk_;
2206 size_func_ = size_func;
2207}
2208
2209
2210HeapObject* LargeObjectIterator::next() {
2211 ASSERT(has_next());
2212 HeapObject* object = current_->GetObject();
2213 current_ = current_->next();
2214 return object;
2215}
2216
2217
2218// -----------------------------------------------------------------------------
2219// LargeObjectChunk
2220
2221LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002222 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002223 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002224 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002225 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2226 chunk_size,
2227 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002228 if (mem == NULL) return NULL;
2229 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2230 if (*chunk_size < requested) {
2231 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2232 LOG(DeleteEvent("LargeObjectChunk", mem));
2233 return NULL;
2234 }
2235 return reinterpret_cast<LargeObjectChunk*>(mem);
2236}
2237
2238
2239int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2240 int os_alignment = OS::AllocateAlignment();
2241 if (os_alignment < Page::kPageSize)
2242 size_in_bytes += (Page::kPageSize - os_alignment);
2243 return size_in_bytes + Page::kObjectStartOffset;
2244}
2245
2246// -----------------------------------------------------------------------------
2247// LargeObjectSpace
2248
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002249LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2250 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002251 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002252 size_(0),
2253 page_count_(0) {}
2254
2255
2256bool LargeObjectSpace::Setup() {
2257 first_chunk_ = NULL;
2258 size_ = 0;
2259 page_count_ = 0;
2260 return true;
2261}
2262
2263
2264void LargeObjectSpace::TearDown() {
2265 while (first_chunk_ != NULL) {
2266 LargeObjectChunk* chunk = first_chunk_;
2267 first_chunk_ = first_chunk_->next();
2268 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2269 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2270 }
2271
2272 size_ = 0;
2273 page_count_ = 0;
2274}
2275
2276
kasperl@chromium.orgf5aa8372009-03-24 14:47:14 +00002277#ifdef ENABLE_HEAP_PROTECTION
2278
2279void LargeObjectSpace::Protect() {
2280 LargeObjectChunk* chunk = first_chunk_;
2281 while (chunk != NULL) {
2282 MemoryAllocator::Protect(chunk->address(), chunk->size());
2283 chunk = chunk->next();
2284 }
2285}
2286
2287
2288void LargeObjectSpace::Unprotect() {
2289 LargeObjectChunk* chunk = first_chunk_;
2290 while (chunk != NULL) {
2291 bool is_code = chunk->GetObject()->IsCode();
2292 MemoryAllocator::Unprotect(chunk->address(), chunk->size(),
2293 is_code ? EXECUTABLE : NOT_EXECUTABLE);
2294 chunk = chunk->next();
2295 }
2296}
2297
2298#endif
2299
2300
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002301Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002302 int object_size,
2303 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002304 ASSERT(0 < object_size && object_size <= requested_size);
kasperl@chromium.org9bbf9682008-10-30 11:53:07 +00002305
2306 // Check if we want to force a GC before growing the old space further.
2307 // If so, fail the allocation.
2308 if (!Heap::always_allocate() && Heap::OldGenerationAllocationLimitReached()) {
2309 return Failure::RetryAfterGC(requested_size, identity());
2310 }
2311
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002312 size_t chunk_size;
2313 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002314 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002315 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002316 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002317 }
2318
2319 size_ += chunk_size;
2320 page_count_++;
2321 chunk->set_next(first_chunk_);
2322 chunk->set_size(chunk_size);
2323 first_chunk_ = chunk;
2324
2325 // Set the object address and size in the page header and clear its
2326 // remembered set.
2327 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2328 Address object_address = page->ObjectAreaStart();
2329 // Clear the low order bit of the second word in the page to flag it as a
2330 // large object page. If the chunk_size happened to be written there, its
2331 // low order bit should already be clear.
2332 ASSERT((chunk_size & 0x1) == 0);
2333 page->is_normal_page &= ~0x1;
2334 page->ClearRSet();
2335 int extra_bytes = requested_size - object_size;
2336 if (extra_bytes > 0) {
2337 // The extra memory for the remembered set should be cleared.
2338 memset(object_address + object_size, 0, extra_bytes);
2339 }
2340
2341 return HeapObject::FromAddress(object_address);
2342}
2343
2344
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002345Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002346 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002347 return AllocateRawInternal(size_in_bytes,
2348 size_in_bytes,
2349 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002350}
2351
2352
2353Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002354 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002355 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002356 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2357 size_in_bytes,
2358 NOT_EXECUTABLE);
2359}
2360
2361
2362Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2363 ASSERT(0 < size_in_bytes);
2364 return AllocateRawInternal(size_in_bytes,
2365 size_in_bytes,
2366 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002367}
2368
2369
2370// GC support
2371Object* LargeObjectSpace::FindObject(Address a) {
2372 for (LargeObjectChunk* chunk = first_chunk_;
2373 chunk != NULL;
2374 chunk = chunk->next()) {
2375 Address chunk_address = chunk->address();
2376 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2377 return chunk->GetObject();
2378 }
2379 }
2380 return Failure::Exception();
2381}
2382
2383
2384void LargeObjectSpace::ClearRSet() {
2385 ASSERT(Page::is_rset_in_use());
2386
2387 LargeObjectIterator it(this);
2388 while (it.has_next()) {
2389 HeapObject* object = it.next();
2390 // We only have code, sequential strings, or fixed arrays in large
2391 // object space, and only fixed arrays need remembered set support.
2392 if (object->IsFixedArray()) {
2393 // Clear the normal remembered set region of the page;
2394 Page* page = Page::FromAddress(object->address());
2395 page->ClearRSet();
2396
2397 // Clear the extra remembered set.
2398 int size = object->Size();
2399 int extra_rset_bytes = ExtraRSetBytesFor(size);
2400 memset(object->address() + size, 0, extra_rset_bytes);
2401 }
2402 }
2403}
2404
2405
2406void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2407 ASSERT(Page::is_rset_in_use());
2408
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002409 static void* lo_rset_histogram = StatsTable::CreateHistogram(
2410 "V8.RSetLO",
2411 0,
2412 // Keeping this histogram's buckets the same as the paged space histogram.
2413 Page::kObjectAreaSize / kPointerSize,
2414 30);
2415
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002416 LargeObjectIterator it(this);
2417 while (it.has_next()) {
2418 // We only have code, sequential strings, or fixed arrays in large
2419 // object space, and only fixed arrays can possibly contain pointers to
2420 // the young generation.
2421 HeapObject* object = it.next();
2422 if (object->IsFixedArray()) {
2423 // Iterate the normal page remembered set range.
2424 Page* page = Page::FromAddress(object->address());
2425 Address object_end = object->address() + object->Size();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002426 int count = Heap::IterateRSetRange(page->ObjectAreaStart(),
2427 Min(page->ObjectAreaEnd(), object_end),
2428 page->RSetStart(),
2429 copy_object_func);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002430
2431 // Iterate the extra array elements.
2432 if (object_end > page->ObjectAreaEnd()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002433 count += Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2434 object_end, copy_object_func);
2435 }
2436 if (lo_rset_histogram != NULL) {
2437 StatsTable::AddHistogramSample(lo_rset_histogram, count);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002438 }
2439 }
2440 }
2441}
2442
2443
2444void LargeObjectSpace::FreeUnmarkedObjects() {
2445 LargeObjectChunk* previous = NULL;
2446 LargeObjectChunk* current = first_chunk_;
2447 while (current != NULL) {
2448 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002449 if (object->IsMarked()) {
2450 object->ClearMark();
2451 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002452 previous = current;
2453 current = current->next();
2454 } else {
2455 Address chunk_address = current->address();
2456 size_t chunk_size = current->size();
2457
2458 // Cut the chunk out from the chunk list.
2459 current = current->next();
2460 if (previous == NULL) {
2461 first_chunk_ = current;
2462 } else {
2463 previous->set_next(current);
2464 }
2465
2466 // Free the chunk.
2467 if (object->IsCode()) {
2468 LOG(CodeDeleteEvent(object->address()));
2469 }
2470 size_ -= chunk_size;
2471 page_count_--;
2472 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2473 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2474 }
2475 }
2476}
2477
2478
2479bool LargeObjectSpace::Contains(HeapObject* object) {
2480 Address address = object->address();
2481 Page* page = Page::FromAddress(address);
2482
2483 SLOW_ASSERT(!page->IsLargeObjectPage()
2484 || !FindObject(address)->IsFailure());
2485
2486 return page->IsLargeObjectPage();
2487}
2488
2489
2490#ifdef DEBUG
2491// We do not assume that the large object iterator works, because it depends
2492// on the invariants we are checking during verification.
2493void LargeObjectSpace::Verify() {
2494 for (LargeObjectChunk* chunk = first_chunk_;
2495 chunk != NULL;
2496 chunk = chunk->next()) {
2497 // Each chunk contains an object that starts at the large object page's
2498 // object area start.
2499 HeapObject* object = chunk->GetObject();
2500 Page* page = Page::FromAddress(object->address());
2501 ASSERT(object->address() == page->ObjectAreaStart());
2502
2503 // The first word should be a map, and we expect all map pointers to be
2504 // in map space.
2505 Map* map = object->map();
2506 ASSERT(map->IsMap());
2507 ASSERT(Heap::map_space()->Contains(map));
2508
2509 // We have only code, sequential strings, fixed arrays, and byte arrays
2510 // in large object space.
2511 ASSERT(object->IsCode() || object->IsSeqString()
2512 || object->IsFixedArray() || object->IsByteArray());
2513
2514 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002515 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002516
2517 // Byte arrays and strings don't have interior pointers.
2518 if (object->IsCode()) {
2519 VerifyPointersVisitor code_visitor;
2520 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2521 object->IterateBody(map->instance_type(),
2522 object->Size(),
2523 &code_visitor);
2524 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2525 } else if (object->IsFixedArray()) {
2526 // We loop over fixed arrays ourselves, rather then using the visitor,
2527 // because the visitor doesn't support the start/offset iteration
2528 // needed for IsRSetSet.
2529 FixedArray* array = FixedArray::cast(object);
2530 for (int j = 0; j < array->length(); j++) {
2531 Object* element = array->get(j);
2532 if (element->IsHeapObject()) {
2533 HeapObject* element_object = HeapObject::cast(element);
2534 ASSERT(Heap::Contains(element_object));
2535 ASSERT(element_object->map()->IsMap());
2536 if (Heap::InNewSpace(element_object)) {
2537 ASSERT(Page::IsRSetSet(object->address(),
2538 FixedArray::kHeaderSize + j * kPointerSize));
2539 }
2540 }
2541 }
2542 }
2543 }
2544}
2545
2546
2547void LargeObjectSpace::Print() {
2548 LargeObjectIterator it(this);
2549 while (it.has_next()) {
2550 it.next()->Print();
2551 }
2552}
2553
2554
2555void LargeObjectSpace::ReportStatistics() {
2556 PrintF(" size: %d\n", size_);
2557 int num_objects = 0;
2558 ClearHistograms();
2559 LargeObjectIterator it(this);
2560 while (it.has_next()) {
2561 num_objects++;
2562 CollectHistogramInfo(it.next());
2563 }
2564
2565 PrintF(" number of objects %d\n", num_objects);
2566 if (num_objects > 0) ReportHistogram(false);
2567}
2568
2569
2570void LargeObjectSpace::CollectCodeStatistics() {
2571 LargeObjectIterator obj_it(this);
2572 while (obj_it.has_next()) {
2573 HeapObject* obj = obj_it.next();
2574 if (obj->IsCode()) {
2575 Code* code = Code::cast(obj);
2576 code_kind_statistics[code->kind()] += code->Size();
2577 }
2578 }
2579}
2580
2581
2582void LargeObjectSpace::PrintRSet() {
2583 LargeObjectIterator it(this);
2584 while (it.has_next()) {
2585 HeapObject* object = it.next();
2586 if (object->IsFixedArray()) {
2587 Page* page = Page::FromAddress(object->address());
2588
2589 Address allocation_top = object->address() + object->Size();
2590 PrintF("large page 0x%x:\n", page);
2591 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2592 reinterpret_cast<Object**>(object->address()),
2593 allocation_top);
2594 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2595 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2596 kBitsPerInt);
2597 PrintF("------------------------------------------------------------"
2598 "-----------\n");
2599 PrintRSetRange(allocation_top,
2600 allocation_top + extra_rset_bits / kBitsPerByte,
2601 reinterpret_cast<Object**>(object->address()
2602 + Page::kObjectAreaSize),
2603 allocation_top);
2604 PrintF("\n");
2605 }
2606 }
2607}
2608#endif // DEBUG
2609
2610} } // namespace v8::internal