blob: d1aacebf2e4ae54fe4a061432b7f5f5bf16ecf90 [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
34namespace v8 { namespace internal {
35
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036// For contiguous spaces, top should be in the space (or at the end) and limit
37// should be the end of the space.
38#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
39 ASSERT((space)->low() <= (info).top \
40 && (info).top <= (space)->high() \
41 && (info).limit == (space)->high())
42
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
44// ----------------------------------------------------------------------------
45// HeapObjectIterator
46
47HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
48 Initialize(space->bottom(), space->top(), NULL);
49}
50
51
52HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
53 HeapObjectCallback size_func) {
54 Initialize(space->bottom(), space->top(), size_func);
55}
56
57
58HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start) {
59 Initialize(start, space->top(), NULL);
60}
61
62
63HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start,
64 HeapObjectCallback size_func) {
65 Initialize(start, space->top(), size_func);
66}
67
68
69void HeapObjectIterator::Initialize(Address cur, Address end,
70 HeapObjectCallback size_f) {
71 cur_addr_ = cur;
72 end_addr_ = end;
73 end_page_ = Page::FromAllocationTop(end);
74 size_func_ = size_f;
75 Page* p = Page::FromAllocationTop(cur_addr_);
76 cur_limit_ = (p == end_page_) ? end_addr_ : p->AllocationTop();
77
78#ifdef DEBUG
79 Verify();
80#endif
81}
82
83
84bool HeapObjectIterator::HasNextInNextPage() {
85 if (cur_addr_ == end_addr_) return false;
86
87 Page* cur_page = Page::FromAllocationTop(cur_addr_);
88 cur_page = cur_page->next_page();
89 ASSERT(cur_page->is_valid());
90
91 cur_addr_ = cur_page->ObjectAreaStart();
92 cur_limit_ = (cur_page == end_page_) ? end_addr_ : cur_page->AllocationTop();
93
94 ASSERT(cur_addr_ < cur_limit_);
95#ifdef DEBUG
96 Verify();
97#endif
98 return true;
99}
100
101
102#ifdef DEBUG
103void HeapObjectIterator::Verify() {
104 Page* p = Page::FromAllocationTop(cur_addr_);
105 ASSERT(p == Page::FromAllocationTop(cur_limit_));
106 ASSERT(p->Offset(cur_addr_) <= p->Offset(cur_limit_));
107}
108#endif
109
110
111// -----------------------------------------------------------------------------
112// PageIterator
113
114PageIterator::PageIterator(PagedSpace* space, Mode mode) {
115 cur_page_ = space->first_page_;
116 switch (mode) {
117 case PAGES_IN_USE:
118 stop_page_ = space->AllocationTopPage()->next_page();
119 break;
120 case PAGES_USED_BY_MC:
121 stop_page_ = space->MCRelocationTopPage()->next_page();
122 break;
123 case ALL_PAGES:
124 stop_page_ = Page::FromAddress(NULL);
125 break;
126 default:
127 UNREACHABLE();
128 }
129}
130
131
132// -----------------------------------------------------------------------------
133// Page
134
135#ifdef DEBUG
136Page::RSetState Page::rset_state_ = Page::IN_USE;
137#endif
138
139// -----------------------------------------------------------------------------
140// MemoryAllocator
141//
142int MemoryAllocator::capacity_ = 0;
143int MemoryAllocator::size_ = 0;
144
145VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
146
147// 270 is an estimate based on the static default heap size of a pair of 256K
148// semispaces and a 64M old generation.
149const int kEstimatedNumberOfChunks = 270;
150List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
151 kEstimatedNumberOfChunks);
152List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
153int MemoryAllocator::max_nof_chunks_ = 0;
154int MemoryAllocator::top_ = 0;
155
156
157void MemoryAllocator::Push(int free_chunk_id) {
158 ASSERT(max_nof_chunks_ > 0);
159 ASSERT(top_ < max_nof_chunks_);
160 free_chunk_ids_[top_++] = free_chunk_id;
161}
162
163
164int MemoryAllocator::Pop() {
165 ASSERT(top_ > 0);
166 return free_chunk_ids_[--top_];
167}
168
169
170bool MemoryAllocator::Setup(int capacity) {
171 capacity_ = RoundUp(capacity, Page::kPageSize);
172
173 // Over-estimate the size of chunks_ array. It assumes the expansion of old
174 // space is always in the unit of a chunk (kChunkSize) except the last
175 // expansion.
176 //
177 // Due to alignment, allocated space might be one page less than required
178 // number (kPagesPerChunk) of pages for old spaces.
179 //
kasper.lund7276f142008-07-30 08:49:36 +0000180 // Reserve two chunk ids for semispaces, one for map space, one for old
181 // space, and one for code space.
182 max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000183 if (max_nof_chunks_ > kMaxNofChunks) return false;
184
185 size_ = 0;
186 ChunkInfo info; // uninitialized element.
187 for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
188 chunks_.Add(info);
189 free_chunk_ids_.Add(i);
190 }
191 top_ = max_nof_chunks_;
192 return true;
193}
194
195
196void MemoryAllocator::TearDown() {
197 for (int i = 0; i < max_nof_chunks_; i++) {
198 if (chunks_[i].address() != NULL) DeleteChunk(i);
199 }
200 chunks_.Clear();
201 free_chunk_ids_.Clear();
202
203 if (initial_chunk_ != NULL) {
204 LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
205 delete initial_chunk_;
206 initial_chunk_ = NULL;
207 }
208
209 ASSERT(top_ == max_nof_chunks_); // all chunks are free
210 top_ = 0;
211 capacity_ = 0;
212 size_ = 0;
213 max_nof_chunks_ = 0;
214}
215
216
217void* MemoryAllocator::AllocateRawMemory(const size_t requested,
kasper.lund7276f142008-07-30 08:49:36 +0000218 size_t* allocated,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000219 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000220 if (size_ + static_cast<int>(requested) > capacity_) return NULL;
221
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000222 void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000223 int alloced = *allocated;
224 size_ += alloced;
225 Counters::memory_allocated.Increment(alloced);
226 return mem;
227}
228
229
230void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
231 OS::Free(mem, length);
232 Counters::memory_allocated.Decrement(length);
233 size_ -= length;
234 ASSERT(size_ >= 0);
235}
236
237
238void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
239 ASSERT(initial_chunk_ == NULL);
240
241 initial_chunk_ = new VirtualMemory(requested);
242 CHECK(initial_chunk_ != NULL);
243 if (!initial_chunk_->IsReserved()) {
244 delete initial_chunk_;
245 initial_chunk_ = NULL;
246 return NULL;
247 }
248
249 // We are sure that we have mapped a block of requested addresses.
250 ASSERT(initial_chunk_->size() == requested);
251 LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
252 size_ += requested;
253 return initial_chunk_->address();
254}
255
256
257static int PagesInChunk(Address start, size_t size) {
258 // The first page starts on the first page-aligned address from start onward
259 // and the last page ends on the last page-aligned address before
260 // start+size. Page::kPageSize is a power of two so we can divide by
261 // shifting.
262 return (RoundDown(start + size, Page::kPageSize)
263 - RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
264}
265
266
267Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
268 PagedSpace* owner) {
269 if (requested_pages <= 0) return Page::FromAddress(NULL);
270 size_t chunk_size = requested_pages * Page::kPageSize;
271
272 // There is not enough space to guarantee the desired number pages can be
273 // allocated.
274 if (size_ + static_cast<int>(chunk_size) > capacity_) {
275 // Request as many pages as we can.
276 chunk_size = capacity_ - size_;
277 requested_pages = chunk_size >> Page::kPageSizeBits;
278
279 if (requested_pages <= 0) return Page::FromAddress(NULL);
280 }
kasper.lund7276f142008-07-30 08:49:36 +0000281 void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000282 if (chunk == NULL) return Page::FromAddress(NULL);
283 LOG(NewEvent("PagedChunk", chunk, chunk_size));
284
285 *allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
286 if (*allocated_pages == 0) {
287 FreeRawMemory(chunk, chunk_size);
288 LOG(DeleteEvent("PagedChunk", chunk));
289 return Page::FromAddress(NULL);
290 }
291
292 int chunk_id = Pop();
293 chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
294
295 return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
296}
297
298
299Page* MemoryAllocator::CommitPages(Address start, size_t size,
300 PagedSpace* owner, int* num_pages) {
301 ASSERT(start != NULL);
302 *num_pages = PagesInChunk(start, size);
303 ASSERT(*num_pages > 0);
304 ASSERT(initial_chunk_ != NULL);
305 ASSERT(initial_chunk_->address() <= start);
306 ASSERT(start + size <= reinterpret_cast<Address>(initial_chunk_->address())
307 + initial_chunk_->size());
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000308 if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309 return Page::FromAddress(NULL);
310 }
311 Counters::memory_allocated.Increment(size);
312
313 // So long as we correctly overestimated the number of chunks we should not
314 // run out of chunk ids.
315 CHECK(!OutOfChunkIds());
316 int chunk_id = Pop();
317 chunks_[chunk_id].init(start, size, owner);
318 return InitializePagesInChunk(chunk_id, *num_pages, owner);
319}
320
321
kasper.lund7276f142008-07-30 08:49:36 +0000322bool MemoryAllocator::CommitBlock(Address start,
323 size_t size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000324 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000325 ASSERT(start != NULL);
326 ASSERT(size > 0);
327 ASSERT(initial_chunk_ != NULL);
328 ASSERT(initial_chunk_->address() <= start);
329 ASSERT(start + size <= reinterpret_cast<Address>(initial_chunk_->address())
330 + initial_chunk_->size());
331
kasper.lund7276f142008-07-30 08:49:36 +0000332 if (!initial_chunk_->Commit(start, size, executable)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000333 Counters::memory_allocated.Increment(size);
334 return true;
335}
336
337
338Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
339 PagedSpace* owner) {
340 ASSERT(IsValidChunk(chunk_id));
341 ASSERT(pages_in_chunk > 0);
342
343 Address chunk_start = chunks_[chunk_id].address();
344
345 Address low = RoundUp(chunk_start, Page::kPageSize);
346
347#ifdef DEBUG
348 size_t chunk_size = chunks_[chunk_id].size();
349 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
350 ASSERT(pages_in_chunk <=
351 ((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
352#endif
353
354 Address page_addr = low;
355 for (int i = 0; i < pages_in_chunk; i++) {
356 Page* p = Page::FromAddress(page_addr);
357 p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
358 p->is_normal_page = 1;
359 page_addr += Page::kPageSize;
360 }
361
362 // Set the next page of the last page to 0.
363 Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
364 last_page->opaque_header = OffsetFrom(0) | chunk_id;
365
366 return Page::FromAddress(low);
367}
368
369
370Page* MemoryAllocator::FreePages(Page* p) {
371 if (!p->is_valid()) return p;
372
373 // Find the first page in the same chunk as 'p'
374 Page* first_page = FindFirstPageInSameChunk(p);
375 Page* page_to_return = Page::FromAddress(NULL);
376
377 if (p != first_page) {
378 // Find the last page in the same chunk as 'prev'.
379 Page* last_page = FindLastPageInSameChunk(p);
380 first_page = GetNextPage(last_page); // first page in next chunk
381
382 // set the next_page of last_page to NULL
383 SetNextPage(last_page, Page::FromAddress(NULL));
384 page_to_return = p; // return 'p' when exiting
385 }
386
387 while (first_page->is_valid()) {
388 int chunk_id = GetChunkId(first_page);
389 ASSERT(IsValidChunk(chunk_id));
390
391 // Find the first page of the next chunk before deleting this chunk.
392 first_page = GetNextPage(FindLastPageInSameChunk(first_page));
393
394 // Free the current chunk.
395 DeleteChunk(chunk_id);
396 }
397
398 return page_to_return;
399}
400
401
402void MemoryAllocator::DeleteChunk(int chunk_id) {
403 ASSERT(IsValidChunk(chunk_id));
404
405 ChunkInfo& c = chunks_[chunk_id];
406
407 // We cannot free a chunk contained in the initial chunk because it was not
408 // allocated with AllocateRawMemory. Instead we uncommit the virtual
409 // memory.
410 bool in_initial_chunk = false;
411 if (initial_chunk_ != NULL) {
412 Address start = static_cast<Address>(initial_chunk_->address());
413 Address end = start + initial_chunk_->size();
414 in_initial_chunk = (start <= c.address()) && (c.address() < end);
415 }
416
417 if (in_initial_chunk) {
418 // TODO(1240712): VirtualMemory::Uncommit has a return value which
419 // is ignored here.
420 initial_chunk_->Uncommit(c.address(), c.size());
421 Counters::memory_allocated.Decrement(c.size());
422 } else {
423 LOG(DeleteEvent("PagedChunk", c.address()));
424 FreeRawMemory(c.address(), c.size());
425 }
426 c.init(NULL, 0, NULL);
427 Push(chunk_id);
428}
429
430
431Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
432 int chunk_id = GetChunkId(p);
433 ASSERT(IsValidChunk(chunk_id));
434
435 Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
436 return Page::FromAddress(low);
437}
438
439
440Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
441 int chunk_id = GetChunkId(p);
442 ASSERT(IsValidChunk(chunk_id));
443
444 Address chunk_start = chunks_[chunk_id].address();
445 size_t chunk_size = chunks_[chunk_id].size();
446
447 Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
448 ASSERT(chunk_start <= p->address() && p->address() < high);
449
450 return Page::FromAddress(high - Page::kPageSize);
451}
452
453
454#ifdef DEBUG
455void MemoryAllocator::ReportStatistics() {
456 float pct = static_cast<float>(capacity_ - size_) / capacity_;
457 PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
458 capacity_, size_, static_cast<int>(pct*100));
459}
460#endif
461
462
463// -----------------------------------------------------------------------------
464// PagedSpace implementation
465
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000466PagedSpace::PagedSpace(int max_capacity,
467 AllocationSpace id,
468 Executability executable)
kasper.lund7276f142008-07-30 08:49:36 +0000469 : Space(id, executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000470 max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
471 * Page::kObjectAreaSize;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472 accounting_stats_.Clear();
473
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000474 allocation_info_.top = NULL;
475 allocation_info_.limit = NULL;
476
477 mc_forwarding_info_.top = NULL;
478 mc_forwarding_info_.limit = NULL;
479}
480
481
482bool PagedSpace::Setup(Address start, size_t size) {
483 if (HasBeenSetup()) return false;
484
485 int num_pages = 0;
486 // Try to use the virtual memory range passed to us. If it is too small to
487 // contain at least one page, ignore it and allocate instead.
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000488 int pages_in_chunk = PagesInChunk(start, size);
489 if (pages_in_chunk > 0) {
490 first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
491 Page::kPageSize * pages_in_chunk,
492 this, &num_pages);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000493 } else {
494 int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
495 max_capacity_ / Page::kObjectAreaSize);
496 first_page_ =
497 MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
498 if (!first_page_->is_valid()) return false;
499 }
500
501 // We are sure that the first page is valid and that we have at least one
502 // page.
503 ASSERT(first_page_->is_valid());
504 ASSERT(num_pages > 0);
505 accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
506 ASSERT(Capacity() <= max_capacity_);
507
508 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
509 p->ClearRSet();
510 }
511
512 // Use first_page_ for allocation.
513 SetAllocationInfo(&allocation_info_, first_page_);
514
515 return true;
516}
517
518
519bool PagedSpace::HasBeenSetup() {
520 return (Capacity() > 0);
521}
522
523
524void PagedSpace::TearDown() {
525 first_page_ = MemoryAllocator::FreePages(first_page_);
526 ASSERT(!first_page_->is_valid());
527
528 accounting_stats_.Clear();
529}
530
531
532void PagedSpace::ClearRSet() {
533 PageIterator it(this, PageIterator::ALL_PAGES);
534 while (it.has_next()) {
535 it.next()->ClearRSet();
536 }
537}
538
539
540Object* PagedSpace::FindObject(Address addr) {
541#ifdef DEBUG
542 // Note: this function can only be called before or after mark-compact GC
543 // because it accesses map pointers.
544 ASSERT(!MarkCompactCollector::in_use());
545#endif
546
547 if (!Contains(addr)) return Failure::Exception();
548
549 Page* p = Page::FromAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000550 ASSERT(IsUsed(p));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551 Address cur = p->ObjectAreaStart();
552 Address end = p->AllocationTop();
553 while (cur < end) {
554 HeapObject* obj = HeapObject::FromAddress(cur);
555 Address next = cur + obj->Size();
556 if ((cur <= addr) && (addr < next)) return obj;
557 cur = next;
558 }
559
kasper.lund7276f142008-07-30 08:49:36 +0000560 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000561 return Failure::Exception();
562}
563
564
kasper.lund7276f142008-07-30 08:49:36 +0000565bool PagedSpace::IsUsed(Page* page) {
566 PageIterator it(this, PageIterator::PAGES_IN_USE);
567 while (it.has_next()) {
568 if (page == it.next()) return true;
569 }
570 return false;
571}
572
573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000574void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
575 alloc_info->top = p->ObjectAreaStart();
576 alloc_info->limit = p->ObjectAreaEnd();
kasper.lund7276f142008-07-30 08:49:36 +0000577 ASSERT(alloc_info->VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578}
579
580
581void PagedSpace::MCResetRelocationInfo() {
582 // Set page indexes.
583 int i = 0;
584 PageIterator it(this, PageIterator::ALL_PAGES);
585 while (it.has_next()) {
586 Page* p = it.next();
587 p->mc_page_index = i++;
588 }
589
590 // Set mc_forwarding_info_ to the first page in the space.
591 SetAllocationInfo(&mc_forwarding_info_, first_page_);
592 // All the bytes in the space are 'available'. We will rediscover
593 // allocated and wasted bytes during GC.
594 accounting_stats_.Reset();
595}
596
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
599#ifdef DEBUG
600 // The Contains function considers the address at the beginning of a
601 // page in the page, MCSpaceOffsetForAddress considers it is in the
602 // previous page.
603 if (Page::IsAlignedToPageSize(addr)) {
604 ASSERT(Contains(addr - kPointerSize));
605 } else {
606 ASSERT(Contains(addr));
607 }
608#endif
609
610 // If addr is at the end of a page, it belongs to previous page
611 Page* p = Page::IsAlignedToPageSize(addr)
612 ? Page::FromAllocationTop(addr)
613 : Page::FromAddress(addr);
614 int index = p->mc_page_index;
615 return (index * Page::kPageSize) + p->Offset(addr);
616}
617
618
kasper.lund7276f142008-07-30 08:49:36 +0000619// Slow case for reallocating and promoting objects during a compacting
620// collection. This function is not space-specific.
621HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
622 Page* current_page = TopPageOf(mc_forwarding_info_);
623 if (!current_page->next_page()->is_valid()) {
624 if (!Expand(current_page)) {
625 return NULL;
626 }
627 }
628
629 // There are surely more pages in the space now.
630 ASSERT(current_page->next_page()->is_valid());
631 // We do not add the top of page block for current page to the space's
632 // free list---the block may contain live objects so we cannot write
633 // bookkeeping information to it. Instead, we will recover top of page
634 // blocks when we move objects to their new locations.
635 //
636 // We do however write the allocation pointer to the page. The encoding
637 // of forwarding addresses is as an offset in terms of live bytes, so we
638 // need quick access to the allocation top of each page to decode
639 // forwarding addresses.
640 current_page->mc_relocation_top = mc_forwarding_info_.top;
641 SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
642 return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
643}
644
645
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000646bool PagedSpace::Expand(Page* last_page) {
647 ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
648 ASSERT(Capacity() % Page::kObjectAreaSize == 0);
649
650 if (Capacity() == max_capacity_) return false;
651
652 ASSERT(Capacity() < max_capacity_);
653 // Last page must be valid and its next page is invalid.
654 ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
655
656 int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
657 if (available_pages <= 0) return false;
658
659 int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
660 Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
661 if (!p->is_valid()) return false;
662
663 accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
664 ASSERT(Capacity() <= max_capacity_);
665
666 MemoryAllocator::SetNextPage(last_page, p);
667
668 // Clear remembered set of new pages.
669 while (p->is_valid()) {
670 p->ClearRSet();
671 p = p->next_page();
672 }
673
674 return true;
675}
676
677
678#ifdef DEBUG
679int PagedSpace::CountTotalPages() {
680 int count = 0;
681 for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
682 count++;
683 }
684 return count;
685}
686#endif
687
688
689void PagedSpace::Shrink() {
690 // Release half of free pages.
691 Page* top_page = AllocationTopPage();
692 ASSERT(top_page->is_valid());
693
694 // Loop over the pages from the top page to the end of the space to count
695 // the number of pages to keep and find the last page to keep.
696 int free_pages = 0;
697 int pages_to_keep = 0; // Of the free pages.
698 Page* last_page_to_keep = top_page;
699 Page* current_page = top_page->next_page();
700 // Loop over the pages to the end of the space.
701 while (current_page->is_valid()) {
kasper.lund7276f142008-07-30 08:49:36 +0000702 // Advance last_page_to_keep every other step to end up at the midpoint.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703 if ((free_pages & 0x1) == 1) {
704 pages_to_keep++;
705 last_page_to_keep = last_page_to_keep->next_page();
706 }
707 free_pages++;
708 current_page = current_page->next_page();
709 }
710
711 // Free pages after last_page_to_keep, and adjust the next_page link.
712 Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
713 MemoryAllocator::SetNextPage(last_page_to_keep, p);
714
715 // Since pages are only freed in whole chunks, we may have kept more than
716 // pages_to_keep.
717 while (p->is_valid()) {
718 pages_to_keep++;
719 p = p->next_page();
720 }
721
722 // The difference between free_pages and pages_to_keep is the number of
723 // pages actually freed.
724 ASSERT(pages_to_keep <= free_pages);
725 int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
726 accounting_stats_.ShrinkSpace(bytes_freed);
727
728 ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
729}
730
731
732bool PagedSpace::EnsureCapacity(int capacity) {
733 if (Capacity() >= capacity) return true;
734
735 // Start from the allocation top and loop to the last page in the space.
736 Page* last_page = AllocationTopPage();
737 Page* next_page = last_page->next_page();
738 while (next_page->is_valid()) {
739 last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
740 next_page = last_page->next_page();
741 }
742
743 // Expand the space until it has the required capacity or expansion fails.
744 do {
745 if (!Expand(last_page)) return false;
746 ASSERT(last_page->next_page()->is_valid());
747 last_page =
748 MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
749 } while (Capacity() < capacity);
750
751 return true;
752}
753
754
755#ifdef DEBUG
756void PagedSpace::Print() { }
757#endif
758
759
760// -----------------------------------------------------------------------------
761// NewSpace implementation
762
763NewSpace::NewSpace(int initial_semispace_capacity,
kasper.lund7276f142008-07-30 08:49:36 +0000764 int maximum_semispace_capacity,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000765 AllocationSpace id)
766 : Space(id, NOT_EXECUTABLE) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000767 ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
768 ASSERT(IsPowerOf2(maximum_semispace_capacity));
769 maximum_capacity_ = maximum_semispace_capacity;
770 capacity_ = initial_semispace_capacity;
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000771 to_space_ = new SemiSpace(capacity_, maximum_capacity_, id);
772 from_space_ = new SemiSpace(capacity_, maximum_capacity_, id);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773
774 // Allocate and setup the histogram arrays if necessary.
775#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
776 allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
777 promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
778
779#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
780 promoted_histogram_[name].set_name(#name);
781 INSTANCE_TYPE_LIST(SET_NAME)
782#undef SET_NAME
783#endif
784}
785
786
787bool NewSpace::Setup(Address start, int size) {
788 ASSERT(size == 2 * maximum_capacity_);
789 ASSERT(IsAddressAligned(start, size, 0));
790
791 if (to_space_ == NULL
792 || !to_space_->Setup(start, maximum_capacity_)) {
793 return false;
794 }
795 if (from_space_ == NULL
796 || !from_space_->Setup(start + maximum_capacity_, maximum_capacity_)) {
797 return false;
798 }
799
800 start_ = start;
801 address_mask_ = ~(size - 1);
802 object_mask_ = address_mask_ | kHeapObjectTag;
803 object_expected_ = reinterpret_cast<uint32_t>(start) | kHeapObjectTag;
804
805 allocation_info_.top = to_space_->low();
806 allocation_info_.limit = to_space_->high();
807 mc_forwarding_info_.top = NULL;
808 mc_forwarding_info_.limit = NULL;
809
810 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
811 return true;
812}
813
814
815void NewSpace::TearDown() {
816#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
817 if (allocated_histogram_) {
818 DeleteArray(allocated_histogram_);
819 allocated_histogram_ = NULL;
820 }
821 if (promoted_histogram_) {
822 DeleteArray(promoted_histogram_);
823 promoted_histogram_ = NULL;
824 }
825#endif
826
827 start_ = NULL;
828 capacity_ = 0;
829 allocation_info_.top = NULL;
830 allocation_info_.limit = NULL;
831 mc_forwarding_info_.top = NULL;
832 mc_forwarding_info_.limit = NULL;
833
834 if (to_space_ != NULL) {
835 to_space_->TearDown();
836 delete to_space_;
837 to_space_ = NULL;
838 }
839
840 if (from_space_ != NULL) {
841 from_space_->TearDown();
842 delete from_space_;
843 from_space_ = NULL;
844 }
845}
846
847
848void NewSpace::Flip() {
849 SemiSpace* tmp = from_space_;
850 from_space_ = to_space_;
851 to_space_ = tmp;
852}
853
854
855bool NewSpace::Double() {
856 ASSERT(capacity_ <= maximum_capacity_ / 2);
857 // TODO(1240712): Failure to double the from space can result in
858 // semispaces of different sizes. In the event of that failure, the
859 // to space doubling should be rolled back before returning false.
860 if (!to_space_->Double() || !from_space_->Double()) return false;
861 capacity_ *= 2;
862 allocation_info_.limit = to_space_->high();
863 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
864 return true;
865}
866
867
868void NewSpace::ResetAllocationInfo() {
869 allocation_info_.top = to_space_->low();
870 allocation_info_.limit = to_space_->high();
871 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
872}
873
874
875void NewSpace::MCResetRelocationInfo() {
876 mc_forwarding_info_.top = from_space_->low();
877 mc_forwarding_info_.limit = from_space_->high();
878 ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);
879}
880
881
882void NewSpace::MCCommitRelocationInfo() {
883 // Assumes that the spaces have been flipped so that mc_forwarding_info_ is
884 // valid allocation info for the to space.
885 allocation_info_.top = mc_forwarding_info_.top;
886 allocation_info_.limit = to_space_->high();
887 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
888}
889
890
891#ifdef DEBUG
892// We do not use the SemispaceIterator because verification doesn't assume
893// that it works (it depends on the invariants we are checking).
894void NewSpace::Verify() {
895 // The allocation pointer should be in the space or at the very end.
896 ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
897
898 // There should be objects packed in from the low address up to the
899 // allocation pointer.
900 Address current = to_space_->low();
901 while (current < top()) {
902 HeapObject* object = HeapObject::FromAddress(current);
903
904 // The first word should be a map, and we expect all map pointers to
905 // be in map space.
906 Map* map = object->map();
907 ASSERT(map->IsMap());
908 ASSERT(Heap::map_space()->Contains(map));
909
910 // The object should not be code or a map.
911 ASSERT(!object->IsMap());
912 ASSERT(!object->IsCode());
913
914 // The object itself should look OK.
915 object->Verify();
916
917 // All the interior pointers should be contained in the heap.
918 VerifyPointersVisitor visitor;
919 int size = object->Size();
920 object->IterateBody(map->instance_type(), size, &visitor);
921
922 current += size;
923 }
924
925 // The allocation pointer should not be in the middle of an object.
926 ASSERT(current == top());
927}
928#endif
929
930
931// -----------------------------------------------------------------------------
932// SemiSpace implementation
933
kasper.lund7276f142008-07-30 08:49:36 +0000934SemiSpace::SemiSpace(int initial_capacity,
935 int maximum_capacity,
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000936 AllocationSpace id)
937 : Space(id, NOT_EXECUTABLE), capacity_(initial_capacity),
kasper.lund7276f142008-07-30 08:49:36 +0000938 maximum_capacity_(maximum_capacity), start_(NULL), age_mark_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939}
940
941
942bool SemiSpace::Setup(Address start, int size) {
943 ASSERT(size == maximum_capacity_);
kasper.lund7276f142008-07-30 08:49:36 +0000944 if (!MemoryAllocator::CommitBlock(start, capacity_, executable())) {
945 return false;
946 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000947
948 start_ = start;
949 address_mask_ = ~(size - 1);
950 object_mask_ = address_mask_ | kHeapObjectTag;
951 object_expected_ = reinterpret_cast<uint32_t>(start) | kHeapObjectTag;
952
953 age_mark_ = start_;
954 return true;
955}
956
957
958void SemiSpace::TearDown() {
959 start_ = NULL;
960 capacity_ = 0;
961}
962
963
964bool SemiSpace::Double() {
kasper.lund7276f142008-07-30 08:49:36 +0000965 if (!MemoryAllocator::CommitBlock(high(), capacity_, executable())) {
966 return false;
967 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000968 capacity_ *= 2;
969 return true;
970}
971
972
973#ifdef DEBUG
974void SemiSpace::Print() { }
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000975
976
977void SemiSpace::Verify() { }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000978#endif
979
980
981// -----------------------------------------------------------------------------
982// SemiSpaceIterator implementation.
983SemiSpaceIterator::SemiSpaceIterator(NewSpace* space) {
984 Initialize(space, space->bottom(), space->top(), NULL);
985}
986
987
988SemiSpaceIterator::SemiSpaceIterator(NewSpace* space,
989 HeapObjectCallback size_func) {
990 Initialize(space, space->bottom(), space->top(), size_func);
991}
992
993
994SemiSpaceIterator::SemiSpaceIterator(NewSpace* space, Address start) {
995 Initialize(space, start, space->top(), NULL);
996}
997
998
999void SemiSpaceIterator::Initialize(NewSpace* space, Address start,
1000 Address end,
1001 HeapObjectCallback size_func) {
1002 ASSERT(space->ToSpaceContains(start));
1003 ASSERT(space->ToSpaceLow() <= end
1004 && end <= space->ToSpaceHigh());
1005 space_ = space->to_space_;
1006 current_ = start;
1007 limit_ = end;
1008 size_func_ = size_func;
1009}
1010
1011
1012#ifdef DEBUG
1013// A static array of histogram info for each type.
1014static HistogramInfo heap_histograms[LAST_TYPE+1];
1015static JSObject::SpillInformation js_spill_information;
1016
1017// heap_histograms is shared, always clear it before using it.
1018static void ClearHistograms() {
1019 // We reset the name each time, though it hasn't changed.
1020#define DEF_TYPE_NAME(name) heap_histograms[name].set_name(#name);
1021 INSTANCE_TYPE_LIST(DEF_TYPE_NAME)
1022#undef DEF_TYPE_NAME
1023
1024#define CLEAR_HISTOGRAM(name) heap_histograms[name].clear();
1025 INSTANCE_TYPE_LIST(CLEAR_HISTOGRAM)
1026#undef CLEAR_HISTOGRAM
1027
1028 js_spill_information.Clear();
1029}
1030
1031
1032static int code_kind_statistics[Code::NUMBER_OF_KINDS];
1033
1034
1035static void ClearCodeKindStatistics() {
1036 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1037 code_kind_statistics[i] = 0;
1038 }
1039}
1040
1041
1042static void ReportCodeKindStatistics() {
1043 const char* table[Code::NUMBER_OF_KINDS];
1044
1045#define CASE(name) \
1046 case Code::name: table[Code::name] = #name; \
1047 break
1048
1049 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1050 switch (static_cast<Code::Kind>(i)) {
1051 CASE(FUNCTION);
1052 CASE(STUB);
1053 CASE(BUILTIN);
1054 CASE(LOAD_IC);
1055 CASE(KEYED_LOAD_IC);
1056 CASE(STORE_IC);
1057 CASE(KEYED_STORE_IC);
1058 CASE(CALL_IC);
1059 }
1060 }
1061
1062#undef CASE
1063
1064 PrintF("\n Code kind histograms: \n");
1065 for (int i = 0; i < Code::NUMBER_OF_KINDS; i++) {
1066 if (code_kind_statistics[i] > 0) {
1067 PrintF(" %-20s: %10d bytes\n", table[i], code_kind_statistics[i]);
1068 }
1069 }
1070 PrintF("\n");
1071}
1072
1073
1074static int CollectHistogramInfo(HeapObject* obj) {
1075 InstanceType type = obj->map()->instance_type();
1076 ASSERT(0 <= type && type <= LAST_TYPE);
1077 ASSERT(heap_histograms[type].name() != NULL);
1078 heap_histograms[type].increment_number(1);
1079 heap_histograms[type].increment_bytes(obj->Size());
1080
1081 if (FLAG_collect_heap_spill_statistics && obj->IsJSObject()) {
1082 JSObject::cast(obj)->IncrementSpillStatistics(&js_spill_information);
1083 }
1084
1085 return obj->Size();
1086}
1087
1088
1089static void ReportHistogram(bool print_spill) {
1090 PrintF("\n Object Histogram:\n");
1091 for (int i = 0; i <= LAST_TYPE; i++) {
1092 if (heap_histograms[i].number() > 0) {
1093 PrintF(" %-33s%10d (%10d bytes)\n",
1094 heap_histograms[i].name(),
1095 heap_histograms[i].number(),
1096 heap_histograms[i].bytes());
1097 }
1098 }
1099 PrintF("\n");
1100
1101 // Summarize string types.
1102 int string_number = 0;
1103 int string_bytes = 0;
1104#define INCREMENT(type, size, name) \
1105 string_number += heap_histograms[type].number(); \
1106 string_bytes += heap_histograms[type].bytes();
1107 STRING_TYPE_LIST(INCREMENT)
1108#undef INCREMENT
1109 if (string_number > 0) {
1110 PrintF(" %-33s%10d (%10d bytes)\n\n", "STRING_TYPE", string_number,
1111 string_bytes);
1112 }
1113
1114 if (FLAG_collect_heap_spill_statistics && print_spill) {
1115 js_spill_information.Print();
1116 }
1117}
1118#endif // DEBUG
1119
1120
1121// Support for statistics gathering for --heap-stats and --log-gc.
1122#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1123void NewSpace::ClearHistograms() {
1124 for (int i = 0; i <= LAST_TYPE; i++) {
1125 allocated_histogram_[i].clear();
1126 promoted_histogram_[i].clear();
1127 }
1128}
1129
1130// Because the copying collector does not touch garbage objects, we iterate
1131// the new space before a collection to get a histogram of allocated objects.
1132// This only happens (1) when compiled with DEBUG and the --heap-stats flag is
1133// set, or when compiled with ENABLE_LOGGING_AND_PROFILING and the --log-gc
1134// flag is set.
1135void NewSpace::CollectStatistics() {
1136 ClearHistograms();
1137 SemiSpaceIterator it(this);
1138 while (it.has_next()) RecordAllocation(it.next());
1139}
1140
1141
1142#ifdef ENABLE_LOGGING_AND_PROFILING
1143static void DoReportStatistics(HistogramInfo* info, const char* description) {
1144 LOG(HeapSampleBeginEvent("NewSpace", description));
1145 // Lump all the string types together.
1146 int string_number = 0;
1147 int string_bytes = 0;
1148#define INCREMENT(type, size, name) \
1149 string_number += info[type].number(); \
1150 string_bytes += info[type].bytes();
1151 STRING_TYPE_LIST(INCREMENT)
1152#undef INCREMENT
1153 if (string_number > 0) {
1154 LOG(HeapSampleItemEvent("STRING_TYPE", string_number, string_bytes));
1155 }
1156
1157 // Then do the other types.
1158 for (int i = FIRST_NONSTRING_TYPE; i <= LAST_TYPE; ++i) {
1159 if (info[i].number() > 0) {
1160 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
1161 info[i].bytes()));
1162 }
1163 }
1164 LOG(HeapSampleEndEvent("NewSpace", description));
1165}
1166#endif // ENABLE_LOGGING_AND_PROFILING
1167
1168
1169void NewSpace::ReportStatistics() {
1170#ifdef DEBUG
1171 if (FLAG_heap_stats) {
1172 float pct = static_cast<float>(Available()) / Capacity();
1173 PrintF(" capacity: %d, available: %d, %%%d\n",
1174 Capacity(), Available(), static_cast<int>(pct*100));
1175 PrintF("\n Object Histogram:\n");
1176 for (int i = 0; i <= LAST_TYPE; i++) {
1177 if (allocated_histogram_[i].number() > 0) {
1178 PrintF(" %-33s%10d (%10d bytes)\n",
1179 allocated_histogram_[i].name(),
1180 allocated_histogram_[i].number(),
1181 allocated_histogram_[i].bytes());
1182 }
1183 }
1184 PrintF("\n");
1185 }
1186#endif // DEBUG
1187
1188#ifdef ENABLE_LOGGING_AND_PROFILING
1189 if (FLAG_log_gc) {
1190 DoReportStatistics(allocated_histogram_, "allocated");
1191 DoReportStatistics(promoted_histogram_, "promoted");
1192 }
1193#endif // ENABLE_LOGGING_AND_PROFILING
1194}
1195
1196
1197void NewSpace::RecordAllocation(HeapObject* obj) {
1198 InstanceType type = obj->map()->instance_type();
1199 ASSERT(0 <= type && type <= LAST_TYPE);
1200 allocated_histogram_[type].increment_number(1);
1201 allocated_histogram_[type].increment_bytes(obj->Size());
1202}
1203
1204
1205void NewSpace::RecordPromotion(HeapObject* obj) {
1206 InstanceType type = obj->map()->instance_type();
1207 ASSERT(0 <= type && type <= LAST_TYPE);
1208 promoted_histogram_[type].increment_number(1);
1209 promoted_histogram_[type].increment_bytes(obj->Size());
1210}
1211#endif // defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1212
1213
1214// -----------------------------------------------------------------------------
1215// Free lists for old object spaces implementation
1216
1217void FreeListNode::set_size(int size_in_bytes) {
1218 ASSERT(size_in_bytes > 0);
1219 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1220
1221 // We write a map and possibly size information to the block. If the block
1222 // is big enough to be a ByteArray with at least one extra word (the next
1223 // pointer), we set its map to be the byte array map and its size to an
1224 // appropriate array length for the desired size from HeapObject::Size().
1225 // If the block is too small (eg, one or two words), to hold both a size
1226 // field and a next pointer, we give it a filler map that gives it the
1227 // correct size.
1228 if (size_in_bytes > Array::kHeaderSize) {
1229 set_map(Heap::byte_array_map());
1230 ByteArray::cast(this)->set_length(ByteArray::LengthFor(size_in_bytes));
1231 } else if (size_in_bytes == kPointerSize) {
1232 set_map(Heap::one_word_filler_map());
1233 } else if (size_in_bytes == 2 * kPointerSize) {
1234 set_map(Heap::two_word_filler_map());
1235 } else {
1236 UNREACHABLE();
1237 }
kasper.lund7276f142008-07-30 08:49:36 +00001238 ASSERT(Size() == size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001239}
1240
1241
1242Address FreeListNode::next() {
1243 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001244 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001245 return Memory::Address_at(address() + kNextOffset);
1246}
1247
1248
1249void FreeListNode::set_next(Address next) {
1250 ASSERT(map() == Heap::byte_array_map());
kasper.lund7276f142008-07-30 08:49:36 +00001251 ASSERT(Size() >= kNextOffset + kPointerSize);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001252 Memory::Address_at(address() + kNextOffset) = next;
1253}
1254
1255
1256OldSpaceFreeList::OldSpaceFreeList(AllocationSpace owner) : owner_(owner) {
1257 Reset();
1258}
1259
1260
1261void OldSpaceFreeList::Reset() {
1262 available_ = 0;
1263 for (int i = 0; i < kFreeListsLength; i++) {
1264 free_[i].head_node_ = NULL;
1265 }
1266 needs_rebuild_ = false;
1267 finger_ = kHead;
1268 free_[kHead].next_size_ = kEnd;
1269}
1270
1271
1272void OldSpaceFreeList::RebuildSizeList() {
1273 ASSERT(needs_rebuild_);
1274 int cur = kHead;
1275 for (int i = cur + 1; i < kFreeListsLength; i++) {
1276 if (free_[i].head_node_ != NULL) {
1277 free_[cur].next_size_ = i;
1278 cur = i;
1279 }
1280 }
1281 free_[cur].next_size_ = kEnd;
1282 needs_rebuild_ = false;
1283}
1284
1285
1286int OldSpaceFreeList::Free(Address start, int size_in_bytes) {
1287#ifdef DEBUG
1288 for (int i = 0; i < size_in_bytes; i += kPointerSize) {
1289 Memory::Address_at(start + i) = kZapValue;
1290 }
1291#endif
1292 FreeListNode* node = FreeListNode::FromAddress(start);
1293 node->set_size(size_in_bytes);
1294
1295 // Early return to drop too-small blocks on the floor (one or two word
1296 // blocks cannot hold a map pointer, a size field, and a pointer to the
1297 // next block in the free list).
1298 if (size_in_bytes < kMinBlockSize) {
1299 return size_in_bytes;
1300 }
1301
1302 // Insert other blocks at the head of an exact free list.
1303 int index = size_in_bytes >> kPointerSizeLog2;
1304 node->set_next(free_[index].head_node_);
1305 free_[index].head_node_ = node->address();
1306 available_ += size_in_bytes;
1307 needs_rebuild_ = true;
1308 return 0;
1309}
1310
1311
1312Object* OldSpaceFreeList::Allocate(int size_in_bytes, int* wasted_bytes) {
1313 ASSERT(0 < size_in_bytes);
1314 ASSERT(size_in_bytes <= kMaxBlockSize);
1315 ASSERT(IsAligned(size_in_bytes, kPointerSize));
1316
1317 if (needs_rebuild_) RebuildSizeList();
1318 int index = size_in_bytes >> kPointerSizeLog2;
1319 // Check for a perfect fit.
1320 if (free_[index].head_node_ != NULL) {
1321 FreeListNode* node = FreeListNode::FromAddress(free_[index].head_node_);
1322 // If this was the last block of its size, remove the size.
1323 if ((free_[index].head_node_ = node->next()) == NULL) RemoveSize(index);
1324 available_ -= size_in_bytes;
1325 *wasted_bytes = 0;
1326 return node;
1327 }
1328 // Search the size list for the best fit.
1329 int prev = finger_ < index ? finger_ : kHead;
1330 int cur = FindSize(index, &prev);
1331 ASSERT(index < cur);
1332 if (cur == kEnd) {
1333 // No large enough size in list.
1334 *wasted_bytes = 0;
1335 return Failure::RetryAfterGC(size_in_bytes, owner_);
1336 }
1337 int rem = cur - index;
1338 int rem_bytes = rem << kPointerSizeLog2;
1339 FreeListNode* cur_node = FreeListNode::FromAddress(free_[cur].head_node_);
kasper.lund7276f142008-07-30 08:49:36 +00001340 ASSERT(cur_node->Size() == (cur << kPointerSizeLog2));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001341 FreeListNode* rem_node = FreeListNode::FromAddress(free_[cur].head_node_ +
1342 size_in_bytes);
1343 // Distinguish the cases prev < rem < cur and rem <= prev < cur
1344 // to avoid many redundant tests and calls to Insert/RemoveSize.
1345 if (prev < rem) {
1346 // Simple case: insert rem between prev and cur.
1347 finger_ = prev;
1348 free_[prev].next_size_ = rem;
1349 // If this was the last block of size cur, remove the size.
1350 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1351 free_[rem].next_size_ = free_[cur].next_size_;
1352 } else {
1353 free_[rem].next_size_ = cur;
1354 }
1355 // Add the remainder block.
1356 rem_node->set_size(rem_bytes);
1357 rem_node->set_next(free_[rem].head_node_);
1358 free_[rem].head_node_ = rem_node->address();
1359 } else {
1360 // If this was the last block of size cur, remove the size.
1361 if ((free_[cur].head_node_ = cur_node->next()) == NULL) {
1362 finger_ = prev;
1363 free_[prev].next_size_ = free_[cur].next_size_;
1364 }
1365 if (rem_bytes < kMinBlockSize) {
1366 // Too-small remainder is wasted.
1367 rem_node->set_size(rem_bytes);
1368 available_ -= size_in_bytes + rem_bytes;
1369 *wasted_bytes = rem_bytes;
1370 return cur_node;
1371 }
1372 // Add the remainder block and, if needed, insert its size.
1373 rem_node->set_size(rem_bytes);
1374 rem_node->set_next(free_[rem].head_node_);
1375 free_[rem].head_node_ = rem_node->address();
1376 if (rem_node->next() == NULL) InsertSize(rem);
1377 }
1378 available_ -= size_in_bytes;
1379 *wasted_bytes = 0;
1380 return cur_node;
1381}
1382
1383
kasper.lund7276f142008-07-30 08:49:36 +00001384#ifdef DEBUG
1385bool OldSpaceFreeList::Contains(FreeListNode* node) {
1386 for (int i = 0; i < kFreeListsLength; i++) {
1387 Address cur_addr = free_[i].head_node_;
1388 while (cur_addr != NULL) {
1389 FreeListNode* cur_node = FreeListNode::FromAddress(cur_addr);
1390 if (cur_node == node) return true;
1391 cur_addr = cur_node->next();
1392 }
1393 }
1394 return false;
1395}
1396#endif
1397
1398
1399MapSpaceFreeList::MapSpaceFreeList(AllocationSpace owner) {
1400 owner_ = owner;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001401 Reset();
1402}
1403
1404
1405void MapSpaceFreeList::Reset() {
1406 available_ = 0;
1407 head_ = NULL;
1408}
1409
1410
1411void MapSpaceFreeList::Free(Address start) {
1412#ifdef DEBUG
1413 for (int i = 0; i < Map::kSize; i += kPointerSize) {
1414 Memory::Address_at(start + i) = kZapValue;
1415 }
1416#endif
1417 FreeListNode* node = FreeListNode::FromAddress(start);
1418 node->set_size(Map::kSize);
1419 node->set_next(head_);
1420 head_ = node->address();
1421 available_ += Map::kSize;
1422}
1423
1424
1425Object* MapSpaceFreeList::Allocate() {
1426 if (head_ == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00001427 return Failure::RetryAfterGC(Map::kSize, owner_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001428 }
1429
1430 FreeListNode* node = FreeListNode::FromAddress(head_);
1431 head_ = node->next();
1432 available_ -= Map::kSize;
1433 return node;
1434}
1435
1436
1437// -----------------------------------------------------------------------------
1438// OldSpace implementation
1439
1440void OldSpace::PrepareForMarkCompact(bool will_compact) {
1441 if (will_compact) {
1442 // Reset relocation info. During a compacting collection, everything in
1443 // the space is considered 'available' and we will rediscover live data
1444 // and waste during the collection.
1445 MCResetRelocationInfo();
1446 mc_end_of_relocation_ = bottom();
1447 ASSERT(Available() == Capacity());
1448 } else {
1449 // During a non-compacting collection, everything below the linear
1450 // allocation pointer is considered allocated (everything above is
1451 // available) and we will rediscover available and wasted bytes during
1452 // the collection.
1453 accounting_stats_.AllocateBytes(free_list_.available());
1454 accounting_stats_.FillWastedBytes(Waste());
1455 }
1456
kasper.lund7276f142008-07-30 08:49:36 +00001457 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001458 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001459}
1460
1461
1462void OldSpace::MCAdjustRelocationEnd(Address address, int size_in_bytes) {
1463 ASSERT(Contains(address));
1464 Address current_top = mc_end_of_relocation_;
1465 Page* current_page = Page::FromAllocationTop(current_top);
1466
1467 // No more objects relocated to this page? Move to the next.
1468 ASSERT(current_top <= current_page->mc_relocation_top);
1469 if (current_top == current_page->mc_relocation_top) {
1470 // The space should already be properly expanded.
1471 Page* next_page = current_page->next_page();
1472 CHECK(next_page->is_valid());
1473 mc_end_of_relocation_ = next_page->ObjectAreaStart();
1474 }
1475 ASSERT(mc_end_of_relocation_ == address);
1476 mc_end_of_relocation_ += size_in_bytes;
1477}
1478
1479
1480void OldSpace::MCCommitRelocationInfo() {
1481 // Update fast allocation info.
1482 allocation_info_.top = mc_forwarding_info_.top;
1483 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001484 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001485
1486 // The space is compacted and we haven't yet built free lists or
1487 // wasted any space.
1488 ASSERT(Waste() == 0);
1489 ASSERT(AvailableFree() == 0);
1490
1491 // Build the free list for the space.
1492 int computed_size = 0;
1493 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1494 while (it.has_next()) {
1495 Page* p = it.next();
1496 // Space below the relocation pointer is allocated.
1497 computed_size += p->mc_relocation_top - p->ObjectAreaStart();
1498 if (it.has_next()) {
1499 // Free the space at the top of the page. We cannot use
1500 // p->mc_relocation_top after the call to Free (because Free will clear
1501 // remembered set bits).
1502 int extra_size = p->ObjectAreaEnd() - p->mc_relocation_top;
1503 if (extra_size > 0) {
1504 int wasted_bytes = free_list_.Free(p->mc_relocation_top, extra_size);
1505 // The bytes we have just "freed" to add to the free list were
1506 // already accounted as available.
1507 accounting_stats_.WasteBytes(wasted_bytes);
1508 }
1509 }
1510 }
1511
1512 // Make sure the computed size - based on the used portion of the pages in
1513 // use - matches the size obtained while computing forwarding addresses.
1514 ASSERT(computed_size == Size());
1515}
1516
1517
kasper.lund7276f142008-07-30 08:49:36 +00001518// Slow case for normal allocation. Try in order: (1) allocate in the next
1519// page in the space, (2) allocate off the space's free list, (3) expand the
1520// space, (4) fail.
1521HeapObject* OldSpace::SlowAllocateRaw(int size_in_bytes) {
1522 // Linear allocation in this space has failed. If there is another page
1523 // in the space, move to that page and allocate there. This allocation
1524 // should succeed (size_in_bytes should not be greater than a page's
1525 // object area size).
1526 Page* current_page = TopPageOf(allocation_info_);
1527 if (current_page->next_page()->is_valid()) {
1528 return AllocateInNextPage(current_page, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001529 }
kasper.lund7276f142008-07-30 08:49:36 +00001530
1531 // There is no next page in this space. Try free list allocation.
1532 int wasted_bytes;
1533 Object* result = free_list_.Allocate(size_in_bytes, &wasted_bytes);
1534 accounting_stats_.WasteBytes(wasted_bytes);
1535 if (!result->IsFailure()) {
1536 accounting_stats_.AllocateBytes(size_in_bytes);
1537 return HeapObject::cast(result);
1538 }
1539
1540 // Free list allocation failed and there is no next page. Try to expand
1541 // the space and allocate in the new next page.
1542 ASSERT(!current_page->next_page()->is_valid());
1543 if (Expand(current_page)) {
1544 return AllocateInNextPage(current_page, size_in_bytes);
1545 }
1546
1547 // Finally, fail.
1548 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549}
1550
1551
kasper.lund7276f142008-07-30 08:49:36 +00001552// Add the block at the top of the page to the space's free list, set the
1553// allocation info to the next page (assumed to be one), and allocate
1554// linearly there.
1555HeapObject* OldSpace::AllocateInNextPage(Page* current_page,
1556 int size_in_bytes) {
1557 ASSERT(current_page->next_page()->is_valid());
1558 // Add the block at the top of this page to the free list.
1559 int free_size = current_page->ObjectAreaEnd() - allocation_info_.top;
1560 if (free_size > 0) {
1561 int wasted_bytes = free_list_.Free(allocation_info_.top, free_size);
1562 accounting_stats_.WasteBytes(wasted_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001563 }
kasper.lund7276f142008-07-30 08:49:36 +00001564 SetAllocationInfo(&allocation_info_, current_page->next_page());
1565 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001566}
1567
1568
1569#ifdef DEBUG
1570// We do not assume that the PageIterator works, because it depends on the
1571// invariants we are checking during verification.
1572void OldSpace::Verify() {
1573 // The allocation pointer should be valid, and it should be in a page in the
1574 // space.
kasper.lund7276f142008-07-30 08:49:36 +00001575 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001576 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
1577 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
1578
1579 // Loop over all the pages.
1580 bool above_allocation_top = false;
1581 Page* current_page = first_page_;
1582 while (current_page->is_valid()) {
1583 if (above_allocation_top) {
1584 // We don't care what's above the allocation top.
1585 } else {
1586 // Unless this is the last page in the space containing allocated
1587 // objects, the allocation top should be at the object area end.
1588 Address top = current_page->AllocationTop();
1589 if (current_page == top_page) {
1590 ASSERT(top == allocation_info_.top);
1591 // The next page will be above the allocation top.
1592 above_allocation_top = true;
1593 } else {
1594 ASSERT(top == current_page->ObjectAreaEnd());
1595 }
1596
1597 // It should be packed with objects from the bottom to the top.
1598 Address current = current_page->ObjectAreaStart();
1599 while (current < top) {
1600 HeapObject* object = HeapObject::FromAddress(current);
1601
1602 // The first word should be a map, and we expect all map pointers to
1603 // be in map space.
1604 Map* map = object->map();
1605 ASSERT(map->IsMap());
1606 ASSERT(Heap::map_space()->Contains(map));
1607
1608 // The object should not be a map.
1609 ASSERT(!object->IsMap());
1610
1611 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00001612 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001613
1614 // All the interior pointers should be contained in the heap and have
1615 // their remembered set bits set if they point to new space. Code
1616 // objects do not have remembered set bits that we care about.
1617 VerifyPointersAndRSetVisitor rset_visitor;
1618 VerifyPointersVisitor no_rset_visitor;
1619 int size = object->Size();
1620 if (object->IsCode()) {
1621 Code::cast(object)->ConvertICTargetsFromAddressToObject();
1622 object->IterateBody(map->instance_type(), size, &no_rset_visitor);
1623 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
1624 } else {
1625 object->IterateBody(map->instance_type(), size, &rset_visitor);
1626 }
1627
1628 current += size;
1629 }
1630
1631 // The allocation pointer should not be in the middle of an object.
1632 ASSERT(current == top);
1633 }
1634
1635 current_page = current_page->next_page();
1636 }
1637}
1638
1639
1640struct CommentStatistic {
1641 const char* comment;
1642 int size;
1643 int count;
1644 void Clear() {
1645 comment = NULL;
1646 size = 0;
1647 count = 0;
1648 }
1649};
1650
1651
1652// must be small, since an iteration is used for lookup
1653const int kMaxComments = 64;
1654static CommentStatistic comments_statistics[kMaxComments+1];
1655
1656
1657void PagedSpace::ReportCodeStatistics() {
1658 ReportCodeKindStatistics();
1659 PrintF("Code comment statistics (\" [ comment-txt : size/ "
1660 "count (average)\"):\n");
1661 for (int i = 0; i <= kMaxComments; i++) {
1662 const CommentStatistic& cs = comments_statistics[i];
1663 if (cs.size > 0) {
1664 PrintF(" %-30s: %10d/%6d (%d)\n", cs.comment, cs.size, cs.count,
1665 cs.size/cs.count);
1666 }
1667 }
1668 PrintF("\n");
1669}
1670
1671
1672void PagedSpace::ResetCodeStatistics() {
1673 ClearCodeKindStatistics();
1674 for (int i = 0; i < kMaxComments; i++) comments_statistics[i].Clear();
1675 comments_statistics[kMaxComments].comment = "Unknown";
1676 comments_statistics[kMaxComments].size = 0;
1677 comments_statistics[kMaxComments].count = 0;
1678}
1679
1680
1681// Adds comment to 'comment_statistics' table. Performance OK sa long as
1682// 'kMaxComments' is small
1683static void EnterComment(const char* comment, int delta) {
1684 // Do not count empty comments
1685 if (delta <= 0) return;
1686 CommentStatistic* cs = &comments_statistics[kMaxComments];
1687 // Search for a free or matching entry in 'comments_statistics': 'cs'
1688 // points to result.
1689 for (int i = 0; i < kMaxComments; i++) {
1690 if (comments_statistics[i].comment == NULL) {
1691 cs = &comments_statistics[i];
1692 cs->comment = comment;
1693 break;
1694 } else if (strcmp(comments_statistics[i].comment, comment) == 0) {
1695 cs = &comments_statistics[i];
1696 break;
1697 }
1698 }
1699 // Update entry for 'comment'
1700 cs->size += delta;
1701 cs->count += 1;
1702}
1703
1704
1705// Call for each nested comment start (start marked with '[ xxx', end marked
1706// with ']'. RelocIterator 'it' must point to a comment reloc info.
1707static void CollectCommentStatistics(RelocIterator* it) {
1708 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001709 ASSERT(it->rinfo()->rmode() == RelocInfo::COMMENT);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710 const char* tmp = reinterpret_cast<const char*>(it->rinfo()->data());
1711 if (tmp[0] != '[') {
1712 // Not a nested comment; skip
1713 return;
1714 }
1715
1716 // Search for end of nested comment or a new nested comment
1717 const char* const comment_txt =
1718 reinterpret_cast<const char*>(it->rinfo()->data());
1719 const byte* prev_pc = it->rinfo()->pc();
1720 int flat_delta = 0;
1721 it->next();
1722 while (true) {
1723 // All nested comments must be terminated properly, and therefore exit
1724 // from loop.
1725 ASSERT(!it->done());
ager@chromium.org236ad962008-09-25 09:45:57 +00001726 if (it->rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001727 const char* const txt =
1728 reinterpret_cast<const char*>(it->rinfo()->data());
1729 flat_delta += it->rinfo()->pc() - prev_pc;
1730 if (txt[0] == ']') break; // End of nested comment
1731 // A new comment
1732 CollectCommentStatistics(it);
1733 // Skip code that was covered with previous comment
1734 prev_pc = it->rinfo()->pc();
1735 }
1736 it->next();
1737 }
1738 EnterComment(comment_txt, flat_delta);
1739}
1740
1741
1742// Collects code size statistics:
1743// - by code kind
1744// - by code comment
1745void PagedSpace::CollectCodeStatistics() {
1746 HeapObjectIterator obj_it(this);
1747 while (obj_it.has_next()) {
1748 HeapObject* obj = obj_it.next();
1749 if (obj->IsCode()) {
1750 Code* code = Code::cast(obj);
1751 code_kind_statistics[code->kind()] += code->Size();
1752 RelocIterator it(code);
1753 int delta = 0;
1754 const byte* prev_pc = code->instruction_start();
1755 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001756 if (it.rinfo()->rmode() == RelocInfo::COMMENT) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757 delta += it.rinfo()->pc() - prev_pc;
1758 CollectCommentStatistics(&it);
1759 prev_pc = it.rinfo()->pc();
1760 }
1761 it.next();
1762 }
1763
1764 ASSERT(code->instruction_start() <= prev_pc &&
1765 prev_pc <= code->relocation_start());
1766 delta += code->relocation_start() - prev_pc;
1767 EnterComment("NoComment", delta);
1768 }
1769 }
1770}
1771
1772
1773void OldSpace::ReportStatistics() {
1774 int pct = Available() * 100 / Capacity();
1775 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
1776 Capacity(), Waste(), Available(), pct);
1777
1778 // Report remembered set statistics.
1779 int rset_marked_pointers = 0;
1780 int rset_marked_arrays = 0;
1781 int rset_marked_array_elements = 0;
1782 int cross_gen_pointers = 0;
1783 int cross_gen_array_elements = 0;
1784
1785 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
1786 while (page_it.has_next()) {
1787 Page* p = page_it.next();
1788
1789 for (Address rset_addr = p->RSetStart();
1790 rset_addr < p->RSetEnd();
1791 rset_addr += kIntSize) {
1792 int rset = Memory::int_at(rset_addr);
1793 if (rset != 0) {
1794 // Bits were set
1795 int intoff = rset_addr - p->address();
1796 int bitoff = 0;
1797 for (; bitoff < kBitsPerInt; ++bitoff) {
1798 if ((rset & (1 << bitoff)) != 0) {
1799 int bitpos = intoff*kBitsPerByte + bitoff;
1800 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
1801 Object** obj = reinterpret_cast<Object**>(slot);
1802 if (*obj == Heap::fixed_array_map()) {
1803 rset_marked_arrays++;
1804 FixedArray* fa = FixedArray::cast(HeapObject::FromAddress(slot));
1805
1806 rset_marked_array_elements += fa->length();
1807 // Manually inline FixedArray::IterateBody
1808 Address elm_start = slot + FixedArray::kHeaderSize;
1809 Address elm_stop = elm_start + fa->length() * kPointerSize;
1810 for (Address elm_addr = elm_start;
1811 elm_addr < elm_stop; elm_addr += kPointerSize) {
1812 // Filter non-heap-object pointers
1813 Object** elm_p = reinterpret_cast<Object**>(elm_addr);
1814 if (Heap::InNewSpace(*elm_p))
1815 cross_gen_array_elements++;
1816 }
1817 } else {
1818 rset_marked_pointers++;
1819 if (Heap::InNewSpace(*obj))
1820 cross_gen_pointers++;
1821 }
1822 }
1823 }
1824 }
1825 }
1826 }
1827
1828 pct = rset_marked_pointers == 0 ?
1829 0 : cross_gen_pointers * 100 / rset_marked_pointers;
1830 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
1831 rset_marked_pointers, cross_gen_pointers, pct);
1832 PrintF(" rset_marked arrays %d, ", rset_marked_arrays);
1833 PrintF(" elements %d, ", rset_marked_array_elements);
1834 pct = rset_marked_array_elements == 0 ? 0
1835 : cross_gen_array_elements * 100 / rset_marked_array_elements;
1836 PrintF(" pointers to new space %d (%%%d)\n", cross_gen_array_elements, pct);
1837 PrintF(" total rset-marked bits %d\n",
1838 (rset_marked_pointers + rset_marked_arrays));
1839 pct = (rset_marked_pointers + rset_marked_array_elements) == 0 ? 0
1840 : (cross_gen_pointers + cross_gen_array_elements) * 100 /
1841 (rset_marked_pointers + rset_marked_array_elements);
1842 PrintF(" total rset pointers %d, true cross generation ones %d (%%%d)\n",
1843 (rset_marked_pointers + rset_marked_array_elements),
1844 (cross_gen_pointers + cross_gen_array_elements),
1845 pct);
1846
1847 ClearHistograms();
1848 HeapObjectIterator obj_it(this);
1849 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
1850 ReportHistogram(true);
1851}
1852
1853
1854// Dump the range of remembered set words between [start, end) corresponding
1855// to the pointers starting at object_p. The allocation_top is an object
1856// pointer which should not be read past. This is important for large object
1857// pages, where some bits in the remembered set range do not correspond to
1858// allocated addresses.
1859static void PrintRSetRange(Address start, Address end, Object** object_p,
1860 Address allocation_top) {
1861 Address rset_address = start;
1862
1863 // If the range starts on on odd numbered word (eg, for large object extra
1864 // remembered set ranges), print some spaces.
1865 if ((reinterpret_cast<uint32_t>(start) / kIntSize) % 2 == 1) {
1866 PrintF(" ");
1867 }
1868
1869 // Loop over all the words in the range.
1870 while (rset_address < end) {
1871 uint32_t rset_word = Memory::uint32_at(rset_address);
1872 int bit_position = 0;
1873
1874 // Loop over all the bits in the word.
1875 while (bit_position < kBitsPerInt) {
1876 if (object_p == reinterpret_cast<Object**>(allocation_top)) {
1877 // Print a bar at the allocation pointer.
1878 PrintF("|");
1879 } else if (object_p > reinterpret_cast<Object**>(allocation_top)) {
1880 // Do not dereference object_p past the allocation pointer.
1881 PrintF("#");
1882 } else if ((rset_word & (1 << bit_position)) == 0) {
1883 // Print a dot for zero bits.
1884 PrintF(".");
1885 } else if (Heap::InNewSpace(*object_p)) {
1886 // Print an X for one bits for pointers to new space.
1887 PrintF("X");
1888 } else {
1889 // Print a circle for one bits for pointers to old space.
1890 PrintF("o");
1891 }
1892
1893 // Print a space after every 8th bit except the last.
1894 if (bit_position % 8 == 7 && bit_position != (kBitsPerInt - 1)) {
1895 PrintF(" ");
1896 }
1897
1898 // Advance to next bit.
1899 bit_position++;
1900 object_p++;
1901 }
1902
1903 // Print a newline after every odd numbered word, otherwise a space.
1904 if ((reinterpret_cast<uint32_t>(rset_address) / kIntSize) % 2 == 1) {
1905 PrintF("\n");
1906 } else {
1907 PrintF(" ");
1908 }
1909
1910 // Advance to next remembered set word.
1911 rset_address += kIntSize;
1912 }
1913}
1914
1915
1916void PagedSpace::DoPrintRSet(const char* space_name) {
1917 PageIterator it(this, PageIterator::PAGES_IN_USE);
1918 while (it.has_next()) {
1919 Page* p = it.next();
1920 PrintF("%s page 0x%x:\n", space_name, p);
1921 PrintRSetRange(p->RSetStart(), p->RSetEnd(),
1922 reinterpret_cast<Object**>(p->ObjectAreaStart()),
1923 p->AllocationTop());
1924 PrintF("\n");
1925 }
1926}
1927
1928
1929void OldSpace::PrintRSet() { DoPrintRSet("old"); }
1930#endif
1931
1932// -----------------------------------------------------------------------------
1933// MapSpace implementation
1934
1935void MapSpace::PrepareForMarkCompact(bool will_compact) {
1936 if (will_compact) {
1937 // Reset relocation info.
1938 MCResetRelocationInfo();
1939
1940 // Initialize map index entry.
1941 int page_count = 0;
1942 PageIterator it(this, PageIterator::ALL_PAGES);
1943 while (it.has_next()) {
1944 ASSERT_MAP_PAGE_INDEX(page_count);
1945
1946 Page* p = it.next();
1947 ASSERT(p->mc_page_index == page_count);
1948
1949 page_addresses_[page_count++] = p->address();
1950 }
1951
1952 // During a compacting collection, everything in the space is considered
1953 // 'available' (set by the call to MCResetRelocationInfo) and we will
1954 // rediscover live and wasted bytes during the collection.
1955 ASSERT(Available() == Capacity());
1956 } else {
1957 // During a non-compacting collection, everything below the linear
1958 // allocation pointer except wasted top-of-page blocks is considered
1959 // allocated and we will rediscover available bytes during the
1960 // collection.
1961 accounting_stats_.AllocateBytes(free_list_.available());
1962 }
1963
kasper.lund7276f142008-07-30 08:49:36 +00001964 // Clear the free list before a full GC---it will be rebuilt afterward.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001965 free_list_.Reset();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001966}
1967
1968
1969void MapSpace::MCCommitRelocationInfo() {
1970 // Update fast allocation info.
1971 allocation_info_.top = mc_forwarding_info_.top;
1972 allocation_info_.limit = mc_forwarding_info_.limit;
kasper.lund7276f142008-07-30 08:49:36 +00001973 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001974
1975 // The space is compacted and we haven't yet wasted any space.
1976 ASSERT(Waste() == 0);
1977
1978 // Update allocation_top of each page in use and compute waste.
1979 int computed_size = 0;
1980 PageIterator it(this, PageIterator::PAGES_USED_BY_MC);
1981 while (it.has_next()) {
1982 Page* page = it.next();
1983 Address page_top = page->AllocationTop();
1984 computed_size += page_top - page->ObjectAreaStart();
1985 if (it.has_next()) {
1986 accounting_stats_.WasteBytes(page->ObjectAreaEnd() - page_top);
1987 }
1988 }
1989
1990 // Make sure the computed size - based on the used portion of the
1991 // pages in use - matches the size we adjust during allocation.
1992 ASSERT(computed_size == Size());
1993}
1994
1995
kasper.lund7276f142008-07-30 08:49:36 +00001996// Slow case for normal allocation. Try in order: (1) allocate in the next
1997// page in the space, (2) allocate off the space's free list, (3) expand the
1998// space, (4) fail.
1999HeapObject* MapSpace::SlowAllocateRaw(int size_in_bytes) {
2000 // Linear allocation in this space has failed. If there is another page
2001 // in the space, move to that page and allocate there. This allocation
2002 // should succeed.
2003 Page* current_page = TopPageOf(allocation_info_);
2004 if (current_page->next_page()->is_valid()) {
2005 return AllocateInNextPage(current_page, size_in_bytes);
2006 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002007
kasper.lund7276f142008-07-30 08:49:36 +00002008 // There is no next page in this space. Try free list allocation. The
2009 // map space free list implicitly assumes that all free blocks are map
2010 // sized.
2011 if (size_in_bytes == Map::kSize) {
2012 Object* result = free_list_.Allocate();
2013 if (!result->IsFailure()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002014 accounting_stats_.AllocateBytes(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002015 return HeapObject::cast(result);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002016 }
2017 }
kasper.lund7276f142008-07-30 08:49:36 +00002018
2019 // Free list allocation failed and there is no next page. Try to expand
2020 // the space and allocate in the new next page.
2021 ASSERT(!current_page->next_page()->is_valid());
2022 if (Expand(current_page)) {
2023 return AllocateInNextPage(current_page, size_in_bytes);
2024 }
2025
2026 // Finally, fail.
2027 return NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002028}
2029
2030
kasper.lund7276f142008-07-30 08:49:36 +00002031// Move to the next page (there is assumed to be one) and allocate there.
2032// The top of page block is always wasted, because it is too small to hold a
2033// map.
2034HeapObject* MapSpace::AllocateInNextPage(Page* current_page,
2035 int size_in_bytes) {
2036 ASSERT(current_page->next_page()->is_valid());
2037 ASSERT(current_page->ObjectAreaEnd() - allocation_info_.top == kPageExtra);
2038 accounting_stats_.WasteBytes(kPageExtra);
2039 SetAllocationInfo(&allocation_info_, current_page->next_page());
2040 return AllocateLinearly(&allocation_info_, size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002041}
2042
2043
2044#ifdef DEBUG
2045// We do not assume that the PageIterator works, because it depends on the
2046// invariants we are checking during verification.
2047void MapSpace::Verify() {
2048 // The allocation pointer should be valid, and it should be in a page in the
2049 // space.
kasper.lund7276f142008-07-30 08:49:36 +00002050 ASSERT(allocation_info_.VerifyPagedAllocation());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002051 Page* top_page = Page::FromAllocationTop(allocation_info_.top);
2052 ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
2053
2054 // Loop over all the pages.
2055 bool above_allocation_top = false;
2056 Page* current_page = first_page_;
2057 while (current_page->is_valid()) {
2058 if (above_allocation_top) {
2059 // We don't care what's above the allocation top.
2060 } else {
2061 // Unless this is the last page in the space containing allocated
2062 // objects, the allocation top should be at a constant offset from the
2063 // object area end.
2064 Address top = current_page->AllocationTop();
2065 if (current_page == top_page) {
2066 ASSERT(top == allocation_info_.top);
2067 // The next page will be above the allocation top.
2068 above_allocation_top = true;
2069 } else {
2070 ASSERT(top == current_page->ObjectAreaEnd() - kPageExtra);
2071 }
2072
2073 // It should be packed with objects from the bottom to the top.
2074 Address current = current_page->ObjectAreaStart();
2075 while (current < top) {
2076 HeapObject* object = HeapObject::FromAddress(current);
2077
2078 // The first word should be a map, and we expect all map pointers to
2079 // be in map space.
2080 Map* map = object->map();
2081 ASSERT(map->IsMap());
2082 ASSERT(Heap::map_space()->Contains(map));
2083
2084 // The object should be a map or a byte array.
2085 ASSERT(object->IsMap() || object->IsByteArray());
2086
2087 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002088 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002089
2090 // All the interior pointers should be contained in the heap and
2091 // have their remembered set bits set if they point to new space.
2092 VerifyPointersAndRSetVisitor visitor;
2093 int size = object->Size();
2094 object->IterateBody(map->instance_type(), size, &visitor);
2095
2096 current += size;
2097 }
2098
2099 // The allocation pointer should not be in the middle of an object.
2100 ASSERT(current == top);
2101 }
2102
2103 current_page = current_page->next_page();
2104 }
2105}
2106
2107
2108void MapSpace::ReportStatistics() {
2109 int pct = Available() * 100 / Capacity();
2110 PrintF(" capacity: %d, waste: %d, available: %d, %%%d\n",
2111 Capacity(), Waste(), Available(), pct);
2112
2113 // Report remembered set statistics.
2114 int rset_marked_pointers = 0;
2115 int cross_gen_pointers = 0;
2116
2117 PageIterator page_it(this, PageIterator::PAGES_IN_USE);
2118 while (page_it.has_next()) {
2119 Page* p = page_it.next();
2120
2121 for (Address rset_addr = p->RSetStart();
2122 rset_addr < p->RSetEnd();
2123 rset_addr += kIntSize) {
2124 int rset = Memory::int_at(rset_addr);
2125 if (rset != 0) {
2126 // Bits were set
2127 int intoff = rset_addr - p->address();
2128 int bitoff = 0;
2129 for (; bitoff < kBitsPerInt; ++bitoff) {
2130 if ((rset & (1 << bitoff)) != 0) {
2131 int bitpos = intoff*kBitsPerByte + bitoff;
2132 Address slot = p->OffsetToAddress(bitpos << kObjectAlignmentBits);
2133 Object** obj = reinterpret_cast<Object**>(slot);
2134 rset_marked_pointers++;
2135 if (Heap::InNewSpace(*obj))
2136 cross_gen_pointers++;
2137 }
2138 }
2139 }
2140 }
2141 }
2142
2143 pct = rset_marked_pointers == 0 ?
2144 0 : cross_gen_pointers * 100 / rset_marked_pointers;
2145 PrintF(" rset-marked pointers %d, to-new-space %d (%%%d)\n",
2146 rset_marked_pointers, cross_gen_pointers, pct);
2147
2148 ClearHistograms();
2149 HeapObjectIterator obj_it(this);
2150 while (obj_it.has_next()) { CollectHistogramInfo(obj_it.next()); }
2151 ReportHistogram(false);
2152}
2153
2154
2155void MapSpace::PrintRSet() { DoPrintRSet("map"); }
2156#endif
2157
2158
2159// -----------------------------------------------------------------------------
2160// LargeObjectIterator
2161
2162LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space) {
2163 current_ = space->first_chunk_;
2164 size_func_ = NULL;
2165}
2166
2167
2168LargeObjectIterator::LargeObjectIterator(LargeObjectSpace* space,
2169 HeapObjectCallback size_func) {
2170 current_ = space->first_chunk_;
2171 size_func_ = size_func;
2172}
2173
2174
2175HeapObject* LargeObjectIterator::next() {
2176 ASSERT(has_next());
2177 HeapObject* object = current_->GetObject();
2178 current_ = current_->next();
2179 return object;
2180}
2181
2182
2183// -----------------------------------------------------------------------------
2184// LargeObjectChunk
2185
2186LargeObjectChunk* LargeObjectChunk::New(int size_in_bytes,
kasper.lund7276f142008-07-30 08:49:36 +00002187 size_t* chunk_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002188 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002189 size_t requested = ChunkSizeFor(size_in_bytes);
kasper.lund7276f142008-07-30 08:49:36 +00002190 void* mem = MemoryAllocator::AllocateRawMemory(requested,
2191 chunk_size,
2192 executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002193 if (mem == NULL) return NULL;
2194 LOG(NewEvent("LargeObjectChunk", mem, *chunk_size));
2195 if (*chunk_size < requested) {
2196 MemoryAllocator::FreeRawMemory(mem, *chunk_size);
2197 LOG(DeleteEvent("LargeObjectChunk", mem));
2198 return NULL;
2199 }
2200 return reinterpret_cast<LargeObjectChunk*>(mem);
2201}
2202
2203
2204int LargeObjectChunk::ChunkSizeFor(int size_in_bytes) {
2205 int os_alignment = OS::AllocateAlignment();
2206 if (os_alignment < Page::kPageSize)
2207 size_in_bytes += (Page::kPageSize - os_alignment);
2208 return size_in_bytes + Page::kObjectStartOffset;
2209}
2210
2211// -----------------------------------------------------------------------------
2212// LargeObjectSpace
2213
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002214LargeObjectSpace::LargeObjectSpace(AllocationSpace id)
2215 : Space(id, NOT_EXECUTABLE), // Managed on a per-allocation basis
kasper.lund7276f142008-07-30 08:49:36 +00002216 first_chunk_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002217 size_(0),
2218 page_count_(0) {}
2219
2220
2221bool LargeObjectSpace::Setup() {
2222 first_chunk_ = NULL;
2223 size_ = 0;
2224 page_count_ = 0;
2225 return true;
2226}
2227
2228
2229void LargeObjectSpace::TearDown() {
2230 while (first_chunk_ != NULL) {
2231 LargeObjectChunk* chunk = first_chunk_;
2232 first_chunk_ = first_chunk_->next();
2233 LOG(DeleteEvent("LargeObjectChunk", chunk->address()));
2234 MemoryAllocator::FreeRawMemory(chunk->address(), chunk->size());
2235 }
2236
2237 size_ = 0;
2238 page_count_ = 0;
2239}
2240
2241
2242Object* LargeObjectSpace::AllocateRawInternal(int requested_size,
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002243 int object_size,
2244 Executability executable) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002245 ASSERT(0 < object_size && object_size <= requested_size);
2246 size_t chunk_size;
2247 LargeObjectChunk* chunk =
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002248 LargeObjectChunk::New(requested_size, &chunk_size, executable);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002249 if (chunk == NULL) {
kasper.lund7276f142008-07-30 08:49:36 +00002250 return Failure::RetryAfterGC(requested_size, identity());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002251 }
2252
2253 size_ += chunk_size;
2254 page_count_++;
2255 chunk->set_next(first_chunk_);
2256 chunk->set_size(chunk_size);
2257 first_chunk_ = chunk;
2258
2259 // Set the object address and size in the page header and clear its
2260 // remembered set.
2261 Page* page = Page::FromAddress(RoundUp(chunk->address(), Page::kPageSize));
2262 Address object_address = page->ObjectAreaStart();
2263 // Clear the low order bit of the second word in the page to flag it as a
2264 // large object page. If the chunk_size happened to be written there, its
2265 // low order bit should already be clear.
2266 ASSERT((chunk_size & 0x1) == 0);
2267 page->is_normal_page &= ~0x1;
2268 page->ClearRSet();
2269 int extra_bytes = requested_size - object_size;
2270 if (extra_bytes > 0) {
2271 // The extra memory for the remembered set should be cleared.
2272 memset(object_address + object_size, 0, extra_bytes);
2273 }
2274
2275 return HeapObject::FromAddress(object_address);
2276}
2277
2278
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002279Object* LargeObjectSpace::AllocateRawCode(int size_in_bytes) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002280 ASSERT(0 < size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002281 return AllocateRawInternal(size_in_bytes,
2282 size_in_bytes,
2283 EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002284}
2285
2286
2287Object* LargeObjectSpace::AllocateRawFixedArray(int size_in_bytes) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002288 ASSERT(0 < size_in_bytes);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002289 int extra_rset_bytes = ExtraRSetBytesFor(size_in_bytes);
ager@chromium.org9258b6b2008-09-11 09:11:10 +00002290 return AllocateRawInternal(size_in_bytes + extra_rset_bytes,
2291 size_in_bytes,
2292 NOT_EXECUTABLE);
2293}
2294
2295
2296Object* LargeObjectSpace::AllocateRaw(int size_in_bytes) {
2297 ASSERT(0 < size_in_bytes);
2298 return AllocateRawInternal(size_in_bytes,
2299 size_in_bytes,
2300 NOT_EXECUTABLE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002301}
2302
2303
2304// GC support
2305Object* LargeObjectSpace::FindObject(Address a) {
2306 for (LargeObjectChunk* chunk = first_chunk_;
2307 chunk != NULL;
2308 chunk = chunk->next()) {
2309 Address chunk_address = chunk->address();
2310 if (chunk_address <= a && a < chunk_address + chunk->size()) {
2311 return chunk->GetObject();
2312 }
2313 }
2314 return Failure::Exception();
2315}
2316
2317
2318void LargeObjectSpace::ClearRSet() {
2319 ASSERT(Page::is_rset_in_use());
2320
2321 LargeObjectIterator it(this);
2322 while (it.has_next()) {
2323 HeapObject* object = it.next();
2324 // We only have code, sequential strings, or fixed arrays in large
2325 // object space, and only fixed arrays need remembered set support.
2326 if (object->IsFixedArray()) {
2327 // Clear the normal remembered set region of the page;
2328 Page* page = Page::FromAddress(object->address());
2329 page->ClearRSet();
2330
2331 // Clear the extra remembered set.
2332 int size = object->Size();
2333 int extra_rset_bytes = ExtraRSetBytesFor(size);
2334 memset(object->address() + size, 0, extra_rset_bytes);
2335 }
2336 }
2337}
2338
2339
2340void LargeObjectSpace::IterateRSet(ObjectSlotCallback copy_object_func) {
2341 ASSERT(Page::is_rset_in_use());
2342
2343 LargeObjectIterator it(this);
2344 while (it.has_next()) {
2345 // We only have code, sequential strings, or fixed arrays in large
2346 // object space, and only fixed arrays can possibly contain pointers to
2347 // the young generation.
2348 HeapObject* object = it.next();
2349 if (object->IsFixedArray()) {
2350 // Iterate the normal page remembered set range.
2351 Page* page = Page::FromAddress(object->address());
2352 Address object_end = object->address() + object->Size();
2353 Heap::IterateRSetRange(page->ObjectAreaStart(),
2354 Min(page->ObjectAreaEnd(), object_end),
2355 page->RSetStart(),
2356 copy_object_func);
2357
2358 // Iterate the extra array elements.
2359 if (object_end > page->ObjectAreaEnd()) {
2360 Heap::IterateRSetRange(page->ObjectAreaEnd(), object_end,
2361 object_end, copy_object_func);
2362 }
2363 }
2364 }
2365}
2366
2367
2368void LargeObjectSpace::FreeUnmarkedObjects() {
2369 LargeObjectChunk* previous = NULL;
2370 LargeObjectChunk* current = first_chunk_;
2371 while (current != NULL) {
2372 HeapObject* object = current->GetObject();
kasper.lund7276f142008-07-30 08:49:36 +00002373 if (object->IsMarked()) {
2374 object->ClearMark();
2375 MarkCompactCollector::tracer()->decrement_marked_count();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002376 previous = current;
2377 current = current->next();
2378 } else {
2379 Address chunk_address = current->address();
2380 size_t chunk_size = current->size();
2381
2382 // Cut the chunk out from the chunk list.
2383 current = current->next();
2384 if (previous == NULL) {
2385 first_chunk_ = current;
2386 } else {
2387 previous->set_next(current);
2388 }
2389
2390 // Free the chunk.
2391 if (object->IsCode()) {
2392 LOG(CodeDeleteEvent(object->address()));
2393 }
2394 size_ -= chunk_size;
2395 page_count_--;
2396 MemoryAllocator::FreeRawMemory(chunk_address, chunk_size);
2397 LOG(DeleteEvent("LargeObjectChunk", chunk_address));
2398 }
2399 }
2400}
2401
2402
2403bool LargeObjectSpace::Contains(HeapObject* object) {
2404 Address address = object->address();
2405 Page* page = Page::FromAddress(address);
2406
2407 SLOW_ASSERT(!page->IsLargeObjectPage()
2408 || !FindObject(address)->IsFailure());
2409
2410 return page->IsLargeObjectPage();
2411}
2412
2413
2414#ifdef DEBUG
2415// We do not assume that the large object iterator works, because it depends
2416// on the invariants we are checking during verification.
2417void LargeObjectSpace::Verify() {
2418 for (LargeObjectChunk* chunk = first_chunk_;
2419 chunk != NULL;
2420 chunk = chunk->next()) {
2421 // Each chunk contains an object that starts at the large object page's
2422 // object area start.
2423 HeapObject* object = chunk->GetObject();
2424 Page* page = Page::FromAddress(object->address());
2425 ASSERT(object->address() == page->ObjectAreaStart());
2426
2427 // The first word should be a map, and we expect all map pointers to be
2428 // in map space.
2429 Map* map = object->map();
2430 ASSERT(map->IsMap());
2431 ASSERT(Heap::map_space()->Contains(map));
2432
2433 // We have only code, sequential strings, fixed arrays, and byte arrays
2434 // in large object space.
2435 ASSERT(object->IsCode() || object->IsSeqString()
2436 || object->IsFixedArray() || object->IsByteArray());
2437
2438 // The object itself should look OK.
mads.s.ager@gmail.com9a4089a2008-09-01 08:55:01 +00002439 object->Verify();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002440
2441 // Byte arrays and strings don't have interior pointers.
2442 if (object->IsCode()) {
2443 VerifyPointersVisitor code_visitor;
2444 Code::cast(object)->ConvertICTargetsFromAddressToObject();
2445 object->IterateBody(map->instance_type(),
2446 object->Size(),
2447 &code_visitor);
2448 Code::cast(object)->ConvertICTargetsFromObjectToAddress();
2449 } else if (object->IsFixedArray()) {
2450 // We loop over fixed arrays ourselves, rather then using the visitor,
2451 // because the visitor doesn't support the start/offset iteration
2452 // needed for IsRSetSet.
2453 FixedArray* array = FixedArray::cast(object);
2454 for (int j = 0; j < array->length(); j++) {
2455 Object* element = array->get(j);
2456 if (element->IsHeapObject()) {
2457 HeapObject* element_object = HeapObject::cast(element);
2458 ASSERT(Heap::Contains(element_object));
2459 ASSERT(element_object->map()->IsMap());
2460 if (Heap::InNewSpace(element_object)) {
2461 ASSERT(Page::IsRSetSet(object->address(),
2462 FixedArray::kHeaderSize + j * kPointerSize));
2463 }
2464 }
2465 }
2466 }
2467 }
2468}
2469
2470
2471void LargeObjectSpace::Print() {
2472 LargeObjectIterator it(this);
2473 while (it.has_next()) {
2474 it.next()->Print();
2475 }
2476}
2477
2478
2479void LargeObjectSpace::ReportStatistics() {
2480 PrintF(" size: %d\n", size_);
2481 int num_objects = 0;
2482 ClearHistograms();
2483 LargeObjectIterator it(this);
2484 while (it.has_next()) {
2485 num_objects++;
2486 CollectHistogramInfo(it.next());
2487 }
2488
2489 PrintF(" number of objects %d\n", num_objects);
2490 if (num_objects > 0) ReportHistogram(false);
2491}
2492
2493
2494void LargeObjectSpace::CollectCodeStatistics() {
2495 LargeObjectIterator obj_it(this);
2496 while (obj_it.has_next()) {
2497 HeapObject* obj = obj_it.next();
2498 if (obj->IsCode()) {
2499 Code* code = Code::cast(obj);
2500 code_kind_statistics[code->kind()] += code->Size();
2501 }
2502 }
2503}
2504
2505
2506void LargeObjectSpace::PrintRSet() {
2507 LargeObjectIterator it(this);
2508 while (it.has_next()) {
2509 HeapObject* object = it.next();
2510 if (object->IsFixedArray()) {
2511 Page* page = Page::FromAddress(object->address());
2512
2513 Address allocation_top = object->address() + object->Size();
2514 PrintF("large page 0x%x:\n", page);
2515 PrintRSetRange(page->RSetStart(), page->RSetEnd(),
2516 reinterpret_cast<Object**>(object->address()),
2517 allocation_top);
2518 int extra_array_bytes = object->Size() - Page::kObjectAreaSize;
2519 int extra_rset_bits = RoundUp(extra_array_bytes / kPointerSize,
2520 kBitsPerInt);
2521 PrintF("------------------------------------------------------------"
2522 "-----------\n");
2523 PrintRSetRange(allocation_top,
2524 allocation_top + extra_rset_bits / kBitsPerByte,
2525 reinterpret_cast<Object**>(object->address()
2526 + Page::kObjectAreaSize),
2527 allocation_top);
2528 PrintF("\n");
2529 }
2530 }
2531}
2532#endif // DEBUG
2533
2534} } // namespace v8::internal